← All stepsBobgame: make a Python game

Step 9 of 12

Write player.py and draw Bob

Time to make Bob. Open bobgame/player.py

import pygame

from .settings import (
    ARROW_COLOR, BOB_RADIUS, BOB_SPEED, HAIR_COLOR, HEIGHT, SKIN_COLOR, WIDTH,
)


class Bob:
    def __init__(self) -> None:
        self.pos = pygame.Vector2(WIDTH / 2, HEIGHT / 2)
        self.facing = pygame.Vector2(0, -1)

    def draw(self, surface: pygame.Surface) -> None:
        center = (round(self.pos.x), round(self.pos.y))
        pygame.draw.circle(surface, SKIN_COLOR, center, BOB_RADIUS)
        # Hair: ring around the head plus a cap on the back half.
        pygame.draw.circle(surface, HAIR_COLOR, center, BOB_RADIUS, 4)
        back = self.pos - self.facing * (BOB_RADIUS * 0.35)
        pygame.draw.circle(
            surface, HAIR_COLOR, (round(back.x), round(back.y)), BOB_RADIUS * 0.6
        )

Bob is another class, another blueprint.

Now we need the game to make a Bob and draw him. Change game.py in three places

from .player import Bob

add that near the top, below import pygame. Then in __init__ add one line

        self.bob = Bob()

below self.clock = .... And in step draw him after the background is painted

        self.screen.fill(BG_COLOR)
        self.bob.draw(self.screen)
        pygame.display.flip()

The order matters. If we drew Bob first and then painted the background, we'd cover him up!

Run it again. You should see a round head with hair in the middle of the window. He's not moving yet, so let's fix that.