Pygame Zero: Click the Dot Game

This is a simple game where the player clicks on a randomly moving red dot to increase their score. Below is the breakdown of the code:

1. Importing Modules

The random module is used to generate random positions for the dot, and pgzrun is used to run the game:

import random
import pgzrun

2. Setting Up the Game Screen

The screen's dimensions are defined here, with both width and height set to 300 pixels:

WIDTH = 300
HEIGHT = 300

3. Dot Setup

The dot is represented by a rectangle that starts at the center of the screen:

dot = Rect((WIDTH // 2, HEIGHT // 2), (20, 20))
  • Rect((WIDTH // 2, HEIGHT // 2), (20, 20)): Creates a rectangle with a width and height of 20 pixels, positioned at the center of the screen.

4. Game Variables

The score variable tracks the player's score:

score = 0

5. Drawing the Game Screen

The draw() function clears the screen, draws the red dot, and displays the player's score:

def draw():
    screen.clear()
    screen.draw.filled_rect(dot, "red")
    screen.draw.text(f"Score: {score}", (10, 10), color="white", fontsize=20)
  • screen.clear(): Clears the screen before drawing new elements.
  • screen.draw.filled_rect(dot, "red"): Draws the dot as a red rectangle.
  • screen.draw.text(): Displays the current score at the top-left corner of the screen.

6. Moving the Dot

The move_dot() function moves the dot to a random position within the screen boundaries:

def move_dot():
    dot.x = random.randint(0, WIDTH - dot.width)
    dot.y = random.randint(0, HEIGHT - dot.height)
  • random.randint(0, WIDTH - dot.width): Ensures the dot stays within the horizontal boundaries.
  • random.randint(0, HEIGHT - dot.height): Ensures the dot stays within the vertical boundaries.

7. Handling Mouse Clicks

The on_mouse_down(pos) function checks if the dot is clicked and updates the score if it is:

def on_mouse_down(pos):
    global score
    if dot.collidepoint(pos):
        score += 1
        move_dot()
  • dot.collidepoint(pos): Checks if the mouse click position overlaps with the dot's position.
  • score += 1: Increases the score by 1 for each successful click.
  • move_dot(): Moves the dot to a new random position after it's clicked.

8. Scheduling Dot Movement

The dot moves to a new random position every second, using clock.schedule_interval():

clock.schedule_interval(move_dot, 1.0)
  • move_dot: The function to be executed.
  • 1.0: The interval in seconds between each execution.

9. Starting the Game

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

pgzrun.go()