The fourth episod of this serie, Pygame first game, we make little changes, that are important though. In fact we are trying to make to code readable, a fundamental thing if you want to make some code that is mantainable as the lines of code, inevitably, starts to spread all over the place. But, hey, you will see this at the end
Here is the code
# Pygame first gamet - tutorial 4 import pygame as pg import sys from glob import glob class Sprite(pg.sprite.Sprite): def __init__(self, pw, ph, action): "loads all the image that starts with 'action' in position pw, ph" super().__init__() self.pw = pw self.ph = ph self.current = 0 self.countframe = 0 self.action = action self.order_images() self.position_sprite() def order_images(self): "take the list of images (load_images()) and order them" lst = self.load_images() 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])]) self.sprites = [pg.image.load(x) for x in img] self.image = self.sprites[self.current] def load_images(self): "Load images that starts with action" folder = "cat\\" lst = glob(f"{folder}{self.action}*") return lst def position_sprite(self): self.rect = self.image.get_rect() self.rect.topleft = [self.pw, self.ph] def update(self): "This animate the sprite, it is called in the while loop by th update(sprite) function" self.countframe += 1 # the more is the number the more the animation is slow if self.countframe == 4: # restart the counter self.countframe = 0 # The new animation image is flipped after 4 frames self.current += 1 # check if the images of the animations are ended if self.current >= len(self.sprites): # if so it goes back to the initial image self.current = 0 # and now it shows the next image or the initial one self.image = self.sprites[self.current] def window(title): "Create the screen + title and the clock object for the frame" screen = pg.display.set_mode((400, 300)) pg.display.set_caption(title) return screen, pg.time.Clock() def quitbutton(): "Look for the key events" global loop for event in pg.event.get(): if event.type == pg.QUIT: loop = 0 def mk_sprite(action, w, h): "Create a group, the Sprite with some images" group = pg.sprite.Group() sprite = Sprite(w, h, action=action) group.add(sprite) return group def update(sprite): sprite.draw(screen) sprite.update() def clear_screen(): screen.fill((0, 64, 128)) def refresh_screen(): pg.display.flip() clock.tick(60) def update_screen(): quitbutton() clear_screen() # update(prun) # update(pwalk) for s in dsprites: update(dsprites(s)) refresh_screen() pg.init() screen, clock = window("Game") dsprites = { "pwalk" : mk_sprite("Walk", 100, 100), "prun" : mk_sprite("Run", 200, 100) } loop = 1 # ============== Where everything happens while loop: update_screen() # ======================== engine end === pg.quit() sys.exit()
The video
Subscribe to the newsletter for updates
Tkinter templates
My youtube channel
Twitter: @pythonprogrammi - python_pygame