How to design interactive terminal games using Pygame

Pygame is a Python library that allows us to design interactive 2D terminal games. It is equipped with modules and functions that enable handling graphics, sounds, and other aspects of game development very conveniently.

Key features

The key features of Pygame include:

  • Graphics: Pygame offers modules to help draw and manipulate different shapes, colors, and images and display them on the screen.

  • Sounds and music: Pygame enables us to add sound effects to our project that enhance the game’s interactivity.

  • Input handling: To ensure interactivity, Pygame helps handle the user input and manipulate it. This makes handling keyboard entries and mouse clicks very easy.

  • Font rendering: Pygame allows rendering fonts of different types, sizes, and colors to create more visually appealing programs.

Implementation of the Pygame program

In the game, a target box appears randomly within a window, and the player’s objective is to click the target. Upon successfully clicking the target, the player’s score increases, and a new target box spawns at another random position. The game loop continues indefinitely, with the player accumulating points by clicking on each new target.

The implementation of a simple Pygame program is shown below:

import pygame
import random
import sys

# Initialize the Pygame
pygame.init()

# Constants
WIDTH, HEIGHT = 800, 600
FPS = 60
TARGET_SIZE = 50

# Colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)

# Game variables
score = 0

# Create a Pygame window
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Click Game")
clock = pygame.time.Clock()

def spawn_target():
    """Spawn a new target at a random position."""
    x = random.randint(0, WIDTH - TARGET_SIZE)
    y = random.randint(0, HEIGHT - TARGET_SIZE)
    return pygame.Rect(x, y, TARGET_SIZE, TARGET_SIZE)

def draw_text(text, size, color, x, y):
    """Draw text on the screen."""
    font = pygame.font.Font(None, size)
    text_surface = font.render(text, True, color)
    text_rect = text_surface.get_rect(center=(x, y))
    screen.blit(text_surface, text_rect)

def main():
    global score

    target_rect = spawn_target()

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if target_rect and target_rect.collidepoint(event.pos):
                    score += 1
                    target_rect = spawn_target()  # Spawn a new target

        screen.fill(WHITE)

        # Draw the target
        if target_rect:
            pygame.draw.rect(screen, RED, target_rect)

        draw_text(f"Score: {score}", 36, RED, WIDTH // 2, 50)

        pygame.display.flip()
        clock.tick(FPS)

if __name__ == "__main__":
    main()
A simple game using Pygame

Code explanation

Here is the simple code explanation for more understanding:

  • Lines 1–3: We import important libraries.

  • Lines 6–18: We initialize the Pygame library, constants, colors for the game, and other variables.

  • Lines 21–23: We create the Pygame window with the specified dimensions, set the window caption, and create a clock object to control the frame rate.

  • Lines 25–29: The spawn_target function generates a new target rectangle at a random position and returns it.

  • Lines 31–36: The draw_text function draws text on the screen. It takes parameters like text, font size, color, and position.

  • Lines 38–62: The main function is the main game loop. It handles events, updates the screen, and manages the display. If the player clicks on the target, the score is incremented, and a new target is spawned.

Note: Pygame is primarily designed for graphical applications, and creating terminal-based games with it is limited compared to using dedicated terminal libraries like curses. If there is an interest in more advanced terminal games, explore other libraries specifically designed for terminal game development.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved