← All stepsBobgame: make a Python game

Step 10 of 12

Move Bob with W A S D

Add this update method to the Bob class in player.py, between __init__ and draw

    def update(self, dt: float, keys, mouse_pos) -> None:
        direction = pygame.Vector2(
            keys[pygame.K_d] - keys[pygame.K_a],
            keys[pygame.K_s] - keys[pygame.K_w],
        )
        if direction.length_squared() > 0:
            direction.normalize_ip()
        self.pos += direction * BOB_SPEED * dt
        self.pos.x = max(BOB_RADIUS, min(WIDTH - BOB_RADIUS, self.pos.x))
        self.pos.y = max(BOB_RADIUS, min(HEIGHT - BOB_RADIUS, self.pos.y))

keys is a list of every key on the keyboard, and each one is True if it's being held down or False if not. Python treats True as 1 and False as 0, so we can do maths with them.

The mouse_pos isn't used yet, we'll use it in the next step. In game.py we need to call update on every frame. Add this to step, right before the line that paints the background

        self.bob.update(dt, pygame.key.get_pressed(), pygame.mouse.get_pos())

pygame.key.get_pressed() hands over the list of keys and pygame.mouse.get_pos() gives the mouse position. Run the game and use W A S D. Bob should glide around and stop at the edges.