Curriculum
Course: Python Game Development : Build 5 Fun Pr...
Login

Curriculum

Python Game Development : Build 5 Fun Projects with Pygame

Text lesson

Initial Setup :Project 5 : 2D ball racing game

Initialization and Setup:

  • import pygame: Imports the Pygame library for game development.
  • import sys: Imports the sys module for system-specific functions.
  • import random: Imports the random module for generating random numbers.
  • pygame.init(): Initializes Pygame and its modules.
  • WIDTH, HEIGHT = 1200, 800: Sets the dimensions of the game window.
  • WINDOW = pygame.display.set_mode((WIDTH, HEIGHT)): Creates the game window with the specified dimensions.
  • pygame.display.set_caption("Road Path Ball Race"): Sets the caption/title of the game window.

import pygame

import sys

import random # Initialize Pygame

pygame.init() # Set up the window

WIDTH, HEIGHT = 1200, 800

WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))

pygame.display.set_caption(“Road Path Ball Race”)

Definitions:

  • Colors are defined using RGB values.
  • path_width is set to define the width of the road path.
  • road_points contains the coordinates of points defining the road path.

# Define colors

WHITE = (255, 255, 255)

BLACK = (0, 0, 0)

RED = (255, 0, 0)

BLUE = (0, 0, 255) # Define road path points

path_width = 80

road_points = [ (100, 100), (1000, 100), (1000, 300), (200, 300), (200, 500), (1100, 500), (1100, 700), (100, 700), ]

Ball and Enemy Parameters:

  • Parameters for the balls (players) and enemies are defined.
  • Initial positions, velocities, and flags to track whether each ball has reached the end point are set.
  • Enemy parameters such as radius, color, spawn timer, and spawn interval are defined

# Ball parameters

ball_radius = 15

ball_speed = 5 # Initial position for both balls

start_point = road_points[0] # First ball (red)

ball1_x, ball1_y = start_point

ball1_dx, ball1_dy = 0, 0

ball1_reached_end = False # Second ball (blue)

ball2_x, ball2_y = start_point

ball2_dx, ball2_dy = 0, 0

ball2_reached_end = False # Enemy parameters

enemy_radius = 10

enemy_color = (0, 255, 0)

enemies = []

enemy_spawn_timer = 0

enemy_spawn_interval = 500

 

×

Cart