Keyboard Game

Now you are going to create a game, in which you will use the keyboard to move a player around the screen.


Demo:


Live Demo (Trinket Replacement)

Use W A S D to move the player.


Tasks:


1. Set a variable to represent the player's starting position

# player position
x = size[0] // 2
y = size[1] // 2

2. Add colour variables

# Colours
RED = pygame.color.Color('#FF8080')
BLUE = pygame.color.Color('#8080FF')
WHITE = pygame.color.Color('#FFFFFF')
BLACK = pygame.color.Color('#000000')

3. Create the game loop and background colour

# Game Loop
done = False
while not done:
    screen.fill(BLACK)
    keys = pygame.key.get_pressed()

    # Player movement
    if keys[pygame.K_w]:
        y -=1

    #draw player
    pygame.draw.circle(screen, RED, [x,y], 6)
    pygame.display.flip()

    #events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
    clock.tick(72)
pygame.quit()

Challenges:


1. Change the default colours

2. Change the default colour of the background

3. Add full movement, when pressed w, s, a, d should move up, down, left, right respectively


Solution:


If the embed is blocked, open directly: Open on YouTube

Python Editor

#000000

Output

Loading Python runtime...