Pygame from start 1

Here is a new series of tutorials for pygame starting from the very skratch.

Index of Pygame First Game

Let’s show a simple sprite here.

We first:

  • define a class that create a Surface object (a little piece of rectangle) and we colour it
  • then we create a group from pygame.sprite.Group class to hold all the images or surfaces (1 for now)
  • then we create an istance of Player called player and we add it to group
  • then we draw the group on the surface

The result will be this little square that you can see into this picture below. Nothing fancy, but it all starts from here. Now you are ready to go to the next step: displaying an image and also animate it. That is why we used group.


'''
        TUTORIAL 01
        pygame
        absolute beginner

24.5.2020
Giovanni Gatto
'''


import pygame as pg
import sys


class Player(pg.sprite.Sprite):
    def __init__(self, px, py):
        super().__init__()
        self.image = pg.Surface([20, 20])
        self.image.fill((255, 255, 255))
        self.rect = self.image.get_rect()
        self.rect.topleft = [px, py]


pg.init()
clock = pg.time.Clock()


def window():
    screen = pg.display.set_mode((400, 400))
    pg.display.set_caption("Sprite animate")
    return screen

screen = window()
group = pg.sprite.Group()
player = Player(100, 100)
group.add(player)

loop = 1
while loop:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            loop = 0

    screen.fill((0, 0, 0))
    group.draw(screen)
    pg.display.flip()
    clock.tick(60)
pg.quit()
sys.exit()

 

Video

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.