Game Controls
So far, we’ve only used input
to ask for user input as text.
Now, we’ll use pygame to handle real-time keyboard and mouse input!
🔗 The Big Event
import pygame
import sys
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode([100,100])
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
print("Quit.")
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
print("Key press.")
elif event.type == pygame.KEYUP:
print("Key up.")
elif event.type == pygame.MOUSEBUTTONDOWN:
print("Key down.")
else:
print("Unknown.")
clock.tick(60) # 60 frames per second
🔗 Keyed Up
import pygame
import sys
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode([100,100])
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
print("Key press.")
if event.key == pygame.K_SPACE:
print("Space key pressed!")
elif event.key == pygame.K_w:
print("w key pressed!")
elif event.key == pygame.K_a:
print("a key pressed!")
elif event.key == pygame.K_s:
print("s key pressed!")
elif event.key == pygame.K_d:
print("d key pressed!")
else:
print("Unknown.")
clock.tick(60) # 60 frames per second
Challenge:
Can you make a game that tests how many total times the user can press the j
and/or k
keys in ten seconds?
Can you make it so that pressing other keys makes you loose points?
Hint: the frame rate is 60 frames per second, so how many times do you need to go through the outer loop?
Challenge:
Open back up your catimation.py
file… can you make the user control the movement of the cat image with the w
(up), a
(left), s
(down), and d
(right) keys?
🔗 Mousing Around
import pygame
import sys
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode([100,100])
while True:
for event in pygame.event.get():
if event.type == pygame.MOUSEMOTION:
x, y = event.pos
print("mouse now at", x, y)
elif event.type == pygame.MOUSEBUTTONDOWN:
print("Mouse button pressed")
elif event.type == pygame.MOUSEBUTTONUP:
print("Mouse button released")
else:
print("Unknown.")
clock.tick(60) # 60 frames per second
Challenge: Can you make a game that tests how far the user can move the mouse in ten seconds? You’ll want to calculate the distance moved relative to the last mouse position each time through the outer loop and add it to a running sum. Can you make it moving the mouse through the center of the screen loses you points? Can you draw a rectangle there so the user knows to avoid it?
- hint 1: the frame rate is 60 frames per second, so how many times do you need to go through the outer loop?
- hint 2: calculate the distance between two mouse positions
[x_1, y_1]
and[x_2, y_2]
as(x_1 - x_2) ** 2 + (y_1 - y_2) ** 2
.
Challenge:
Open back up your catimation.py
file… can you make the user control the movement of the cat image with the mouse?
First, just draw the cat at the position of the mouse cursor.
Then, if you want an extra challenge, have the cat chase the mouse!
🔗 Example - Cat clicker game
Here’s a full-featured game we made as part of the 2021 camp!
import pygame
import sys
import random
pygame.init()
screen = pygame.display.set_mode([400, 400])
pygame.display.set_caption("Click the cat!")
FPS = 30 # Frames per second
fps_clock = pygame.time.Clock()
# r g b
RED = [255, 0, 0]
WHITE = [255, 255, 255]
BLACK = [0, 0, 0]
cat_image = pygame.image.load("cat.png")
cat_rect = cat_image.get_rect()
cat_x = 100
cat_y = 200
cat_delta_x = 4
cat_clicks = 0
cat_attempted_clicks = 0
# run the game loop
while True:
cat_x = cat_x + cat_delta_x
if cat_x >= 350:
cat_delta_x = cat_delta_x * -1
elif cat_x <= 50:
cat_delta_x = cat_delta_x * -1
screen.fill(BLACK)
cat_rect.center = [cat_x, cat_y]
screen.blit(cat_image, cat_rect)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
cat_attempted_clicks += 1 # Increment attempted clicks!
x, y = event.pos
if x >= cat_rect.x and x <= (cat_rect.x + cat_rect.width): # check if cat's left side <= x <= cat's right side
if y >= cat_rect.y and y <= (cat_rect.y + cat_rect.height): # if y is greater than the bottom of the cat
cat_clicks = cat_clicks + 1
cat_delta_x = cat_delta_x * 1.25
cat_y = random.randint(0, 400)
print('Hit! Current hits:', cat_clicks)
if cat_clicks >= 10:
print('Congrats! You did it!')
print("Your final time was: ")
print(pygame.time.get_ticks())
print("Your accuracy was:", cat_clicks / cat_attempted_clicks)
pygame.quit()
sys.exit()
fps_clock.tick(FPS)