Pygame Zero: Move the Box

This game allows the player to move a blue box around the screen using arrow keys. Below is a breakdown of the code:

1. Importing the Pygame Zero Module

The pgzrun module is used to run the game:

import pgzrun

2. Setting Up the Game Screen

The screen dimensions are defined as 300 pixels wide and 300 pixels high:

WIDTH = 300
HEIGHT = 300

3. Box Setup

The box is represented by a rectangle, positioned at the center of the screen. It is 30 pixels wide and 30 pixels tall:

box = Rect((WIDTH // 2 - 15, HEIGHT // 2 - 15), (30, 30))
  • Rect((WIDTH // 2 - 15, HEIGHT // 2 - 15), (30, 30)): Creates a rectangle at the center of the screen with specified dimensions.

4. Drawing the Game Screen

The draw() function clears the screen and draws the blue box:

def draw():
    screen.clear()
    screen.draw.filled_rect(box, "blue")
  • screen.clear(): Clears the screen before drawing new elements.
  • screen.draw.filled_rect(box, "blue"): Draws the blue box at its current position.

5. Updating the Game State

The update() function allows the player to move the box using arrow keys:

def update():
    if keyboard.left and box.left > 0:
        box.x -= 4
    if keyboard.right and box.right < WIDTH:
        box.x += 4
    if keyboard.up and box.top > 0:
        box.y -= 4
    if keyboard.down and box.bottom < HEIGHT:
        box.y += 4
  • keyboard.left: Moves the box left if the left arrow key is pressed and the box isn't at the left edge of the screen.
  • keyboard.right: Moves the box right if the right arrow key is pressed and the box isn't at the right edge of the screen.
  • keyboard.up: Moves the box up if the up arrow key is pressed and the box isn't at the top of the screen.
  • keyboard.down: Moves the box down if the down arrow key is pressed and the box isn't at the bottom of the screen.

6. Starting the Game

The game starts with the pgzrun.go() function, which runs the game loop:

pgzrun.go()