In this lesson, we will create a simple game using Pygame Zero. The player will control a character that needs to catch falling objects. The game will keep track of the player's score and the number of missed objects. The game will end when the player misses three objects.
First, let's import the required modules and set up the game window dimensions.
import pgzrun
import random
WIDTH = 800
HEIGHT = 600
Next, we will create the player character and position it at the bottom center of the screen. We will also create a list of objects that will fall from the top of the screen.
player = Actor("character")
player.pos = WIDTH // 2, HEIGHT - 90
objects = []
for _ in range(5):
obj = Actor("object")
obj.pos = random.randint(0, WIDTH), random.randint(-100, -10)
objects.append(obj)
We will create a background actor and position it at the center of the screen.
background = Actor("background", (WIDTH // 2, HEIGHT // 2))
We will create two variables to keep track of the player's score and the number of missed objects.
score = 0
missed = 0
The draw() function will display the game elements on the screen.
def draw():
First, we will clear the screen.
screen.clear()
Draw the background, player, and each falling object.
background.draw()
player.draw()
for obj in objects:
obj.draw()
Display the score and the number of missed objects.
screen.draw.text("Score: " + str(score), (10, 10), fontsize=30, color="white")
screen.draw.text("Missed: " + str(missed), (10, 50), fontsize=30, color="white")
If the player misses 3 objects, we will display a "Game Over!" message.
if missed >= 3:
screen.draw.text("Game Over!",(WIDTH // 2 - 100, HEIGHT // 2),fontsize=60,color="red")
The update() function handles the game logic.
def update():
Access global variables score and missed. Check if the player misses less than 3 objects.
global score, missed
if missed < 3:
Move the player left or right based on keyboard input.
if keyboard.left and player.left > 0:
player.x -= 8
if keyboard.right and player.right < WIDTH:
player.x += 8
Move each falling object down.
for obj in objects:
obj.y += 3
Check if an object reaches the bottom of the screen. If so, reset its position to the top and increment the number of missed objects.
if obj.top > HEIGHT:
obj.pos = random.randint(0, WIDTH), random.randint(-100, -10)
missed += 1
Check if the player collides with an object. If so, reset the object's position and increment the player's score.
if player.colliderect(obj):
obj.pos = random.randint(0, WIDTH), random.randint(-100, -10)
score += 1
Finally, we will call pgzrun.go() to start the game. Make sure it's always the last line of code in your program.
pgzrun.go()
Copyright © KX Technology Group, LLC. All Rights Reserved.