Embark on a thrilling virtual horse race with "Retro Race Day," a Python arcade game designed to evoke the nostalgia of 80s coin-op classics! Experience simple graphics, addictive gameplay, and the thrill of the finish line.
Game Features:
- Retro Graphics: Pixelated visuals, a limited color palette, and straightforward geometric shapes for horses and track.
- Simple Controls: Press SPACE to accelerate your horse.
- Multiple Horses: Race against AI-controlled opponents.
- Dynamic Speeds: Horses have varying base speeds and encounter minor speed fluctuations.
- Track Design: A clear track with start and finish lines, and lane dividers.
- Game States: Navigate through a start menu, the racing action, and a results screen.
import pygame
import random
import math
# --- Constants ---
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 300
FPS = 60
# Colors (Retro Palette)
COLOR_BLACK = (0, 0, 0)
COLOR_WHITE = (255, 255, 255)
COLOR_RED = (255, 0, 0)
COLOR_GREEN = (0, 255, 0)
COLOR_BLUE = (0, 0, 255)
COLOR_YELLOW = (255, 255, 0)
COLOR_PURPLE = (128, 0, 128)
COLOR_CYAN = (0, 255, 255)
COLOR_ORANGE = (255, 165, 0)
COLOR_GRAY = (128, 128, 128)
# Game Specific Colors
BACKGROUND_COLOR = (20, 20, 80) # Deep blue for a night/stadium feel
TRACK_COLOR = COLOR_GREEN
TRACK_LANE_COLOR = COLOR_WHITE
HORSE_COLORS = [COLOR_RED, COLOR_YELLOW, COLOR_CYAN, COLOR_PURPLE]
# Track Dimensions
TRACK_X_START = 50
TRACK_Y_START = 50
TRACK_WIDTH = SCREEN_WIDTH - TRACK_X_START * 2 # Make track centered and slightly narrower than screen
TRACK_HEIGHT = SCREEN_HEIGHT - TRACK_Y_START * 2
NUM_LANES = 4
LANE_HEIGHT = TRACK_HEIGHT / NUM_LANES
FINISH_LINE_X = TRACK_X_START + TRACK_WIDTH
# Horse Properties
HORSE_BASE_WIDTH = 15
HORSE_BASE_HEIGHT = 25
HORSE_OFFSET_X = 8 # Spacing within lanes
# Game Logic
PLAYER_ACCEL_RATE = 0.06 # Player's acceleration input
MAX_SPEED = 5.0
MIN_SPEED = 0.1
AI_SPEED_VARIATION = 0.4 # How much AI speed can fluctuate randomly
AI_BASE_SPEED_RANGE = (0.5, 1.5) # Base speeds for AI horses
AI_ACCEL_CHANCE = 0.05 # Chance for AI to get a speed boost/drop
# Game States
STATE_MENU = 0
STATE_RACING = 1
STATE_GAME_OVER = 2
# --- Classes ---
class Horse:
"""Represents a horse in the race."""
def __init__(self, lane, color, name="Horse", is_player=False):
self.lane = lane
self.color = color
self.name = name
self.is_player = is_player
self.speed = 0.0
self.acceleration = 0.0
self.position = 0.0 # Distance from start line (0 to TRACK_WIDTH)
# Pygame Rect for drawing. Its position will be updated based on self.position.
self.rect = pygame.Rect(0, 0, HORSE_BASE_WIDTH, HORSE_BASE_HEIGHT)
self.update_rect_position() # Set initial graphical position
def update_rect_position(self):
"""Calculates the graphical (x, y) for the horse's rect based on its race position."""
# Determine the center Y coordinate for the lane
lane_center_y = TRACK_Y_START + self.lane * LANE_HEIGHT + LANE_HEIGHT / 2
# Calculate the graphical X coordinate based on race progress
graphical_x = TRACK_X_START + self.position
# Calculate a horizontal offset to spread horses slightly within their lanes
# This centers the horses within the visual lane space.
lane_span_center = (NUM_LANES - 1) / 2.0
offset_x = (self.lane - lane_span_center) * HORSE_OFFSET_X
# Set the center of the horse's rect
self.rect.centerx = graphical_x + offset_x
self.rect.centery = lane_center_y
def accelerate(self):
"""AI horses use this to determine their acceleration for the turn."""
if not self.is_player:
# Randomly adjust acceleration for AI
self.acceleration = random.uniform(-AI_SPEED_VARIATION, AI_SPEED_VARIATION)
# Add a small chance for a significant speed change
if random.random() < AI_ACCEL_CHANCE:
self.acceleration *= 2.5 # A boost/drop
def update(self):
"""Updates the horse's speed, position, and graphical representation."""
# Apply acceleration to speed (player's acceleration is set externally)
self.speed += self.acceleration
# Clamp speed to min/max limits
self.speed = max(MIN_SPEED, min(self.speed, MAX_SPEED))
# Move horse based on current speed
self.position += self.speed
# Ensure horses don't go past the finish line graphically
self.position = min(self.position, TRACK_WIDTH)
# Update graphical position for drawing
self.update_rect_position()
def reset(self):
"""Resets the horse to the starting position."""
self.speed = 0.0
self.acceleration = 0.0
self.position = 0.0
self.update_rect_position()
# --- Game Functions ---
def draw_text(surface, text, size, color, x, y, center=False):
"""Helper function to draw text on the screen."""
# Use default system font for simplicity and retro feel
font = pygame.font.SysFont(None, size)
text_surface = font.render(text, True, color)
if center:
text_rect = text_surface.get_rect(center=(x, y))
else:
text_rect = text_surface.get_rect(topleft=(x, y))
surface.blit(text_surface, text_rect)
def draw_track(surface, horses):
"""Draws the race track and all horses."""
# Fill background
surface.fill(BACKGROUND_COLOR)
# Draw track rectangle
track_rect = pygame.Rect(TRACK_X_START, TRACK_Y_START, TRACK_WIDTH, TRACK_HEIGHT)
pygame.draw.rect(surface, TRACK_COLOR, track_rect)
# Draw lane dividers (dashed lines)
for i in range(1, NUM_LANES):
lane_y = TRACK_Y_START + i * LANE_HEIGHT
dash_length = 10
gap_length = 5
for x in range(TRACK_X_START, FINISH_LINE_X, dash_length + gap_length):
pygame.draw.line(surface, TRACK_LANE_COLOR, (x, lane_y), (x + dash_length, lane_y), 2)
# Draw Start Line
pygame.draw.line(surface, COLOR_WHITE, (TRACK_X_START, TRACK_Y_START), (TRACK_X_START, TRACK_Y_START + TRACK_HEIGHT), 3)
# Draw Finish Line
pygame.draw.line(surface, COLOR_YELLOW, (FINISH_LINE_X, TRACK_Y_START), (FINISH_LINE_X, TRACK_Y_START + TRACK_HEIGHT), 4)
# Draw Horses
for horse in horses:
# A simple "tail" line for visual flair
tail_x_start = horse.rect.left - 7 # Extend tail slightly behind the horse
tail_y = horse.rect.centery
pygame.draw.line(surface, horse.color, (tail_x_start, tail_y), (horse.rect.left, tail_y), 3)
# Draw the horse body (slightly smaller rect for a cleaner look)
horse_body_rect = horse.rect.inflate(-5, -5) # Reduce size slightly
pygame.draw.rect(surface, horse.color, horse_body_rect)
# --- Game State Functions ---
def run_menu(screen, clock):
"""Handles the main menu screen."""
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False # Signal to exit game
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE or event.key == pygame.K_RETURN:
return STATE_RACING # Transition to racing
if event.key == pygame.K_ESCAPE:
return False # Exit game
screen.fill(BACKGROUND_COLOR) # Clear screen with background color
# Draw Title
draw_text(screen, "RETRO RACE DAY", 40, COLOR_YELLOW, SCREEN_WIDTH // 2, SCREEN_HEIGHT // 3, center=True)
# Draw Instructions
draw_text(screen, "PRESS SPACE TO START", 20, COLOR_WHITE, SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2, center=True)
draw_text(screen, "PRESS ESC TO QUIT", 15, COLOR_GRAY, SCREEN_WIDTH // 2, SCREEN_HEIGHT - 30, center=True)
pygame.display.flip()
clock.tick(FPS)
def run_racing(screen, clock, horses):
"""Handles the main racing gameplay."""
player_horse = next(h for h in horses if h.is_player)
race_over = False
winner = None
finish_times = {} # Stores finish order and time for each horse
# Keep track of game time for potential future use (e.g., race timer display)
game_start_time = pygame.time.get_ticks()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False # Signal to exit game
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
return STATE_MENU # Go back to menu
# --- Player Input ---
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
player_horse.acceleration = PLAYER_ACCEL_RATE # Player holds to accelerate
else:
player_horse.acceleration = 0 # Stop accelerating if key is not pressed
# --- Game Logic Update ---
if not race_over:
# Update AI horse acceleration
for horse in horses:
if not horse.is_player:
horse.accelerate()
# Update position and speed for all horses
for horse in horses:
horse.update()
# Check if horse crossed the finish line
if horse.position >= TRACK_WIDTH:
if not race_over: # If this is the first horse to finish
winner = horse
race_over = True
finish_times[horse] = pygame.time.get_ticks() - game_start_time # Record finish time
# Ensure horses visually stop at the finish line
horse.position = TRACK_WIDTH
horse.speed = 0
horse.acceleration = 0
horse.update_rect_position()
# If race has finished, collect finish times for all remaining horses
if race_over:
for h in horses:
if h not in finish_times:
finish_times[h] = pygame.time.get_ticks() - game_start_time
# Ensure they are also visually at the finish line
h.position = TRACK_WIDTH
h.speed = 0
h.acceleration = 0
h.update_rect_position()
# --- Drawing ---
draw_track(screen, horses)
# Display UI elements
if not race_over:
# Show player stats
draw_text(screen, f"SPEED: {player_horse.speed:.1f}", 20, COLOR_WHITE, 10, 10)
draw_text(screen, "PRESS SPACE TO ACCELERATE", 15, COLOR_YELLOW, SCREEN_WIDTH // 2, 10, center=True)
else:
# Display winner message when race is over
draw_text(screen, f"WINNER: {winner.name.upper()}!", 30, COLOR_YELLOW, SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 - 50, center=True)
draw_text(screen, "PRESS R TO RESTART", 20, COLOR_WHITE, SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 20, center=True)
draw_text(screen, "PRESS ESC FOR MENU", 15, COLOR_GRAY, SCREEN_WIDTH // 2, SCREEN_HEIGHT - 30, center=True)
pygame.display.flip()
# Control frame rate
clock.tick(FPS)
# If race is over, prepare to transition to game over screen
if race_over:
return STATE_GAME_OVER, horses, finish_times
return STATE_MENU # Fallback if loop exits unexpectedly
def run_game_over(screen, clock, horses, finish_times):
"""Handles the race results screen."""
# Sort horses by their finish times
sorted_horses = sorted(horses, key=lambda h: finish_times[h])
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False # Signal to exit game
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
return STATE_RACING # Restart race
if event.key == pygame.K_ESCAPE:
return STATE_MENU # Go back to menu
screen.fill(BACKGROUND_COLOR)
# Draw Title
draw_text(screen, "RACE RESULTS", 40, COLOR_YELLOW, SCREEN_WIDTH // 2, SCREEN_HEIGHT // 4, center=True)
# Display standings
y_pos = SCREEN_HEIGHT // 3
for i, horse in enumerate(sorted_horses):
# Format time from milliseconds to seconds
time_ms = finish_times[horse]
time_str = f"{time_ms / 1000.0:.2f}s"
# Display rank, horse name (color for simplicity) and time
draw_text(screen, f"{i+1}. {horse.name.upper()}", 20, COLOR_WHITE, SCREEN_WIDTH // 2 - 80, y_pos, center=False)
draw_text(screen, time_str, 20, COLOR_WHITE, SCREEN_WIDTH // 2 + 80, y_pos, center=False)
y_pos += 30
# Draw prompts
draw_text(screen, "PRESS R TO RACE AGAIN", 20, COLOR_WHITE, SCREEN_WIDTH // 2, SCREEN_HEIGHT - 50, center=True)
draw_text(screen, "PRESS ESC FOR MENU", 15, COLOR_GRAY, SCREEN_WIDTH // 2, SCREEN_HEIGHT - 20, center=True)
pygame.display.flip()
clock.tick(FPS)
return True # Fallback if loop exits unexpectedly
# --- Main Game Initialization and Loop ---
def main():
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Retro Race Day")
clock = pygame.time.Clock()
game_state = STATE_MENU
# Variables to hold horses and results between state transitions
horses_data = None
finish_times_data = None
# Main game loop: Continues as long as game_state is not False (which signals quitting)
while game_state:
if game_state == STATE_MENU:
next_state = run_menu(screen, clock)
if next_state == STATE_RACING:
# Initialize horses for a new race
player_horse = Horse(lane=0, color=HORSE_COLORS[0], name="Player", is_player=True)
ai_horses = []
for i in range(1, NUM_LANES):
ai_horse = Horse(lane=i, color=HORSE_COLORS[i], name=f"AI-{i}", is_player=False)
# Give AI horses a random base speed to start
ai_horse.speed = random.uniform(*AI_BASE_SPEED_RANGE)
ai_horses.append(ai_horse)
all_horses = [player_horse] + ai_horses
horses_data = all_horses # Store for the next state
game_state = STATE_RACING
elif next_state is False: # Quit signal received from run_menu
game_state = False # Exit the main loop
elif game_state == STATE_RACING:
# run_racing returns a tuple if the race finished, or the next state directly
result = run_racing(screen, clock, horses_data)
if isinstance(result, tuple): # Race finished
# Unpack the results: new state, horses, and finish times
game_state, horses_data, finish_times_data = result
elif result is STATE_MENU: # Escape pressed during race
game_state = STATE_MENU
elif result is False: # Quit signal received during race
game_state = False
elif game_state == STATE_GAME_OVER:
# run_game_over returns a tuple for transitions, or False for quitting
result = run_game_over(screen, clock, horses_data, finish_times_data)
if result == STATE_RACING:
# Re-initialize horses for a new race (same logic as from menu)
player_horse = Horse(lane=0, color=HORSE_COLORS[0], name="Player", is_player=True)
ai_horses = []
for i in range(1, NUM_LANES):
ai_horse = Horse(lane=i, color=HORSE_COLORS[i], name=f"AI-{i}", is_player=False)
ai_horse.speed = random.uniform(*AI_BASE_SPEED_RANGE)
ai_horses.append(ai_horse)
all_horses = [player_horse] + ai_horses
horses_data = all_horses
game_state = STATE_RACING
elif result is STATE_MENU:
game_state = STATE_MENU
elif result is False: # Quit signal received from game over screen
game_state = False
# Game loop has ended (game_state is False)
pygame.quit()
if __name__ == '__main__':
main()