Pygame First Game – tutorial 2

Welcome to this second “episode” of this new serie about pygame that will be the main matter of this blog for the next period. Let’s see what we did in the first episode.

Index of Pygame First Game

'''
        TUTORIAL 01
        pygame
        absolute beginner

24.5.2020
Giovanni Gatto
'''


import pygame as pg
import sys
from glob import glob

class Player(pg.sprite.Sprite):
    def __init__(self, px, py, action):
        super().__init__()
        # self.image = pg.Surface([20, 20])
        # self.image.fill((255, 255, 255))
        # loads all the images in cat\ that startw with idle

        lst = glob("cat\\{}*".format(action))
        img = [f for f in lst if len(f) == len(lst[0])]

        img.extend([f for f in lst if len(f) != len(lst[0])])

        print(img)
        self.sprites = [pg.image.load(x) for x in img]
        self.current = 0
        self.image = self.sprites[self.current]
        self.rect = self.image.get_rect()
        self.rect.topleft = [px, py]
        self.wait = 0

    def update(self, pause=4):
        self.wait += 1
        if self.wait == pause:
            self.wait = 0
            self.current += 1
            if self.current >= len(self.sprites):
                self.current = 0
            self.image = self.sprites[self.current]


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


def window(title):
    screen = pg.display.set_mode((400, 400))
    pg.display.set_caption(title)
    return screen

screen = window("Game")
group = pg.sprite.Group()
player = Player(100, 100, action="Walk")
group.add(player)

loop = 1

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

    screen.fill((0, 64, 128))
    group.draw(screen)
    group.update(pause=2)
    pg.display.flip()
    clock.tick(60)


pg.quit()
sys.exit()

Video of pygame tutorial 2


Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

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.