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.
self.posis Bob's position. AVector2is a pair of numbers,x(how far across) andy(how far down). In games,(0, 0)is the top-left corner andygets bigger as you go down, which is the opposite of the maths you do at school. We start Bob in the middle of the window,WIDTH / 2across andHEIGHT / 2down.self.facingis the direction Bob looks. It is also aVector2, but this time think of it as an arrow with a length of 1 that points somewhere.(0, -1)means 0 across and 1 up (remember, up is negative), so he starts looking at the top of the screen.drawpaints Bob onto asurface(the canvas, in our case the window).pygame.draw.circletakes a canvas, a colour, a centre and a size.- First we draw a skin coloured circle. Then we draw a hair coloured circle with a
4on the end, which means "only draw the outline, 4 pixels thick". That gives a ring of hair. Lastly we draw a smaller hair circle slightly towards Bob's back. We find that spot by going from his centre in the opposite direction (the minus sign) of where he faces. From above, it looks like he has hair on the back of his head. round(...)turns a decimal like400.4into a whole number, because pixels can't be cut in half.
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.