PyGame. Introduction

    PyGame. Introduction


    I had a chance to talk to this library somehow , which I would like to share with you, and leave a notch for myself, so as not to forget :) In this short, I hope, post, I will illustrate this by omitting some of the very most theoretical foundations (which described in the  documentation ), I will show the basic principles of working with the library.



    Task.

    Create a “game” space in which, using the arrow keys, you can move the object.

    Theory.

    Before posting the listings, I will focus on the methods used from the library modules, the description of which is taken from the office. documentation.

    Module image
    1. pygame.image.load (filename): return Surface
    As you might guess, the function loads a certain image and returns as a surface, a type with which pygame functions can already perform some operations (transform, reload, . delete, etc.)

    module surface
    2. Surface.blit (source, dest, area = None, 0 = special_flags)
    Renders a predetermined surface (source) over the base (surface), where dest - a tuple (x, y), kordinaty otrisvoki, area - (width, height) - dimensions of the source surface. At the expense of flags, to be honest, I did not understand yet))
    3. Surface.get_rect ()
    Returns a tuple of the form (x, y, width, height), where x, y are the coordinates of the upper left corner of the surface (Surface), width, height are its dimensions, respectively. Event

    module It allows you to interact with events and requests. In other words, any event in pygame, for example, a keystroke, is placed in a list consisting of Event objects. All these "event objects" are of a type that can be accessed through Event.type. 4. pygame.event.get () The get () method allows you to get a list of events. Module Rect module for working with tuples of type rect. 5. Rect.move (X, Y)







    Returns a new rect, in which the coordinates are offset, relative to the source, by the given X, Y, which can be a positive or negative integer.

    Practice.

    Taking into account the above, we get:
    1. # -*- coding: cp1251 -*-
    2. # Пример реализации движения при помощи pygame.

    3. from pygame import *
    4. import sys
    5. # Инициализируем загруженную библиотеку.
    6. init()

    7. # Создаем окно разрешением 640х480
    8. screen = display.set_mode((640, 480))

    9. # Устанавливаем название окна
    10. display.set_caption('example')

    11. # Загружаем фоновый рисунок, в формате:
    12. # jpg, png, gif(без анимации), bmp, pcx, tga(без сжатия), tif.
    13. background = image.load('background.bmp')

    14. # Отрисовываем рисунок в нашем окне
    15. screen.blit(background, (0, 0))

    16. # Создаем игровой объект
    17. class GameObj:
    18.     def __init__(self, img, x, y, step):
    19.         self.img = img # Картинка объекта
    20.         self.x = x # x, y - коодинаты начального положения
    21.         self.y = y
    22.         self.step = step # Шаг, на который будет смещаться объкт
    23.         self.pos = img.get_rect().move(x, y)
    24.     def _move(self, event):
    25.         if event.key == K_UP: #273 код клавиши вверх
    26.             self.pos = self.pos.move(0, -self.step)
    27.         if event.key == K_DOWN:
    28.             self.pos = self.pos.move(0, self.step)
    29.         if event.key == 276:
    30.             self.pos = self.pos.move(-self.step, 0)
    31.         if event.key == 275:
    32.             self.pos = self.pos.move(self.step, 0)
    33.        
    34. avatar = image.load('player.bmp')

    35. # Инициируем игровой объект
    36. x = GameObj(avatar, 320, 220, 10)

    37. # Рисуем картинку объекта, в его координатах
    38. screen.blit(x.img, x.pos)

    39. # Запускаем бесконечный цикл, чтобы окно не схлопнулось после появления :)
    40. while 1:
    41.     for i in event.get(): # Перебор в списке событий
    42.         if i.type == QUIT: # Обрабатываем событие шечка по крестику закрытия окна
    43.             sys.exit()
    44.         if i.type == KEYDOWN:
    45.             screen.blit(background, x.pos, x.pos)
    46.             x._move(i)
    47.             screen.blit(x.img, x.pos)
    48.     # Обновляем изображение в окне, чтобы изменения в нем стали видны
    49.     display.flip()


    Afterword.


    Actually that's all, briefly and angrily :) Having looked through a huge number of games laid out at the office. site, and having discovered real 3D crafts there - I was surprised and rejoiced at the same time)) Although I’m not going to conquer the game peaks, it’s nice that my favorite language is so multidimensional. If someone is interested in this topic, and I don’t lose the desire to record, then there will certainly be a continuation).

    Also popular now: