A Personal Zoo or A Little About Pygame - Part 1

    image
    For those who are not in the know: Pygame is a very, very good framework for developing games in the Python language. Moreover, not only work with 2D and 3D is supported, but you can also install binders to many popular graphic and physical engines if you wish. By the way, Pygame doesn’t need to be used specifically for games, you can also create programs with an unusual interface, for example, some kind of three-dimensional frontend to the database.
    So, in fact, I wanted to talk about the basic principles of working with this framework, you never know, maybe someone will come in handy :)

    Let's go!


    In order to access Pygame classes and methods, it must be initialized. By the way, the global game timer starts when the module is initialized, and the programmer, in turn, at any time can get the time in seconds from the very beginning of the initialization. Create a simple window:
    Copy Source | Copy HTML
    1. import pygame
    2. from pygame.locals import *
    3.  
    4. def init_window():
    5.     pygame.init()
    6.     window = pygame.display.set_mode((550, 480))
    7.     pygame.display.set_caption('My own little world')
    8.  
    9. def main():
    10.     init_window()
    11.  
    12. if __name__ == '__main__': main()

    I designed the code in a C-like manner, so it is easier to read. Actually, there is nothing to perceive so far :) First, we import the necessary modules (for sishnikov - describe the namespace), then initialize the framework, create a window with dimensions of 550 by 480 and give it the title “My own little world”.
    I think those who tried to run this code noticed that the window disappears immediately after the appearance. This is because we have not yet described a global infinite loop for receiving messages, so the window just has nothing to do. Correct this mistake:
    Copy Source | Copy HTML
    1. import sys
    2. import pygame
    3. from pygame.locals import *
    4.  
    5. def init_window():
    6.     pygame.init()
    7.     window = pygame.display.set_mode((550, 480))
    8.     pygame.display.set_caption('My own little world')
    9.  
    10. def input(events):
    11.     for event in events:
    12.         if (event.type == QUIT) or (event.type == KEYDOWN and event.key == K_ESCAPE):
    13.             sys.exit(0)
    14.         else:
    15.             pass
    16.  
    17. def action():
    18.     while 1:
    19.         input(pygame.event.get())
    20.  
    21. def main():
    22.     init_window()
    23.     action()
    24.  
    25. if __name__ == '__main__': main()

    As we can see, an endless cycle of receiving messages starts. If the message QUIT is transmitted (click on the cross of the window) or the ESCAPE button is pressed , the application terminates its work.
    But the window is empty, black, uninteresting. What would we do to draw something on it? First, give it a background . You can fill it with solid color or, strangely enough, just upload a picture of a suitable size and display it at the coordinates (0,0):
    Copy Source | Copy HTML
    1. import os
    2.  
    3. def load_image(name):
    4.     fullname = os.path.join('data', name) # Картинки у меня лежат в папке 'data'
    5.     try:
    6.         image = pygame.image.load(fullname)
    7.     except pygame.error, message: # Мало ли :)
    8.         print "Cannot load image:", name
    9.         raise SystemExit, message
    10.     image = image.convert() # Адаптируем картинку для отображения в игре. Если на ней есть альфа-канал - тогда convert_alpha()
    11.     return image, image.get_rect()
    12.  
    13. def draw_background():
    14.     screen = pygame.display.get_surface() # Получаем поверхность, на которой будем рисовать
    15.     background = pygame.Surface(screen.get_size()) # и ее размер
    16.     background = background.convert()
    17.     background.fill((0, 0, 0)) # заполняем цветом
    18.     screen.blit(background, (0, 0)) # рисуем заполненный одним цветом бэкграунд
    19.     back, back_rect = load_image("grass.jpg") # или загружаем картинку с травой
    20.     screen.blit(back, (0, 0)) # и рисуем ее
    21.     pygame.display.flip() # переключаем буфер экрана
    22.     return back
    23.  
    24. def main():
    25.     init_window()
    26.     bk = draw_background()
    27.     action()

    The most important lines here are screen = pygame.display.get_surface () , screen.blit (back, (0, 0)) and pygame.display.flip () . When working with Pygame, it is important to remember that drawing every time goes on some surface - surface . At the same time, such a thing as a backbuffer acts , that is, drawing goes in the screen buffer, and the flip () method, so to speak, “flips” the screen, displaying the changes that occurred in the buffer on the screen.

    Well, now let's add some living creatures to our small world. To do this, create an animal, for example, an elephant :) Just for starters, we will slightly rewrite our image upload function. Now I will explain why.
    Copy Source | Copy HTML
    1. def load_image(name, colorkey=None):
    2.     fullname = os.path.join('data', name)
    3.     try:
    4.         image = pygame.image.load(fullname)
    5.     except pygame.error, message:
    6.         print "Cannot load image:", name
    7.         raise SystemExit, message
    8.     image = image.convert()
    9.     if colorkey is not None:
    10.         if colorkey is -1:
    11.             colorkey = image.get_at((0,0))
    12.         image.set_colorkey(colorkey, RLEACCEL)
    13.     return image, image.get_rect()
    14.  
    15. class Animal(pygame.sprite.Sprite):
    16.     def __init__(self, img, cX, cY):
    17.         pygame.sprite.Sprite.__init__(self)
    18.         self.image, self.rect = load_image(img, -1)
    19.         screen = pygame.display.get_surface()
    20.         self.area = screen.get_rect()
    21.         self.cX = cX
    22.         self.cY = cY
    23.         self.coord = (cX, cY)
    24.         print"Animal spawned at", self.coord
    25.  
    26. class Elephant(Animal):
    27.     def __init__(self, cX, cY):
    28.         Animal.__init__(self, "Elephant.bmp", cX, cY)

    I foresee the indignant exclamations of “why bmp ??”. I will answer - for experience :) Because now we have acquired another skill - taking the color from the image by coordinates ( colorkey = image.get_at ((0,0)) ), we can make this color in the whole picture completely transparent ( image.set_colorkey (colorkey, RLEACCEL) )! Useful if you suddenly need to upload a picture without an alpha channel.

    pygame.sprite.Sprite is the standard pygame sprite class. For those who are not in the know: a sprite is a flat picture with a number of properties necessary for a game object. In particular, it can be made to move, taught all kinds of interactions, etc.

    And now all we need to do is launch an elephant into our jungle!
    Copy Source | Copy HTML
    1. def action(bk):
    2.     creatures_list = [] # Список со всем животными. Пригодится, если будем добавлять новых
    3.     screen = pygame.display.get_surface()
    4.     elephant = Elephant(10,10) # Помещаем слона по координатам х=10, у=10
    5.     creatures_list.append(elephant)
    6.     animals = pygame.sprite.RenderPlain(creatures_list) # Засовываем всех наших животных в класс RenderPlain для отображения спрайтов на экране
    7.  
    8.     while 1:
    9.         input(pygame.event.get())
    10.         screen.blit(bk, (0, 0))
    11.         animals.update() # Стандартный метод проверки, вдруг что-то изменилось. Пригодится для описания движения
    12.         animals.draw(screen)
    13.         pygame.display.flip()
    14.  
    15. def main():
    16.     init_window()
    17.     bk = draw_background()
    18.     action(bk)

    I agree that the above code needs optimization, in particular, do not kick the curve to draw the background, but in general, everything should be clear.

    And finally, a working screenshot of my little development, just an introduction to Pygame. The green contours around the pictures are the flaws of bmp processing, now I redraw everything under png. The grid is the simplest example of drawing using Pygame, I’ll talk about this next time. Ready to answer any questions and listen to criticism.




    Also popular now: