ASPHALT = (50, 50, 50)
WHITE = (255, 255, 255)
YELLOW = (255, 255, 0)
ROAD_EDGE = (180, 180, 180)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
Road and lanes
road_left = 100
road_right = 600
lane_count = 5
lane_width = (road_right - road_left) // lane_count
lanes = [road_left + i * lane_width + lane_width // 2 for i in range(lane_count)] # center x of each lane
Car settings (hitbox dimensions)
car_width = 70 # Player car hitbox width
car_height = 140 # Player car hitbox height
car_lane = 2 # Start in the middle lane
car_x = lanes[car_lane] - car_width // 2 # Current x position
car_target_x = car_x # Target x position for smooth movement
car_y = height - car_height - 10
car_speed = 10 # Speed of smooth movement (pixels per frame)
Obstacle settings (hitbox dimensions)
obstacle_width = 70 # Obstacle car hitbox width
obstacle_height = 120 # Obstacle car hitbox height
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": None},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": None}, # Second car starts farther away
]
obstacle_speed = 5 # Initial speed
third_obstacle_added = False # Flag for adding a third obstacle
fourth_obstacle_added = False # Flag for adding a fourth obstacle
Visual dimensions (for rendering only)
visual_car_width = 120 # Player car appears thicker
visual_obstacle_width = 70 # Obstacle car appears thinner
Load car images with updated visual dimensions
player_car_img = pygame.image.load("car_player.png") # Replace with the path to your player's car image
player_car_img = pygame.transform.scale(player_car_img, (visual_car_width, car_height))
for obstacle in obstacles:
obstacle["skin"] = random.choice(obstacle_skins)
clock = pygame.time.Clock()
font = pygame.font.Font(pygame.font.match_font('arial'), 36) # Stylish font
title_font = pygame.font.Font(pygame.font.match_font('arial'), 72)
Game variables
run = True
menu_active = True
score = 0
line_offset = 0 # Offset for moving dashed lines
High score handling
high_score_file = "highscore.txt"
def load_high_score():
"""Load the high score from a file."""
if os.path.exists(high_score_file):
with open(high_score_file, "r") as file:
try:
return int(file.read().strip())
except ValueError:
return 0
return 0
def save_high_score(high_score):
"""Save the high score to a file."""
with open(high_score_file, "w") as file:
file.write(str(high_score))
Initialize high score
high_score = load_high_score()
def draw_highway():
# Draw the asphalt background
win.fill(ASPHALT)
code
# Draw road edges (shoulders)
pygame.draw.rect(win, ROAD_EDGE, (road_left - 20, 0, 20, height)) # Left shoulder
pygame.draw.rect(win, ROAD_EDGE, (road_right, 0, 20, height)) # Right shoulder
# Draw the road itself
pygame.draw.rect(win, ASPHALT, (road_left, 0, road_right - road_left, height)) # Road area
# Draw solid white lines for highway boundaries
pygame.draw.line(win, WHITE, (road_left, 0), (road_left, height), 4) # Left boundary
pygame.draw.line(win, WHITE, (road_right, 0), (road_right, height), 4) # Right boundary
# Draw moving dashed yellow lane dividers
global line_offset
line_offset = (line_offset + 5) % 40 # Speed of lane line movement
for i in range(1, lane_count):
lane_x = road_left + i * lane_width
for y in range(-line_offset, height, 40):
pygame.draw.rect(win, YELLOW, (lane_x - 2, y, 4, 20))
def draw_game():
draw_highway()
visual_car_x = car_x - (visual_car_width - car_width) // 2 # Adjust visual car to match hitbox
code
win.blit(player_car_img, (visual_car_x, car_y)) # Draw player's car
# Draw obstacles
for obstacle in obstacles:
obstacle_x = lanes[obstacle["lane"]] - visual_obstacle_width // 2
win.blit(obstacle["skin"], (obstacle_x, obstacle["y"]))
# Display the score
score_text = font.render(f"Score: {score}", True, WHITE)
win.blit(score_text, (10, 10))
def end_game_screen():
global run, menu_active, score, high_score, obstacles, third_obstacle_added, fourth_obstacle_added
code
# Update high score if current score is higher
if score > high_score:
high_score = score
save_high_score(high_score) # Save the new high score
while True:
win.fill(ASPHALT)
end_text = title_font.render("Game Over", True, RED)
score_text = font.render(f"Your Score: {score}", True, WHITE)
high_score_text = font.render(f"High Score: {high_score}", True, WHITE)
play_again_text = font.render("Play Again", True, WHITE)
quit_text = font.render("Quit", True, WHITE)
play_again_button = pygame.Rect(width // 2 - 100, 300, 200, 50) # Play Again button
quit_button = pygame.Rect(width // 2 - 100, 400, 200, 50) # Quit button
# Draw Game Over screen
win.blit(end_text, (width // 2 - end_text.get_width() // 2, 100))
win.blit(score_text, (width // 2 - score_text.get_width() // 2, 200))
win.blit(high_score_text, (width // 2 - high_score_text.get_width() // 2, 250))
pygame.draw.rect(win, BLUE, play_again_button)
pygame.draw.rect(win, BLUE, quit_button)
win.blit(play_again_text, (play_again_button.x + play_again_button.width // 2 - play_again_text.get_width() // 2,
play_again_button.y + play_again_button.height // 2 - play_again_text.get_height() // 2))
win.blit(quit_text, (quit_button.x + quit_button.width // 2 - quit_text.get_width() // 2,
quit_button.y + quit_button.height // 2 - quit_text.get_height() // 2))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if play_again_button.collidepoint(event.pos): # Restart game
score = 0
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": random.choice(obstacle_skins)},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": random.choice(obstacle_skins)},
]
third_obstacle_added = False
fourth_obstacle_added = False
return # Exit the end game screen loop
elif quit_button.collidepoint(event.pos): # Quit game
pygame.quit()
exit()
def main_menu():
global menu_active, obstacles, score, high_score, third_obstacle_added, fourth_obstacle_added
code
while menu_active:
clock.tick(60)
# Update the background gameplay
for obstacle in obstacles:
obstacle["y"] += obstacle_speed
if obstacle["y"] > height:
obstacle["y"] = -obstacle_height
obstacle["lane"] = random.randint(0, lane_count - 1)
obstacle["skin"] = random.choice(obstacle_skins) # Assign a new random skin
# Draw the game in the background
draw_game()
# Draw menu overlay
title_text = title_font.render("Car Game", True, WHITE)
play_text = font.render("Play", True, WHITE)
high_score_text = font.render(f"High Score: {high_score}", True, WHITE)
play_button_rect = pygame.Rect(width // 2 - 100, 300, 200, 50) # Play button dimensions
# Draw title, high score, and button
win.blit(title_text, (width // 2 - title_text.get_width() // 2, 100))
win.blit(high_score_text, (width // 2 - high_score_text.get_width() // 2, 200))
pygame.draw.rect(win, BLUE, play_button_rect)
win.blit(play_text, (play_button_rect.x + play_button_rect.width // 2 - play_text.get_width() // 2,
play_button_rect.y + play_button_rect.height // 2 - play_text.get_height() // 2))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if play_button_rect.collidepoint(event.pos): # Start game
score = 0
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": random.choice(obstacle_skins)},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": random.choice(obstacle_skins)},
]
third_obstacle_added = False
fourth_obstacle_added = False
menu_active = False # Exit the menu
Main loop
main_menu() # Display the main menu
while run:
clock.tick(60)
code
# Increase obstacle speed as score increases
obstacle_speed = 5 + (score // 10)
# Add a third obstacle when the score reaches 10
if score >= 10 and not third_obstacle_added:
obstacles.append({"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 400, "skin": random.choice(obstacle_skins)})
third_obstacle_added = True
# Add a fourth obstacle when the score reaches 20
if score >= 20 and not fourth_obstacle_added:
obstacles.append({"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 600, "skin": random.choice(obstacle_skins)})
fourth_obstacle_added = True
draw_game()
pygame.display.update()
# Update obstacles
for obstacle in obstacles:
obstacle["y"] += obstacle_speed
if obstacle["y"] > height:
obstacle["y"] = -obstacle_height
obstacle["lane"] = random.randint(0, lane_count - 1)
obstacle["skin"] = random.choice(obstacle_skins)
score += 1 # Increase score when an obstacle resets
# Smoothly move the car towards the target x position
if car_x < car_target_x:
car_x += min(car_speed, car_target_x - car_x)
elif car_x > car_target_x:
car_x -= min(car_speed, car_x - car_target_x)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN: # Detect key press
if event.key == pygame.K_LEFT and car_lane > 0:
car_lane -= 1
car_target_x = lanes[car_lane] - car_width // 2
elif event.key == pygame.K_RIGHT and car_lane < lane_count - 1:
car_lane += 1
car_target_x = lanes[car_lane] - car_width // 2
# Check for collisions
car_rect = pygame.Rect(car_x, car_y, car_width, car_height)
for obstacle in obstacles:
obstacle_x = lanes[obstacle["lane"]] - obstacle_width // 2
# Adjust obstacle hitbox to be smaller (10% of original size)
obstacle_hitbox_width = obstacle_width * 0.1
obstacle_hitbox_height = obstacle_height * 0.1
obstacle_hitbox_x = obstacle_x + (obstacle_width - obstacle_hitbox_width) // 2
obstacle_hitbox_y = obstacle["y"] + (obstacle_height - obstacle_hitbox_height) // 2
obstacle_rect = pygame.Rect(
obstacle_hitbox_x, obstacle_hitbox_y, obstacle_hitbox_width, obstacle_hitbox_height
)
if car_rect.colliderect(obstacle_rect):
end_game_screen() # Display end game screen add an oto meter displaying how fast the car is going
Assistant
To add a speedometer display that shows how fast the car is going, you can do the following:
Define a speed variable (we already have obstacle_speed representing obstacle movement speed, which effectively is the "car speed" in gameplay);
On your game screen, display a speedometer element — it can be simple text showing the speed value, or a graphical element (e.g., a semi-circle with a needle). For simplicity, we’ll do a text-based speedometer that updates with the current speed;
Display it in a fixed position (e.g., bottom-left corner or top-right corner);
I'll show how to implement a simple speedometer text display that shows the current speed (the obstacles move faster as score increases, simulating the car speeding up).
Code to add (place this in your draw_game() function):
Add the following lines near the end of draw_game() — after drawing the score, add:
python
# Draw the speedometer
# Convert obstacle speed to km/h or mph for display if you want
# Here, just show the current speed value for simplicity
speed_text = font.render(f"Speed: {obstacle_speed} km/h", True, WHITE)
win.blit(speed_text, (width - speed_text.get_width() - 10, 10)) # Top-right corner
Full snippet integration:
Find your existing draw_game():
python
def draw_game():
draw_highway()
visual_car_x = car_x - (visual_car_width - car_width) // 2 # Adjust visual car to match hitbox
win.blit(player_car_img, (visual_car_x, car_y)) # Draw player's car
# Draw obstacles
for obstacle in obstacles:
obstacle_x = lanes[obstacle["lane"]] - visual_obstacle_width // 2
win.blit(obstacle["skin"], (obstacle_x, obstacle["y"]))
# Display the score
score_text = font.render(f"Score: {score}", True, WHITE)
win.blit(score_text, (10, 10))
User
add all of this to this import pygame
import random
import os # For file handling
ASPHALT = (50, 50, 50)
WHITE = (255, 255, 255)
YELLOW = (255, 255, 0)
ROAD_EDGE = (180, 180, 180)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
Road and lanes
road_left = 100
road_right = 600
lane_count = 5
lane_width = (road_right - road_left) // lane_count
lanes = [road_left + i * lane_width + lane_width // 2 for i in range(lane_count)] # center x of each lane
Car settings (hitbox dimensions)
car_width = 70 # Player car hitbox width
car_height = 140 # Player car hitbox height
car_lane = 2 # Start in the middle lane
car_x = lanes[car_lane] - car_width // 2 # Current x position
car_target_x = car_x # Target x position for smooth movement
car_y = height - car_height - 10
car_speed = 10 # Speed of smooth movement (pixels per frame)
Obstacle settings (hitbox dimensions)
obstacle_width = 70 # Obstacle car hitbox width
obstacle_height = 120 # Obstacle car hitbox height
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": None},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": None}, # Second car starts farther away
]
obstacle_speed = 5 # Initial speed
third_obstacle_added = False # Flag for adding a third obstacle
fourth_obstacle_added = False # Flag for adding a fourth obstacle
Visual dimensions (for rendering only)
visual_car_width = 120 # Player car appears thicker
visual_obstacle_width = 70 # Obstacle car appears thinner
Load car images with updated visual dimensions
player_car_img = pygame.image.load("car_player.png") # Replace with the path to your player's car image
player_car_img = pygame.transform.scale(player_car_img, (visual_car_width, car_height))
for obstacle in obstacles:
obstacle["skin"] = random.choice(obstacle_skins)
clock = pygame.time.Clock()
font = pygame.font.Font(pygame.font.match_font('arial'), 36) # Stylish font
title_font = pygame.font.Font(pygame.font.match_font('arial'), 72)
Game variables
Assistant
Here's your full updated code including the speedometer that displays how fast the car is going (the current speed equals the obstacle speed).
The change is mainly inside the draw_game() function to display the speed, plus a small formatting comment:
python
User
import pygame
import random
import os # For file handling
ASPHALT = (50, 50, 50)
WHITE = (255, 255, 255)
YELLOW = (255, 255, 0)
ROAD_EDGE = (180, 180, 180)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
Road and lanes
road_left = 100
road_right = 600
lane_count = 5
lane_width = (road_right - road_left) // lane_count
lanes = [road_left + i * lane_width + lane_width // 2 for i in range(lane_count)] # center x of each lane
Car settings (hitbox dimensions)
car_width = 70 # Player car hitbox width
car_height = 140 # Player car hitbox height
car_lane = 2 # Start in the middle lane
car_x = lanes[car_lane] - car_width // 2 # Current x position
car_target_x = car_x # Target x position for smooth movement
car_y = height - car_height - 10
car_speed = 10 # Speed of smooth movement (pixels per frame)
Obstacle settings (hitbox dimensions)
obstacle_width = 70 # Obstacle car hitbox width
obstacle_height = 120 # Obstacle car hitbox height
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": None},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": None}, # Second car starts farther away
]
obstacle_speed = 5 # Initial speed
third_obstacle_added = False # Flag for adding a third obstacle
fourth_obstacle_added = False # Flag for adding a fourth obstacle
Visual dimensions (for rendering only)
visual_car_width = 120 # Player car appears thicker
visual_obstacle_width = 70 # Obstacle car appears thinner
Load car images with updated visual dimensions
player_car_img = pygame.image.load("car_player.png") # Replace with the path to your player's car image
player_car_img = pygame.transform.scale(player_car_img, (visual_car_width, car_height))
ASPHALT = (50, 50, 50)
WHITE = (255, 255, 255)
YELLOW = (255, 255, 0)
ROAD_EDGE = (180, 180, 180)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
Road and lanes
road_left = 100
road_right = 600
lane_count = 5
lane_width = (road_right - road_left) // lane_count
lanes = [road_left + i * lane_width + lane_width // 2 for i in range(lane_count)] # center x of each lane
Car settings (hitbox dimensions)
car_width = 70 # Player car hitbox width
car_height = 140 # Player car hitbox height
car_lane = 2 # Start in the middle lane
car_x = lanes[car_lane] - car_width // 2 # Current x position
car_target_x = car_x # Target x position for smooth movement
car_y = height - car_height - 10
car_speed = 10 # Speed of smooth movement (pixels per frame)
Obstacle settings (hitbox dimensions)
obstacle_width = 70 # Obstacle car hitbox width
obstacle_height = 120 # Obstacle car hitbox height
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": None},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": None}, # Second car starts farther away
]
obstacle_speed = 5 # Initial speed
third_obstacle_added = False # Flag for adding a third obstacle
fourth_obstacle_added = False # Flag for adding a fourth obstacle
Visual dimensions (for rendering only)
visual_car_width = 120 # Player car appears thicker
visual_obstacle_width = 70 # Obstacle car appears thinner
Load car images with updated visual dimensions
player_car_img = pygame.image.load("car_player.png") # Replace with the path to your player's car image
player_car_img = pygame.transform.scale(player_car_img, (visual_car_width, car_height))
for obstacle in obstacles:
obstacle["skin"] = random.choice(obstacle_skins)
clock = pygame.time.Clock()
font = pygame.font.Font(pygame.font.match_font('arial'), 36) # Stylish font
title_font = pygame.font.Font(pygame.font.match_font('arial'), 72)
Game variables
Assistant
Certainly! Below is your full Python script with the speedometer moved to the bottom right corner and styled like a car's odometer. It uses a monospace font, zero-padded speed display, and a black rounded rectangle with a white border around it:
python
User
import pygame
import random
import os # For file handling
ASPHALT = (50, 50, 50)
WHITE = (255, 255, 255)
YELLOW = (255, 255, 0)
ROAD_EDGE = (180, 180, 180)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
Road and lanes
road_left = 100
road_right = 600
lane_count = 5
lane_width = (road_right - road_left) // lane_count
lanes = [road_left + i * lane_width + lane_width // 2 for i in range(lane_count)] # center x of each lane
Car settings (hitbox dimensions)
car_width = 70 # Player car hitbox width
car_height = 140 # Player car hitbox height
car_lane = 2 # Start in the middle lane
car_x = lanes[car_lane] - car_width // 2 # Current x position
car_target_x = car_x # Target x position for smooth movement
car_y = height - car_height - 10
car_speed = 10 # Speed of smooth movement (pixels per frame)
Obstacle settings (hitbox dimensions)
obstacle_width = 70 # Obstacle car hitbox width
obstacle_height = 120 # Obstacle car hitbox height
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": None},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": None}, # Second car starts farther away
]
obstacle_speed = 5 # Initial speed
third_obstacle_added = False # Flag for adding a third obstacle
fourth_obstacle_added = False # Flag for adding a fourth obstacle
Visual dimensions (for rendering only)
visual_car_width = 120 # Player car appears thicker
visual_obstacle_width = 70 # Obstacle car appears thinner
Load car images with updated visual dimensions
player_car_img = pygame.image.load("car_player.png") # Replace with the path to your player's car image
player_car_img = pygame.transform.scale(player_car_img, (visual_car_width, car_height))
for obstacle in obstacles:
obstacle["skin"] = random.choice(obstacle_skins)
clock = pygame.time.Clock()
font = pygame.font.Font(pygame.font.match_font('arial'), 36) # Stylish font
title_font = pygame.font.Font(pygame.font.match_font('arial'), 72)
Load a monospace font for odometer style speed display
Assistant
To make the car start at 60 km/h instead of 5 km/h, simply initialize obstacle_speed to 60 at the start and adjust how the speed increases with score accordingly.
Here's what you need to do:
1. Change the initial speed:
python
obstacle_speed = 60 # Start at 60 km/h
2. Adjust speed increment in your main loop to avoid jumps from 5 to 60:
Currently, you do:
python
obstacle_speed = 5 + (score // 10)
Change it to:
python
obstacle_speed = 60 + (score // 10)
This means the speed starts at 60 km/h and increases by 1 km/h every 10 points.
Summary of changes:
Find the top where obstacle_speed is defined:
python
obstacle_speed = 60 # Initial speed set to 60 km/h
And in the main loop, replace the speed calculation with:
python
obstacle_speed = 60 + (score // 10)
Minimal diff snippet for your main loop:
python
# Main loop
main_menu() # Display the main menu
while run:
clock.tick(60)
# Increase obstacle speed as score increases, starting at 60 km/h
obstacle_speed = 60 + (score // 10)
# Add a third obstacle when the score reaches 10
if score >= 10 and not third_obstacle_added:
obstacles.append({"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 400, "skin": random.choice(obstacle_skins)})
third_obstacle_added = True
# Add a fourth obstacle when the score reaches 20
if score >= 20 and not fourth_obstacle_added:
obstacles.append({"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 600, "skin": random.choice(obstacle_skins)})
fourth_obstacle_added = True
draw_game()
pygame.display.update()
# Rest of your loop...
This will have your car "speedometer" start at 60 km/h as requested.
Let me know if you'd like the full updated script or help with anything else!
User
add it all to this code import pygame
import random
import os # For file handling
ASPHALT = (50, 50, 50)
WHITE = (255, 255, 255)
YELLOW = (255, 255, 0)
ROAD_EDGE = (180, 180, 180)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
Road and lanes
road_left = 100
road_right = 600
lane_count = 5
lane_width = (road_right - road_left) // lane_count
lanes = [road_left + i * lane_width + lane_width // 2 for i in range(lane_count)] # center x of each lane
Car settings (hitbox dimensions)
car_width = 70 # Player car hitbox width
car_height = 140 # Player car hitbox height
car_lane = 2 # Start in the middle lane
car_x = lanes[car_lane] - car_width // 2 # Current x position
car_target_x = car_x # Target x position for smooth movement
car_y = height - car_height - 10
car_speed = 10 # Speed of smooth movement (pixels per frame)
Obstacle settings (hitbox dimensions)
obstacle_width = 70 # Obstacle car hitbox width
obstacle_height = 120 # Obstacle car hitbox height
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": None},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": None}, # Second car starts farther away
]
obstacle_speed = 5 # Initial speed
third_obstacle_added = False # Flag for adding a third obstacle
fourth_obstacle_added = False # Flag for adding a fourth obstacle
Visual dimensions (for rendering only)
visual_car_width = 120 # Player car appears thicker
visual_obstacle_width = 70 # Obstacle car appears thinner
Load car images with updated visual dimensions
player_car_img = pygame.image.load("car_player.png") # Replace with the path to your player's car image
player_car_img = pygame.transform.scale(player_car_img, (visual_car_width, car_height))
# Display the score
score_text = font.render(f"Score: {score}", True, WHITE)
win.blit(score_text, (10, 10))
# Draw the speedometer
speed_text = font.render(f"Speed: {obstacle_speed} km/h", True, WHITE)
win.blit(speed_text, (width - speed_text.get_width() - 10, 10)) # Position it top-right
Now the game will display the Speed: label alongside the speed value (which corresponds to the obstacle movement speed).
If you want a graphical speedometer (like a dial), that’s significantly more involved, requiring drawing arcs or a needle rotated depending on speed. Let me know if you'd prefer that instead!
run = True
menu_active = True
score = 0
line_offset = 0 # Offset for moving dashed lines
High score handling
high_score_file = "highscore.txt"
def load_high_score():
"""Load the high score from a file."""
if os.path.exists(high_score_file):
with open(high_score_file, "r") as file:
try:
return int(file.read().strip())
except ValueError:
return 0
return 0
def save_high_score(high_score):
"""Save the high score to a file."""
with open(high_score_file, "w") as file:
file.write(str(high_score))
Initialize high score
high_score = load_high_score()
def draw_highway():
# Draw the asphalt background
win.fill(ASPHALT)
code
# Draw road edges (shoulders)
pygame.draw.rect(win, ROAD_EDGE, (road_left - 20, 0, 20, height)) # Left shoulder
pygame.draw.rect(win, ROAD_EDGE, (road_right, 0, 20, height)) # Right shoulder
# Draw the road itself
pygame.draw.rect(win, ASPHALT, (road_left, 0, road_right - road_left, height)) # Road area
# Draw solid white lines for highway boundaries
pygame.draw.line(win, WHITE, (road_left, 0), (road_left, height), 4) # Left boundary
pygame.draw.line(win, WHITE, (road_right, 0), (road_right, height), 4) # Right boundary
# Draw moving dashed yellow lane dividers
global line_offset
line_offset = (line_offset + 5) % 40 # Speed of lane line movement
for i in range(1, lane_count):
lane_x = road_left + i * lane_width
for y in range(-line_offset, height, 40):
pygame.draw.rect(win, YELLOW, (lane_x - 2, y, 4, 20))
def draw_game():
draw_highway()
visual_car_x = car_x - (visual_car_width - car_width) // 2 # Adjust visual car to match hitbox
code
win.blit(player_car_img, (visual_car_x, car_y)) # Draw player's car
# Draw obstacles
for obstacle in obstacles:
obstacle_x = lanes[obstacle["lane"]] - visual_obstacle_width // 2
win.blit(obstacle["skin"], (obstacle_x, obstacle["y"]))
# Display the score
score_text = font.render(f"Score: {score}", True, WHITE)
win.blit(score_text, (10, 10))
def end_game_screen():
global run, menu_active, score, high_score, obstacles, third_obstacle_added, fourth_obstacle_added
code
# Update high score if current score is higher
if score > high_score:
high_score = score
save_high_score(high_score) # Save the new high score
while True:
win.fill(ASPHALT)
end_text = title_font.render("Game Over", True, RED)
score_text = font.render(f"Your Score: {score}", True, WHITE)
high_score_text = font.render(f"High Score: {high_score}", True, WHITE)
play_again_text = font.render("Play Again", True, WHITE)
quit_text = font.render("Quit", True, WHITE)
play_again_button = pygame.Rect(width // 2 - 100, 300, 200, 50) # Play Again button
quit_button = pygame.Rect(width // 2 - 100, 400, 200, 50) # Quit button
# Draw Game Over screen
win.blit(end_text, (width // 2 - end_text.get_width() // 2, 100))
win.blit(score_text, (width // 2 - score_text.get_width() // 2, 200))
win.blit(high_score_text, (width // 2 - high_score_text.get_width() // 2, 250))
pygame.draw.rect(win, BLUE, play_again_button)
pygame.draw.rect(win, BLUE, quit_button)
win.blit(play_again_text, (play_again_button.x + play_again_button.width // 2 - play_again_text.get_width() // 2,
play_again_button.y + play_again_button.height // 2 - play_again_text.get_height() // 2))
win.blit(quit_text, (quit_button.x + quit_button.width // 2 - quit_text.get_width() // 2,
quit_button.y + quit_button.height // 2 - quit_text.get_height() // 2))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if play_again_button.collidepoint(event.pos): # Restart game
score = 0
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": random.choice(obstacle_skins)},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": random.choice(obstacle_skins)},
]
third_obstacle_added = False
fourth_obstacle_added = False
return # Exit the end game screen loop
elif quit_button.collidepoint(event.pos): # Quit game
pygame.quit()
exit()
def main_menu():
global menu_active, obstacles, score, high_score, third_obstacle_added, fourth_obstacle_added
code
while menu_active:
clock.tick(60)
# Update the background gameplay
for obstacle in obstacles:
obstacle["y"] += obstacle_speed
if obstacle["y"] > height:
obstacle["y"] = -obstacle_height
obstacle["lane"] = random.randint(0, lane_count - 1)
obstacle["skin"] = random.choice(obstacle_skins) # Assign a new random skin
# Draw the game in the background
draw_game()
# Draw menu overlay
title_text = title_font.render("Car Game", True, WHITE)
play_text = font.render("Play", True, WHITE)
high_score_text = font.render(f"High Score: {high_score}", True, WHITE)
play_button_rect = pygame.Rect(width // 2 - 100, 300, 200, 50) # Play button dimensions
# Draw title, high score, and button
win.blit(title_text, (width // 2 - title_text.get_width() // 2, 100))
win.blit(high_score_text, (width // 2 - high_score_text.get_width() // 2, 200))
pygame.draw.rect(win, BLUE, play_button_rect)
win.blit(play_text, (play_button_rect.x + play_button_rect.width // 2 - play_text.get_width() // 2,
play_button_rect.y + play_button_rect.height // 2 - play_text.get_height() // 2))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if play_button_rect.collidepoint(event.pos): # Start game
score = 0
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": random.choice(obstacle_skins)},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": random.choice(obstacle_skins)},
]
third_obstacle_added = False
fourth_obstacle_added = False
menu_active = False # Exit the menu
Main loop
main_menu() # Display the main menu
while run:
clock.tick(60)
code
# Increase obstacle speed as score increases
obstacle_speed = 5 + (score // 10)
# Add a third obstacle when the score reaches 10
if score >= 10 and not third_obstacle_added:
obstacles.append({"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 400, "skin": random.choice(obstacle_skins)})
third_obstacle_added = True
# Add a fourth obstacle when the score reaches 20
if score >= 20 and not fourth_obstacle_added:
obstacles.append({"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 600, "skin": random.choice(obstacle_skins)})
fourth_obstacle_added = True
draw_game()
pygame.display.update()
# Update obstacles
for obstacle in obstacles:
obstacle["y"] += obstacle_speed
if obstacle["y"] > height:
obstacle["y"] = -obstacle_height
obstacle["lane"] = random.randint(0, lane_count - 1)
obstacle["skin"] = random.choice(obstacle_skins)
score += 1 # Increase score when an obstacle resets
# Smoothly move the car towards the target x position
if car_x < car_target_x:
car_x += min(car_speed, car_target_x - car_x)
elif car_x > car_target_x:
car_x -= min(car_speed, car_x - car_target_x)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN: # Detect key press
if event.key == pygame.K_LEFT and car_lane > 0:
car_lane -= 1
car_target_x = lanes[car_lane] - car_width // 2
elif event.key == pygame.K_RIGHT and car_lane < lane_count - 1:
car_lane += 1
car_target_x = lanes[car_lane] - car_width // 2
# Check for collisions
car_rect = pygame.Rect(car_x, car_y, car_width, car_height)
for obstacle in obstacles:
obstacle_x = lanes[obstacle["lane"]] - obstacle_width // 2
# Adjust obstacle hitbox to be smaller (10% of original size)
obstacle_hitbox_width = obstacle_width * 0.1
obstacle_hitbox_height = obstacle_height * 0.1
obstacle_hitbox_x = obstacle_x + (obstacle_width - obstacle_hitbox_width) // 2
obstacle_hitbox_y = obstacle["y"] + (obstacle_height - obstacle_hitbox_height) // 2
obstacle_rect = pygame.Rect(
obstacle_hitbox_x, obstacle_hitbox_y, obstacle_hitbox_width, obstacle_hitbox_height
)
if car_rect.colliderect(obstacle_rect):
end_game_screen() # Display end game screen
import pygame
import random
import os # For file handling
pygame.init()
# Window settings
width = 700
height = 600
win = pygame.display.set_mode((width, height))
pygame.display.set_caption("Car Game") # Updated title
# Colors
ASPHALT = (50, 50, 50)
WHITE = (255, 255, 255)
YELLOW = (255, 255, 0)
ROAD_EDGE = (180, 180, 180)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
# Road and lanes
road_left = 100
road_right = 600
lane_count = 5
lane_width = (road_right - road_left) // lane_count
lanes = [road_left + i * lane_width + lane_width // 2 for i in range(lane_count)] # center x of each lane
# Car settings (hitbox dimensions)
car_width = 70 # Player car hitbox width
car_height = 140 # Player car hitbox height
car_lane = 2 # Start in the middle lane
car_x = lanes[car_lane] - car_width // 2 # Current x position
car_target_x = car_x # Target x position for smooth movement
car_y = height - car_height - 10
car_speed = 10 # Speed of smooth movement (pixels per frame)
# Obstacle settings (hitbox dimensions)
obstacle_width = 70 # Obstacle car hitbox width
obstacle_height = 120 # Obstacle car hitbox height
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": None},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": None}, # Second car starts farther away
]
obstacle_speed = 5 # Initial speed
third_obstacle_added = False # Flag for adding a third obstacle
fourth_obstacle_added = False # Flag for adding a fourth obstacle
# Visual dimensions (for rendering only)
visual_car_width = 120 # Player car appears thicker
visual_obstacle_width = 70 # Obstacle car appears thinner
# Load car images with updated visual dimensions
player_car_img = pygame.image.load("car_player.png") # Replace with the path to your player's car image
player_car_img = pygame.transform.scale(player_car_img, (visual_car_width, car_height))
# Load multiple obstacle images
obstacle_skins = [
pygame.transform.scale(pygame.image.load("car_obstacle1.png"), (visual_obstacle_width, obstacle_height)),
pygame.transform.scale(pygame.image.load("car_obstacle2.png"), (visual_obstacle_width, obstacle_height)),
pygame.transform.scale(pygame.image.load("car_obstacle3.png"), (visual_obstacle_width, obstacle_height)),
pygame.transform.scale(pygame.image.load("car_obstacle4.png"), (visual_obstacle_width, obstacle_height)),
]
# Assign random skins to initial obstacles
for obstacle in obstacles:
obstacle["skin"] = random.choice(obstacle_skins)
clock = pygame.time.Clock()
font = pygame.font.Font(pygame.font.match_font('arial'), 36) # Stylish font
title_font = pygame.font.Font(pygame.font.match_font('arial'), 72)
# Game variables
run = True
menu_active = True
score = 0
line_offset = 0 # Offset for moving dashed lines
# High score handling
high_score_file = "highscore.txt"
def load_high_score():
"""Load the high score from a file."""
if os.path.exists(high_score_file):
with open(high_score_file, "r") as file:
try:
return int(file.read().strip())
except ValueError:
return 0
return 0
def save_high_score(high_score):
"""Save the high score to a file."""
with open(high_score_file, "w") as file:
file.write(str(high_score))
# Initialize high score
high_score = load_high_score()
def draw_highway():
# Draw the asphalt background
win.fill(ASPHALT)
# Draw road edges (shoulders)
pygame.draw.rect(win, ROAD_EDGE, (road_left - 20, 0, 20, height)) # Left shoulder
pygame.draw.rect(win, ROAD_EDGE, (road_right, 0, 20, height)) # Right shoulder
# Draw the road itself
pygame.draw.rect(win, ASPHALT, (road_left, 0, road_right - road_left, height)) # Road area
# Draw solid white lines for highway boundaries
pygame.draw.line(win, WHITE, (road_left, 0), (road_left, height), 4) # Left boundary
pygame.draw.line(win, WHITE, (road_right, 0), (road_right, height), 4) # Right boundary
# Draw moving dashed yellow lane dividers
global line_offset
line_offset = (line_offset + 5) % 40 # Speed of lane line movement
for i in range(1, lane_count):
lane_x = road_left + i * lane_width
for y in range(-line_offset, height, 40):
pygame.draw.rect(win, YELLOW, (lane_x - 2, y, 4, 20))
def draw_game():
draw_highway()
visual_car_x = car_x - (visual_car_width - car_width) // 2 # Adjust visual car to match hitbox
win.blit(player_car_img, (visual_car_x, car_y)) # Draw player's car
# Draw obstacles
for obstacle in obstacles:
obstacle_x = lanes[obstacle["lane"]] - visual_obstacle_width // 2
win.blit(obstacle["skin"], (obstacle_x, obstacle["y"]))
# Display the score
score_text = font.render(f"Score: {score}", True, WHITE)
win.blit(score_text, (10, 10))
# Draw the speedometer (showing obstacle speed as car's speed)
speed_text = font.render(f"Speed: {obstacle_speed} km/h", True, WHITE)
win.blit(speed_text, (width - speed_text.get_width() - 10, 10)) # Top-right corner
def end_game_screen():
global run, menu_active, score, high_score, obstacles, third_obstacle_added, fourth_obstacle_added
# Update high score if current score is higher
if score > high_score:
high_score = score
save_high_score(high_score) # Save the new high score
while True:
win.fill(ASPHALT)
end_text = title_font.render("Game Over", True, RED)
score_text = font.render(f"Your Score: {score}", True, WHITE)
high_score_text = font.render(f"High Score: {high_score}", True, WHITE)
play_again_text = font.render("Play Again", True, WHITE)
quit_text = font.render("Quit", True, WHITE)
play_again_button = pygame.Rect(width // 2 - 100, 300, 200, 50) # Play Again button
quit_button = pygame.Rect(width // 2 - 100, 400, 200, 50) # Quit button
# Draw Game Over screen
win.blit(end_text, (width // 2 - end_text.get_width() // 2, 100))
win.blit(score_text, (width // 2 - score_text.get_width() // 2, 200))
win.blit(high_score_text, (width // 2 - high_score_text.get_width() // 2, 250))
pygame.draw.rect(win, BLUE, play_again_button)
pygame.draw.rect(win, BLUE, quit_button)
win.blit(play_again_text, (play_again_button.x + play_again_button.width // 2 - play_again_text.get_width() // 2,
play_again_button.y + play_again_button.height // 2 - play_again_text.get_height() // 2))
win.blit(quit_text, (quit_button.x + quit_button.width // 2 - quit_text.get_width() // 2,
quit_button.y + quit_button.height // 2 - quit_text.get_height() // 2))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if play_again_button.collidepoint(event.pos): # Restart game
score = 0
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": random.choice(obstacle_skins)},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": random.choice(obstacle_skins)},
]
third_obstacle_added = False
fourth_obstacle_added = False
return # Exit the end game screen loop
elif quit_button.collidepoint(event.pos): # Quit game
pygame.quit()
exit()
def main_menu():
global menu_active, obstacles, score, high_score, third_obstacle_added, fourth_obstacle_added
while menu_active:
clock.tick(60)
# Update the background gameplay
for obstacle in obstacles:
obstacle["y"] += obstacle_speed
if obstacle["y"] > height:
obstacle["y"] = -obstacle_height
obstacle["lane"] = random.randint(0, lane_count - 1)
obstacle["skin"] = random.choice(obstacle_skins) # Assign a new random skin
# Draw the game in the background
draw_game()
# Draw menu overlay
title_text = title_font.render("Car Game", True, WHITE)
play_text = font.render("Play", True, WHITE)
high_score_text = font.render(f"High Score: {high_score}", True, WHITE)
play_button_rect = pygame.Rect(width // 2 - 100, 300, 200, 50) # Play button dimensions
# Draw title, high score, and button
win.blit(title_text, (width // 2 - title_text.get_width() // 2, 100))
win.blit(high_score_text, (width // 2 - high_score_text.get_width() // 2, 200))
pygame.draw.rect(win, BLUE, play_button_rect)
win.blit(play_text, (play_button_rect.x + play_button_rect.width // 2 - play_text.get_width() // 2,
play_button_rect.y + play_button_rect.height // 2 - play_text.get_height() // 2))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if play_button_rect.collidepoint(event.pos): # Start game
score = 0
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": random.choice(obstacle_skins)},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": random.choice(obstacle_skins)},
]
third_obstacle_added = False
fourth_obstacle_added = False
menu_active = False # Exit the menu
# Main loop
main_menu() # Display the main menu
while run:
clock.tick(60)
# Increase obstacle speed as score increases
obstacle_speed = 5 + (score // 10)
# Add a third obstacle when the score reaches 10
if score >= 10 and not third_obstacle_added:
obstacles.append({"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 400, "skin": random.choice(obstacle_skins)})
third_obstacle_added = True
# Add a fourth obstacle when the score reaches 20
if score >= 20 and not fourth_obstacle_added:
obstacles.append({"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 600, "skin": random.choice(obstacle_skins)})
fourth_obstacle_added = True
draw_game()
pygame.display.update()
# Update obstacles
for obstacle in obstacles:
obstacle["y"] += obstacle_speed
if obstacle["y"] > height:
obstacle["y"] = -obstacle_height
obstacle["lane"] = random.randint(0, lane_count - 1)
obstacle["skin"] = random.choice(obstacle_skins)
score += 1 # Increase score when an obstacle resets
# Smoothly move the car towards the target x position
if car_x < car_target_x:
car_x += min(car_speed, car_target_x - car_x)
elif car_x > car_target_x:
car_x -= min(car_speed, car_x - car_target_x)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN: # Detect key press
if event.key == pygame.K_LEFT and car_lane > 0:
car_lane -= 1
car_target_x = lanes[car_lane] - car_width // 2
elif event.key == pygame.K_RIGHT and car_lane < lane_count - 1:
car_lane += 1
car_target_x = lanes[car_lane] - car_width // 2
# Check for collisions
car_rect = pygame.Rect(car_x, car_y, car_width, car_height)
for obstacle in obstacles:
obstacle_x = lanes[obstacle["lane"]] - obstacle_width // 2
# Adjust obstacle hitbox to be smaller (10% of original size)
obstacle_hitbox_width = obstacle_width * 0.1
obstacle_hitbox_height = obstacle_height * 0.1
obstacle_hitbox_x = obstacle_x + (obstacle_width - obstacle_hitbox_width) // 2
obstacle_hitbox_y = obstacle["y"] + (obstacle_height - obstacle_hitbox_height) // 2
obstacle_rect = pygame.Rect(
obstacle_hitbox_x, obstacle_hitbox_y, obstacle_hitbox_width, obstacle_hitbox_height
)
if car_rect.colliderect(obstacle_rect):
end_game_screen() # Display end game screen
This puts the speedometer text in the top-right corner and updates live with the current speed.
Let me know if you want a graphical (dial/needle) style speedometer instead.
High score handling
high_score_file = "highscore.txt"
def load_high_score():
"""Load the high score from a file."""
if os.path.exists(high_score_file):
with open(high_score_file, "r") as file:
try:
return int(file.read().strip())
except ValueError:
return 0
return 0
def save_high_score(high_score):
"""Save the high score to a file."""
with open(high_score_file, "w") as file:
file.write(str(high_score))
Initialize high score
high_score = load_high_score()
def draw_highway():
# Draw the asphalt background
win.fill(ASPHALT)
code
# Draw road edges (shoulders)
pygame.draw.rect(win, ROAD_EDGE, (road_left - 20, 0, 20, height)) # Left shoulder
pygame.draw.rect(win, ROAD_EDGE, (road_right, 0, 20, height)) # Right shoulder
# Draw the road itself
pygame.draw.rect(win, ASPHALT, (road_left, 0, road_right - road_left, height)) # Road area
# Draw solid white lines for highway boundaries
pygame.draw.line(win, WHITE, (road_left, 0), (road_left, height), 4) # Left boundary
pygame.draw.line(win, WHITE, (road_right, 0), (road_right, height), 4) # Right boundary
# Draw moving dashed yellow lane dividers
global line_offset
line_offset = (line_offset + 5) % 40 # Speed of lane line movement
for i in range(1, lane_count):
lane_x = road_left + i * lane_width
for y in range(-line_offset, height, 40):
pygame.draw.rect(win, YELLOW, (lane_x - 2, y, 4, 20))
def draw_game():
draw_highway()
visual_car_x = car_x - (visual_car_width - car_width) // 2 # Adjust visual car to match hitbox
def end_game_screen():
global run, menu_active, score, high_score, obstacles, third_obstacle_added, fourth_obstacle_added
code
# Update high score if current score is higher
if score > high_score:
high_score = score
save_high_score(high_score) # Save the new high score
while True:
win.fill(ASPHALT)
end_text = title_font.render("Game Over", True, RED)
score_text = font.render(f"Your Score: {score}", True, WHITE)
high_score_text = font.render(f"High Score: {high_score}", True, WHITE)
play_again_text = font.render("Play Again", True, WHITE)
quit_text = font.render("Quit", True, WHITE)
play_again_button = pygame.Rect(width // 2 - 100, 300, 200, 50) # Play Again button
quit_button = pygame.Rect(width // 2 - 100, 400, 200, 50) # Quit button
# Draw Game Over screen
win.blit(end_text, (width // 2 - end_text.get_width() // 2, 100))
win.blit(score_text, (width // 2 - score_text.get_width() // 2, 200))
win.blit(high_score_text, (width // 2 - high_score_text.get_width() // 2, 250))
pygame.draw.rect(win, BLUE, play_again_button)
pygame.draw.rect(win, BLUE, quit_button)
win.blit(play_again_text, (play_again_button.x + play_again_button.width // 2 - play_again_text.get_width() // 2,
play_again_button.y + play_again_button.height // 2 - play_again_text.get_height() // 2))
win.blit(quit_text, (quit_button.x + quit_button.width // 2 - quit_text.get_width() // 2,
quit_button.y + quit_button.height // 2 - quit_text.get_height() // 2))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if play_again_button.collidepoint(event.pos): # Restart game
score = 0
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": random.choice(obstacle_skins)},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": random.choice(obstacle_skins)},
]
third_obstacle_added = False
fourth_obstacle_added = False
return # Exit the end game screen loop
elif quit_button.collidepoint(event.pos): # Quit game
pygame.quit()
exit()
def main_menu():
global menu_active, obstacles, score, high_score, third_obstacle_added, fourth_obstacle_added
code
while menu_active:
clock.tick(60)
# Update the background gameplay
for obstacle in obstacles:
obstacle["y"] += obstacle_speed
if obstacle["y"] > height:
obstacle["y"] = -obstacle_height
obstacle["lane"] = random.randint(0, lane_count - 1)
obstacle["skin"] = random.choice(obstacle_skins) # Assign a new random skin
# Draw the game in the background
draw_game()
# Draw menu overlay
title_text = title_font.render("Car Game", True, WHITE)
play_text = font.render("Play", True, WHITE)
high_score_text = font.render(f"High Score: {high_score}", True, WHITE)
play_button_rect = pygame.Rect(width // 2 - 100, 300, 200, 50) # Play button dimensions
# Draw title, high score, and button
win.blit(title_text, (width // 2 - title_text.get_width() // 2, 100))
win.blit(high_score_text, (width // 2 - high_score_text.get_width() // 2, 200))
pygame.draw.rect(win, BLUE, play_button_rect)
win.blit(play_text, (play_button_rect.x + play_button_rect.width // 2 - play_text.get_width() // 2,
play_button_rect.y + play_button_rect.height // 2 - play_text.get_height() // 2))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if play_button_rect.collidepoint(event.pos): # Start game
score = 0
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": random.choice(obstacle_skins)},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": random.choice(obstacle_skins)},
]
third_obstacle_added = False
fourth_obstacle_added = False
menu_active = False # Exit the menu
Main loop
main_menu() # Display the main menu
while run:
clock.tick(60)
code
# Increase obstacle speed as score increases
obstacle_speed = 5 + (score // 10)
# Add a third obstacle when the score reaches 10
if score >= 10 and not third_obstacle_added:
obstacles.append({"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 400, "skin": random.choice(obstacle_skins)})
third_obstacle_added = True
# Add a fourth obstacle when the score reaches 20
if score >= 20 and not fourth_obstacle_added:
obstacles.append({"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 600, "skin": random.choice(obstacle_skins)})
fourth_obstacle_added = True
draw_game()
pygame.display.update()
# Update obstacles
for obstacle in obstacles:
obstacle["y"] += obstacle_speed
if obstacle["y"] > height:
obstacle["y"] = -obstacle_height
obstacle["lane"] = random.randint(0, lane_count - 1)
obstacle["skin"] = random.choice(obstacle_skins)
score += 1 # Increase score when an obstacle resets
# Smoothly move the car towards the target x position
if car_x < car_target_x:
car_x += min(car_speed, car_target_x - car_x)
elif car_x > car_target_x:
car_x -= min(car_speed, car_x - car_target_x)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN: # Detect key press
if event.key == pygame.K_LEFT and car_lane > 0:
car_lane -= 1
car_target_x = lanes[car_lane] - car_width // 2
elif event.key == pygame.K_RIGHT and car_lane < lane_count - 1:
car_lane += 1
car_target_x = lanes[car_lane] - car_width // 2
# Check for collisions
car_rect = pygame.Rect(car_x, car_y, car_width, car_height)
for obstacle in obstacles:
obstacle_x = lanes[obstacle["lane"]] - obstacle_width // 2
# Adjust obstacle hitbox to be smaller (10% of original size)
obstacle_hitbox_width = obstacle_width * 0.1
obstacle_hitbox_height = obstacle_height * 0.1
obstacle_hitbox_x = obstacle_x + (obstacle_width - obstacle_hitbox_width) // 2
obstacle_hitbox_y = obstacle["y"] + (obstacle_height - obstacle_hitbox_height) // 2
obstacle_rect = pygame.Rect(
obstacle_hitbox_x, obstacle_hitbox_y, obstacle_hitbox_width, obstacle_hitbox_height
)
if car_rect.colliderect(obstacle_rect):
end_game_screen() # Display end game screen move the speed to the bottom right and make it look like a cars odometer
Replace the speed display code inside your draw_game() function with:
python
def draw_game():
draw_highway()
visual_car_x = car_x - (visual_car_width - car_width) // 2 # Adjust visual car to match hitbox
win.blit(player_car_img, (visual_car_x, car_y)) # Draw player's car
# Draw obstacles
for obstacle in obstacles:
obstacle_x = lanes[obstacle["lane"]] - visual_obstacle_width // 2
win.blit(obstacle["skin"], (obstacle_x, obstacle["y"]))
# Display the score
score_text = font.render(f"Score: {score}", True, WHITE)
win.blit(score_text, (10, 10))
# Draw odometer-style speedometer in bottom-right corner
draw_speedometer(obstacle_speed)
Explanation:
The draw_speedometer function draws a rounded black box with a white border and the speed displayed inside using a monospace font for that classic odometer look.
The speed is zero-padded to 3 digits to resemble a real odometer.
It is positioned 20 px from the bottom and right edges.
The main draw_game() function calls this to ensure it updates every frame.
Let me know if you want me to provide your entire script with this incorporated!
run = True
menu_active = True
score = 0
line_offset = 0 # Offset for moving dashed lines
High score handling
high_score_file = "highscore.txt"
def load_high_score():
"""Load the high score from a file."""
if os.path.exists(high_score_file):
with open(high_score_file, "r") as file:
try:
return int(file.read().strip())
except ValueError:
return 0
return 0
def save_high_score(high_score):
"""Save the high score to a file."""
with open(high_score_file, "w") as file:
file.write(str(high_score))
Initialize high score
high_score = load_high_score()
def draw_highway():
# Draw the asphalt background
win.fill(ASPHALT)
code
# Draw road edges (shoulders)
pygame.draw.rect(win, ROAD_EDGE, (road_left - 20, 0, 20, height)) # Left shoulder
pygame.draw.rect(win, ROAD_EDGE, (road_right, 0, 20, height)) # Right shoulder
# Draw the road itself
pygame.draw.rect(win, ASPHALT, (road_left, 0, road_right - road_left, height)) # Road area
# Draw solid white lines for highway boundaries
pygame.draw.line(win, WHITE, (road_left, 0), (road_left, height), 4) # Left boundary
pygame.draw.line(win, WHITE, (road_right, 0), (road_right, height), 4) # Right boundary
# Draw moving dashed yellow lane dividers
global line_offset
line_offset = (line_offset + 5) % 40 # Speed of lane line movement
for i in range(1, lane_count):
lane_x = road_left + i * lane_width
for y in range(-line_offset, height, 40):
pygame.draw.rect(win, YELLOW, (lane_x - 2, y, 4, 20))
def draw_game():
draw_highway()
visual_car_x = car_x - (visual_car_width - car_width) // 2 # Adjust visual car to match hitbox
def end_game_screen():
global run, menu_active, score, high_score, obstacles, third_obstacle_added, fourth_obstacle_added
code
# Update high score if current score is higher
if score > high_score:
high_score = score
save_high_score(high_score) # Save the new high score
while True:
win.fill(ASPHALT)
end_text = title_font.render("Game Over", True, RED)
score_text = font.render(f"Your Score: {score}", True, WHITE)
high_score_text = font.render(f"High Score: {high_score}", True, WHITE)
play_again_text = font.render("Play Again", True, WHITE)
quit_text = font.render("Quit", True, WHITE)
play_again_button = pygame.Rect(width // 2 - 100, 300, 200, 50) # Play Again button
quit_button = pygame.Rect(width // 2 - 100, 400, 200, 50) # Quit button
# Draw Game Over screen
win.blit(end_text, (width // 2 - end_text.get_width() // 2, 100))
win.blit(score_text, (width // 2 - score_text.get_width() // 2, 200))
win.blit(high_score_text, (width // 2 - high_score_text.get_width() // 2, 250))
pygame.draw.rect(win, BLUE, play_again_button)
pygame.draw.rect(win, BLUE, quit_button)
win.blit(play_again_text, (play_again_button.x + play_again_button.width // 2 - play_again_text.get_width() // 2,
play_again_button.y + play_again_button.height // 2 - play_again_text.get_height() // 2))
win.blit(quit_text, (quit_button.x + quit_button.width // 2 - quit_text.get_width() // 2,
quit_button.y + quit_button.height // 2 - quit_text.get_height() // 2))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if play_again_button.collidepoint(event.pos): # Restart game
score = 0
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": random.choice(obstacle_skins)},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": random.choice(obstacle_skins)},
]
third_obstacle_added = False
fourth_obstacle_added = False
return # Exit the end game screen loop
elif quit_button.collidepoint(event.pos): # Quit game
pygame.quit()
exit()
def main_menu():
global menu_active, obstacles, score, high_score, third_obstacle_added, fourth_obstacle_added
code
while menu_active:
clock.tick(60)
# Update the background gameplay
for obstacle in obstacles:
obstacle["y"] += obstacle_speed
if obstacle["y"] > height:
obstacle["y"] = -obstacle_height
obstacle["lane"] = random.randint(0, lane_count - 1)
obstacle["skin"] = random.choice(obstacle_skins) # Assign a new random skin
# Draw the game in the background
draw_game()
# Draw menu overlay
title_text = title_font.render("Car Game", True, WHITE)
play_text = font.render("Play", True, WHITE)
high_score_text = font.render(f"High Score: {high_score}", True, WHITE)
play_button_rect = pygame.Rect(width // 2 - 100, 300, 200, 50) # Play button dimensions
# Draw title, high score, and button
win.blit(title_text, (width // 2 - title_text.get_width() // 2, 100))
win.blit(high_score_text, (width // 2 - high_score_text.get_width() // 2, 200))
pygame.draw.rect(win, BLUE, play_button_rect)
win.blit(play_text, (play_button_rect.x + play_button_rect.width // 2 - play_text.get_width() // 2,
play_button_rect.y + play_button_rect.height // 2 - play_text.get_height() // 2))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if play_button_rect.collidepoint(event.pos): # Start game
score = 0
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": random.choice(obstacle_skins)},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": random.choice(obstacle_skins)},
]
third_obstacle_added = False
fourth_obstacle_added = False
menu_active = False # Exit the menu
Main loop
main_menu() # Display the main menu
while run:
clock.tick(60)
code
# Increase obstacle speed as score increases
obstacle_speed = 5 + (score // 10)
# Add a third obstacle when the score reaches 10
if score >= 10 and not third_obstacle_added:
obstacles.append({"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 400, "skin": random.choice(obstacle_skins)})
third_obstacle_added = True
# Add a fourth obstacle when the score reaches 20
if score >= 20 and not fourth_obstacle_added:
obstacles.append({"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 600, "skin": random.choice(obstacle_skins)})
fourth_obstacle_added = True
draw_game()
pygame.display.update()
# Update obstacles
for obstacle in obstacles:
obstacle["y"] += obstacle_speed
if obstacle["y"] > height:
obstacle["y"] = -obstacle_height
obstacle["lane"] = random.randint(0, lane_count - 1)
obstacle["skin"] = random.choice(obstacle_skins)
score += 1 # Increase score when an obstacle resets
# Smoothly move the car towards the target x position
if car_x < car_target_x:
car_x += min(car_speed, car_target_x - car_x)
elif car_x > car_target_x:
car_x -= min(car_speed, car_x - car_target_x)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN: # Detect key press
if event.key == pygame.K_LEFT and car_lane > 0:
car_lane -= 1
car_target_x = lanes[car_lane] - car_width // 2
elif event.key == pygame.K_RIGHT and car_lane < lane_count - 1:
car_lane += 1
car_target_x = lanes[car_lane] - car_width // 2
# Check for collisions
car_rect = pygame.Rect(car_x, car_y, car_width, car_height)
for obstacle in obstacles:
obstacle_x = lanes[obstacle["lane"]] - obstacle_width // 2
# Adjust obstacle hitbox to be smaller (10% of original size)
obstacle_hitbox_width = obstacle_width * 0.1
obstacle_hitbox_height = obstacle_height * 0.1
obstacle_hitbox_x = obstacle_x + (obstacle_width - obstacle_hitbox_width) // 2
obstacle_hitbox_y = obstacle["y"] + (obstacle_height - obstacle_hitbox_height) // 2
obstacle_rect = pygame.Rect(
obstacle_hitbox_x, obstacle_hitbox_y, obstacle_hitbox_width, obstacle_hitbox_height
)
if car_rect.colliderect(obstacle_rect):
end_game_screen() # Display end game screen
import pygame
import random
import os # For file handling
pygame.init()
# Window settings
width = 700
height = 600
win = pygame.display.set_mode((width, height))
pygame.display.set_caption("Car Game") # Updated title
# Colors
ASPHALT = (50, 50, 50)
WHITE = (255, 255, 255)
YELLOW = (255, 255, 0)
ROAD_EDGE = (180, 180, 180)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
# Road and lanes
road_left = 100
road_right = 600
lane_count = 5
lane_width = (road_right - road_left) // lane_count
lanes = [road_left + i * lane_width + lane_width // 2 for i in range(lane_count)] # center x of each lane
# Car settings (hitbox dimensions)
car_width = 70 # Player car hitbox width
car_height = 140 # Player car hitbox height
car_lane = 2 # Start in the middle lane
car_x = lanes[car_lane] - car_width // 2 # Current x position
car_target_x = car_x # Target x position for smooth movement
car_y = height - car_height - 10
car_speed = 10 # Speed of smooth movement (pixels per frame)
# Obstacle settings (hitbox dimensions)
obstacle_width = 70 # Obstacle car hitbox width
obstacle_height = 120 # Obstacle car hitbox height
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": None},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": None}, # Second car starts farther away
]
obstacle_speed = 5 # Initial speed
third_obstacle_added = False # Flag for adding a third obstacle
fourth_obstacle_added = False # Flag for adding a fourth obstacle
# Visual dimensions (for rendering only)
visual_car_width = 120 # Player car appears thicker
visual_obstacle_width = 70 # Obstacle car appears thinner
# Load car images with updated visual dimensions
player_car_img = pygame.image.load("car_player.png") # Replace with the path to your player's car image
player_car_img = pygame.transform.scale(player_car_img, (visual_car_width, car_height))
# Load multiple obstacle images
obstacle_skins = [
pygame.transform.scale(pygame.image.load("car_obstacle1.png"), (visual_obstacle_width, obstacle_height)),
pygame.transform.scale(pygame.image.load("car_obstacle2.png"), (visual_obstacle_width, obstacle_height)),
pygame.transform.scale(pygame.image.load("car_obstacle3.png"), (visual_obstacle_width, obstacle_height)),
pygame.transform.scale(pygame.image.load("car_obstacle4.png"), (visual_obstacle_width, obstacle_height)),
]
# Assign random skins to initial obstacles
for obstacle in obstacles:
obstacle["skin"] = random.choice(obstacle_skins)
clock = pygame.time.Clock()
font = pygame.font.Font(pygame.font.match_font('arial'), 36) # Stylish font
title_font = pygame.font.Font(pygame.font.match_font('arial'), 72)
# Load a monospace font for odometer style speed display
odometer_font = pygame.font.SysFont('consolas', 40, bold=True)
# Game variables
run = True
menu_active = True
score = 0
line_offset = 0 # Offset for moving dashed lines
# High score handling
high_score_file = "highscore.txt"
def load_high_score():
"""Load the high score from a file."""
if os.path.exists(high_score_file):
with open(high_score_file, "r") as file:
try:
return int(file.read().strip())
except ValueError:
return 0
return 0
def save_high_score(high_score):
"""Save the high score to a file."""
with open(high_score_file, "w") as file:
file.write(str(high_score))
# Initialize high score
high_score = load_high_score()
def draw_speedometer(speed):
# Format speed as 3-digit zero-padded string
speed_str = f"{speed:03d} km/h"
# Render the text
speed_text = odometer_font.render(speed_str, True, WHITE)
padding_x = 15
padding_y = 10
box_width = speed_text.get_width() + 2 * padding_x
box_height = speed_text.get_height() + 2 * padding_y
x = width - box_width - 20
y = height - box_height - 20
# Draw background rectangle (black) with rounded corners
pygame.draw.rect(win, BLACK, (x, y, box_width, box_height), border_radius=10)
# Draw white border rectangle
pygame.draw.rect(win, WHITE, (x, y, box_width, box_height), 3, border_radius=10)
# Blit speed text inside the box
win.blit(speed_text, (x + padding_x, y + padding_y))
def draw_highway():
# Draw the asphalt background
win.fill(ASPHALT)
# Draw road edges (shoulders)
pygame.draw.rect(win, ROAD_EDGE, (road_left - 20, 0, 20, height)) # Left shoulder
pygame.draw.rect(win, ROAD_EDGE, (road_right, 0, 20, height)) # Right shoulder
# Draw the road itself
pygame.draw.rect(win, ASPHALT, (road_left, 0, road_right - road_left, height)) # Road area
# Draw solid white lines for highway boundaries
pygame.draw.line(win, WHITE, (road_left, 0), (road_left, height), 4) # Left boundary
pygame.draw.line(win, WHITE, (road_right, 0), (road_right, height), 4) # Right boundary
# Draw moving dashed yellow lane dividers
global line_offset
line_offset = (line_offset + 5) % 40 # Speed of lane line movement
for i in range(1, lane_count):
lane_x = road_left + i * lane_width
for y in range(-line_offset, height, 40):
pygame.draw.rect(win, YELLOW, (lane_x - 2, y, 4, 20))
def draw_game():
draw_highway()
visual_car_x = car_x - (visual_car_width - car_width) // 2 # Adjust visual car to match hitbox
win.blit(player_car_img, (visual_car_x, car_y)) # Draw player's car
# Draw obstacles
for obstacle in obstacles:
obstacle_x = lanes[obstacle["lane"]] - visual_obstacle_width // 2
win.blit(obstacle["skin"], (obstacle_x, obstacle["y"]))
# Display the score
score_text = font.render(f"Score: {score}", True, WHITE)
win.blit(score_text, (10, 10))
# Draw odometer-style speedometer in bottom-right corner
draw_speedometer(obstacle_speed)
def end_game_screen():
global run, menu_active, score, high_score, obstacles, third_obstacle_added, fourth_obstacle_added
# Update high score if current score is higher
if score > high_score:
high_score = score
save_high_score(high_score) # Save the new high score
while True:
win.fill(ASPHALT)
end_text = title_font.render("Game Over", True, RED)
score_text = font.render(f"Your Score: {score}", True, WHITE)
high_score_text = font.render(f"High Score: {high_score}", True, WHITE)
play_again_text = font.render("Play Again", True, WHITE)
quit_text = font.render("Quit", True, WHITE)
play_again_button = pygame.Rect(width // 2 - 100, 300, 200, 50) # Play Again button
quit_button = pygame.Rect(width // 2 - 100, 400, 200, 50) # Quit button
# Draw Game Over screen
win.blit(end_text, (width // 2 - end_text.get_width() // 2, 100))
win.blit(score_text, (width // 2 - score_text.get_width() // 2, 200))
win.blit(high_score_text, (width // 2 - high_score_text.get_width() // 2, 250))
pygame.draw.rect(win, BLUE, play_again_button)
pygame.draw.rect(win, BLUE, quit_button)
win.blit(play_again_text, (play_again_button.x + play_again_button.width // 2 - play_again_text.get_width() // 2,
play_again_button.y + play_again_button.height // 2 - play_again_text.get_height() // 2))
win.blit(quit_text, (quit_button.x + quit_button.width // 2 - quit_text.get_width() // 2,
quit_button.y + quit_button.height // 2 - quit_text.get_height() // 2))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if play_again_button.collidepoint(event.pos): # Restart game
score = 0
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": random.choice(obstacle_skins)},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": random.choice(obstacle_skins)},
]
third_obstacle_added = False
fourth_obstacle_added = False
return # Exit the end game screen loop
elif quit_button.collidepoint(event.pos): # Quit game
pygame.quit()
exit()
def main_menu():
global menu_active, obstacles, score, high_score, third_obstacle_added, fourth_obstacle_added
while menu_active:
clock.tick(60)
# Update the background gameplay
for obstacle in obstacles:
obstacle["y"] += obstacle_speed
if obstacle["y"] > height:
obstacle["y"] = -obstacle_height
obstacle["lane"] = random.randint(0, lane_count - 1)
obstacle["skin"] = random.choice(obstacle_skins) # Assign a new random skin
# Draw the game in the background
draw_game()
# Draw menu overlay
title_text = title_font.render("Car Game", True, WHITE)
play_text = font.render("Play", True, WHITE)
high_score_text = font.render(f"High Score: {high_score}", True, WHITE)
play_button_rect = pygame.Rect(width // 2 - 100, 300, 200, 50) # Play button dimensions
# Draw title, high score, and button
win.blit(title_text, (width // 2 - title_text.get_width() // 2, 100))
win.blit(high_score_text, (width // 2 - high_score_text.get_width() // 2, 200))
pygame.draw.rect(win, BLUE, play_button_rect)
win.blit(play_text, (play_button_rect.x + play_button_rect.width // 2 - play_text.get_width() // 2,
play_button_rect.y + play_button_rect.height // 2 - play_text.get_height() // 2))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if play_button_rect.collidepoint(event.pos): # Start game
score = 0
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": random.choice(obstacle_skins)},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": random.choice(obstacle_skins)},
]
third_obstacle_added = False
fourth_obstacle_added = False
menu_active = False # Exit the menu
# Main loop
main_menu() # Display the main menu
while run:
clock.tick(60)
# Increase obstacle speed as score increases
obstacle_speed = 5 + (score // 10)
# Add a third obstacle when the score reaches 10
if score >= 10 and not third_obstacle_added:
obstacles.append({"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 400, "skin": random.choice(obstacle_skins)})
third_obstacle_added = True
# Add a fourth obstacle when the score reaches 20
if score >= 20 and not fourth_obstacle_added:
obstacles.append({"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 600, "skin": random.choice(obstacle_skins)})
fourth_obstacle_added = True
draw_game()
pygame.display.update()
# Update obstacles
for obstacle in obstacles:
obstacle["y"] += obstacle_speed
if obstacle["y"] > height:
obstacle["y"] = -obstacle_height
obstacle["lane"] = random.randint(0, lane_count - 1)
obstacle["skin"] = random.choice(obstacle_skins)
score += 1 # Increase score when an obstacle resets
# Smoothly move the car towards the target x position
if car_x < car_target_x:
car_x += min(car_speed, car_target_x - car_x)
elif car_x > car_target_x:
car_x -= min(car_speed, car_x - car_target_x)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN: # Detect key press
if event.key == pygame.K_LEFT and car_lane > 0:
car_lane -= 1
car_target_x = lanes[car_lane] - car_width // 2
elif event.key == pygame.K_RIGHT and car_lane < lane_count - 1:
car_lane += 1
car_target_x = lanes[car_lane] - car_width // 2
# Check for collisions
car_rect = pygame.Rect(car_x, car_y, car_width, car_height)
for obstacle in obstacles:
obstacle_x = lanes[obstacle["lane"]] - obstacle_width // 2
# Adjust obstacle hitbox to be smaller (10% of original size)
obstacle_hitbox_width = obstacle_width * 0.1
obstacle_hitbox_height = obstacle_height * 0.1
obstacle_hitbox_x = obstacle_x + (obstacle_width - obstacle_hitbox_width) // 2
obstacle_hitbox_y = obstacle["y"] + (obstacle_height - obstacle_hitbox_height) // 2
obstacle_rect = pygame.Rect(
obstacle_hitbox_x, obstacle_hitbox_y, obstacle_hitbox_width, obstacle_hitbox_height
)
if car_rect.colliderect(obstacle_rect):
end_game_screen() # Display end game screen
Only substantial addition:
python
# Load a monospace font for odometer style speed display
odometer_font = pygame.font.SysFont('consolas', 40, bold=True)
def draw_speedometer(speed):
# Format speed as 3-digit zero-padded string
speed_str = f"{speed:03d} km/h"
# Render the text
speed_text = odometer_font.render(speed_str, True, WHITE)
padding_x = 15
padding_y = 10
box_width = speed_text.get_width() + 2 * padding_x
box_height = speed_text.get_height() + 2 * padding_y
x = width - box_width - 20
y = height - box_height - 20
# Draw background rectangle (black) with rounded corners
pygame.draw.rect(win, BLACK, (x, y, box_width, box_height), border_radius=10)
# Draw white border rectangle
pygame.draw.rect(win, WHITE, (x, y, box_width, box_height), 3, border_radius=10)
# Blit speed text inside the box
win.blit(speed_text, (x + padding_x, y + padding_y))
And in your draw_game() function, replace the speed text display portion with:
python
# Draw odometer-style speedometer in bottom-right corner
draw_speedometer(obstacle_speed)
That is all! This will give you a nicely styled odometer speed display at the bottom right corner showing the current speed (obstacle speed).
Let me know if you want me to help add a more graphical speedometer or other features.
run = True
menu_active = True
score = 0
line_offset = 0 # Offset for moving dashed lines
High score handling
high_score_file = "highscore.txt"
def load_high_score():
"""Load the high score from a file."""
if os.path.exists(high_score_file):
with open(high_score_file, "r") as file:
try:
return int(file.read().strip())
except ValueError:
return 0
return 0
def save_high_score(high_score):
"""Save the high score to a file."""
with open(high_score_file, "w") as file:
file.write(str(high_score))
Initialize high score
high_score = load_high_score()
def draw_speedometer(speed):
# Format speed as 3-digit zero-padded string
speed_str = f"{speed:03d} km/h"
code
# Render the text
speed_text = odometer_font.render(speed_str, True, WHITE)
padding_x = 15
padding_y = 10
box_width = speed_text.get_width() + 2 * padding_x
box_height = speed_text.get_height() + 2 * padding_y
x = width - box_width - 20
y = height - box_height - 20
# Draw background rectangle (black) with rounded corners
pygame.draw.rect(win, BLACK, (x, y, box_width, box_height), border_radius=10)
# Draw white border rectangle
pygame.draw.rect(win, WHITE, (x, y, box_width, box_height), 3, border_radius=10)
# Blit speed text inside the box
win.blit(speed_text, (x + padding_x, y + padding_y))
def draw_highway():
# Draw the asphalt background
win.fill(ASPHALT)
code
# Draw road edges (shoulders)
pygame.draw.rect(win, ROAD_EDGE, (road_left - 20, 0, 20, height)) # Left shoulder
pygame.draw.rect(win, ROAD_EDGE, (road_right, 0, 20, height)) # Right shoulder
# Draw the road itself
pygame.draw.rect(win, ASPHALT, (road_left, 0, road_right - road_left, height)) # Road area
# Draw solid white lines for highway boundaries
pygame.draw.line(win, WHITE, (road_left, 0), (road_left, height), 4) # Left boundary
pygame.draw.line(win, WHITE, (road_right, 0), (road_right, height), 4) # Right boundary
# Draw moving dashed yellow lane dividers
global line_offset
line_offset = (line_offset + 5) % 40 # Speed of lane line movement
for i in range(1, lane_count):
lane_x = road_left + i * lane_width
for y in range(-line_offset, height, 40):
pygame.draw.rect(win, YELLOW, (lane_x - 2, y, 4, 20))
def draw_game():
draw_highway()
visual_car_x = car_x - (visual_car_width - car_width) // 2 # Adjust visual car to match hitbox
code
win.blit(player_car_img, (visual_car_x, car_y)) # Draw player's car
# Draw obstacles
for obstacle in obstacles:
obstacle_x = lanes[obstacle["lane"]] - visual_obstacle_width // 2
win.blit(obstacle["skin"], (obstacle_x, obstacle["y"]))
# Display the score
score_text = font.render(f"Score: {score}", True, WHITE)
win.blit(score_text, (10, 10))
# Draw odometer-style speedometer in bottom-right corner
draw_speedometer(obstacle_speed)
def end_game_screen():
global run, menu_active, score, high_score, obstacles, third_obstacle_added, fourth_obstacle_added
code
# Update high score if current score is higher
if score > high_score:
high_score = score
save_high_score(high_score) # Save the new high score
while True:
win.fill(ASPHALT)
end_text = title_font.render("Game Over", True, RED)
score_text = font.render(f"Your Score: {score}", True, WHITE)
high_score_text = font.render(f"High Score: {high_score}", True, WHITE)
play_again_text = font.render("Play Again", True, WHITE)
quit_text = font.render("Quit", True, WHITE)
play_again_button = pygame.Rect(width // 2 - 100, 300, 200, 50) # Play Again button
quit_button = pygame.Rect(width // 2 - 100, 400, 200, 50) # Quit button
# Draw Game Over screen
win.blit(end_text, (width // 2 - end_text.get_width() // 2, 100))
win.blit(score_text, (width // 2 - score_text.get_width() // 2, 200))
win.blit(high_score_text, (width // 2 - high_score_text.get_width() // 2, 250))
pygame.draw.rect(win, BLUE, play_again_button)
pygame.draw.rect(win, BLUE, quit_button)
win.blit(play_again_text, (play_again_button.x + play_again_button.width // 2 - play_again_text.get_width() // 2,
play_again_button.y + play_again_button.height // 2 - play_again_text.get_height() // 2))
win.blit(quit_text, (quit_button.x + quit_button.width // 2 - quit_text.get_width() // 2,
quit_button.y + quit_button.height // 2 - quit_text.get_height() // 2))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if play_again_button.collidepoint(event.pos): # Restart game
score = 0
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": random.choice(obstacle_skins)},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": random.choice(obstacle_skins)},
]
third_obstacle_added = False
fourth_obstacle_added = False
return # Exit the end game screen loop
elif quit_button.collidepoint(event.pos): # Quit game
pygame.quit()
exit()
def main_menu():
global menu_active, obstacles, score, high_score, third_obstacle_added, fourth_obstacle_added
code
while menu_active:
clock.tick(60)
# Update the background gameplay
for obstacle in obstacles:
obstacle["y"] += obstacle_speed
if obstacle["y"] > height:
obstacle["y"] = -obstacle_height
obstacle["lane"] = random.randint(0, lane_count - 1)
obstacle["skin"] = random.choice(obstacle_skins) # Assign a new random skin
# Draw the game in the background
draw_game()
# Draw menu overlay
title_text = title_font.render("Car Game", True, WHITE)
play_text = font.render("Play", True, WHITE)
high_score_text = font.render(f"High Score: {high_score}", True, WHITE)
play_button_rect = pygame.Rect(width // 2 - 100, 300, 200, 50) # Play button dimensions
# Draw title, high score, and button
win.blit(title_text, (width // 2 - title_text.get_width() // 2, 100))
win.blit(high_score_text, (width // 2 - high_score_text.get_width() // 2, 200))
pygame.draw.rect(win, BLUE, play_button_rect)
win.blit(play_text, (play_button_rect.x + play_button_rect.width // 2 - play_text.get_width() // 2,
play_button_rect.y + play_button_rect.height // 2 - play_text.get_height() // 2))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if play_button_rect.collidepoint(event.pos): # Start game
score = 0
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": random.choice(obstacle_skins)},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": random.choice(obstacle_skins)},
]
third_obstacle_added = False
fourth_obstacle_added = False
menu_active = False # Exit the menu
Main loop
main_menu() # Display the main menu
while run:
clock.tick(60)
code
# Increase obstacle speed as score increases
obstacle_speed = 5 + (score // 10)
# Add a third obstacle when the score reaches 10
if score >= 10 and not third_obstacle_added:
obstacles.append({"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 400, "skin": random.choice(obstacle_skins)})
third_obstacle_added = True
# Add a fourth obstacle when the score reaches 20
if score >= 20 and not fourth_obstacle_added:
obstacles.append({"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 600, "skin": random.choice(obstacle_skins)})
fourth_obstacle_added = True
draw_game()
pygame.display.update()
# Update obstacles
for obstacle in obstacles:
obstacle["y"] += obstacle_speed
if obstacle["y"] > height:
obstacle["y"] = -obstacle_height
obstacle["lane"] = random.randint(0, lane_count - 1)
obstacle["skin"] = random.choice(obstacle_skins)
score += 1 # Increase score when an obstacle resets
# Smoothly move the car towards the target x position
if car_x < car_target_x:
car_x += min(car_speed, car_target_x - car_x)
elif car_x > car_target_x:
car_x -= min(car_speed, car_x - car_target_x)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN: # Detect key press
if event.key == pygame.K_LEFT and car_lane > 0:
car_lane -= 1
car_target_x = lanes[car_lane] - car_width // 2
elif event.key == pygame.K_RIGHT and car_lane < lane_count - 1:
car_lane += 1
car_target_x = lanes[car_lane] - car_width // 2
# Check for collisions
car_rect = pygame.Rect(car_x, car_y, car_width, car_height)
for obstacle in obstacles:
obstacle_x = lanes[obstacle["lane"]] - obstacle_width // 2
# Adjust obstacle hitbox to be smaller (10% of original size)
obstacle_hitbox_width = obstacle_width * 0.1
obstacle_hitbox_height = obstacle_height * 0.1
obstacle_hitbox_x = obstacle_x + (obstacle_width - obstacle_hitbox_width) // 2
obstacle_hitbox_y = obstacle["y"] + (obstacle_height - obstacle_hitbox_height) // 2
obstacle_rect = pygame.Rect(
obstacle_hitbox_x, obstacle_hitbox_y, obstacle_hitbox_width, obstacle_hitbox_height
)
if car_rect.colliderect(obstacle_rect):
end_game_screen() # Display end game screen make it so you start at 60 km/ h
run = True
menu_active = True
score = 0
line_offset = 0 # Offset for moving dashed lines
High score handling
high_score_file = "highscore.txt"
def load_high_score():
"""Load the high score from a file."""
if os.path.exists(high_score_file):
with open(high_score_file, "r") as file:
try:
return int(file.read().strip())
except ValueError:
return 0
return 0
def save_high_score(high_score):
"""Save the high score to a file."""
with open(high_score_file, "w") as file:
file.write(str(high_score))
Initialize high score
high_score = load_high_score()
def draw_speedometer(speed):
# Format speed as 3-digit zero-padded string
speed_str = f"{speed:03d} km/h"
code
# Render the text
speed_text = odometer_font.render(speed_str, True, WHITE)
padding_x = 15
padding_y = 10
box_width = speed_text.get_width() + 2 * padding_x
box_height = speed_text.get_height() + 2 * padding_y
x = width - box_width - 20
y = height - box_height - 20
# Draw background rectangle (black) with rounded corners
pygame.draw.rect(win, BLACK, (x, y, box_width, box_height), border_radius=10)
# Draw white border rectangle
pygame.draw.rect(win, WHITE, (x, y, box_width, box_height), 3, border_radius=10)
# Blit speed text inside the box
win.blit(speed_text, (x + padding_x, y + padding_y))
def draw_highway():
# Draw the asphalt background
win.fill(ASPHALT)
code
# Draw road edges (shoulders)
pygame.draw.rect(win, ROAD_EDGE, (road_left - 20, 0, 20, height)) # Left shoulder
pygame.draw.rect(win, ROAD_EDGE, (road_right, 0, 20, height)) # Right shoulder
# Draw the road itself
pygame.draw.rect(win, ASPHALT, (road_left, 0, road_right - road_left, height)) # Road area
# Draw solid white lines for highway boundaries
pygame.draw.line(win, WHITE, (road_left, 0), (road_left, height), 4) # Left boundary
pygame.draw.line(win, WHITE, (road_right, 0), (road_right, height), 4) # Right boundary
# Draw moving dashed yellow lane dividers
global line_offset
line_offset = (line_offset + 5) % 40 # Speed of lane line movement
for i in range(1, lane_count):
lane_x = road_left + i * lane_width
for y in range(-line_offset, height, 40):
pygame.draw.rect(win, YELLOW, (lane_x - 2, y, 4, 20))
def draw_game():
draw_highway()
visual_car_x = car_x - (visual_car_width - car_width) // 2 # Adjust visual car to match hitbox
code
win.blit(player_car_img, (visual_car_x, car_y)) # Draw player's car
# Draw obstacles
for obstacle in obstacles:
obstacle_x = lanes[obstacle["lane"]] - visual_obstacle_width // 2
win.blit(obstacle["skin"], (obstacle_x, obstacle["y"]))
# Display the score
score_text = font.render(f"Score: {score}", True, WHITE)
win.blit(score_text, (10, 10))
# Draw odometer-style speedometer in bottom-right corner
draw_speedometer(obstacle_speed)
def end_game_screen():
global run, menu_active, score, high_score, obstacles, third_obstacle_added, fourth_obstacle_added
code
# Update high score if current score is higher
if score > high_score:
high_score = score
save_high_score(high_score) # Save the new high score
while True:
win.fill(ASPHALT)
end_text = title_font.render("Game Over", True, RED)
score_text = font.render(f"Your Score: {score}", True, WHITE)
high_score_text = font.render(f"High Score: {high_score}", True, WHITE)
play_again_text = font.render("Play Again", True, WHITE)
quit_text = font.render("Quit", True, WHITE)
play_again_button = pygame.Rect(width // 2 - 100, 300, 200, 50) # Play Again button
quit_button = pygame.Rect(width // 2 - 100, 400, 200, 50) # Quit button
# Draw Game Over screen
win.blit(end_text, (width // 2 - end_text.get_width() // 2, 100))
win.blit(score_text, (width // 2 - score_text.get_width() // 2, 200))
win.blit(high_score_text, (width // 2 - high_score_text.get_width() // 2, 250))
pygame.draw.rect(win, BLUE, play_again_button)
pygame.draw.rect(win, BLUE, quit_button)
win.blit(play_again_text, (play_again_button.x + play_again_button.width // 2 - play_again_text.get_width() // 2,
play_again_button.y + play_again_button.height // 2 - play_again_text.get_height() // 2))
win.blit(quit_text, (quit_button.x + quit_button.width // 2 - quit_text.get_width() // 2,
quit_button.y + quit_button.height // 2 - quit_text.get_height() // 2))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if play_again_button.collidepoint(event.pos): # Restart game
score = 0
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": random.choice(obstacle_skins)},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": random.choice(obstacle_skins)},
]
third_obstacle_added = False
fourth_obstacle_added = False
return # Exit the end game screen loop
elif quit_button.collidepoint(event.pos): # Quit game
pygame.quit()
exit()
def main_menu():
global menu_active, obstacles, score, high_score, third_obstacle_added, fourth_obstacle_added
code
while menu_active:
clock.tick(60)
# Update the background gameplay
for obstacle in obstacles:
obstacle["y"] += obstacle_speed
if obstacle["y"] > height:
obstacle["y"] = -obstacle_height
obstacle["lane"] = random.randint(0, lane_count - 1)
obstacle["skin"] = random.choice(obstacle_skins) # Assign a new random skin
# Draw the game in the background
draw_game()
# Draw menu overlay
title_text = title_font.render("Car Game", True, WHITE)
play_text = font.render("Play", True, WHITE)
high_score_text = font.render(f"High Score: {high_score}", True, WHITE)
play_button_rect = pygame.Rect(width // 2 - 100, 300, 200, 50) # Play button dimensions
# Draw title, high score, and button
win.blit(title_text, (width // 2 - title_text.get_width() // 2, 100))
win.blit(high_score_text, (width // 2 - high_score_text.get_width() // 2, 200))
pygame.draw.rect(win, BLUE, play_button_rect)
win.blit(play_text, (play_button_rect.x + play_button_rect.width // 2 - play_text.get_width() // 2,
play_button_rect.y + play_button_rect.height // 2 - play_text.get_height() // 2))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if play_button_rect.collidepoint(event.pos): # Start game
score = 0
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": random.choice(obstacle_skins)},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": random.choice(obstacle_skins)},
]
third_obstacle_added = False
fourth_obstacle_added = False
menu_active = False # Exit the menu
Main loop
main_menu() # Display the main menu
while run:
clock.tick(60)
code
# Increase obstacle speed as score increases
obstacle_speed = 5 + (score // 10)
# Add a third obstacle when the score reaches 10
if score >= 10 and not third_obstacle_added:
obstacles.append({"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 400, "skin": random.choice(obstacle_skins)})
third_obstacle_added = True
# Add a fourth obstacle when the score reaches 20
if score >= 20 and not fourth_obstacle_added:
obstacles.append({"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 600, "skin": random.choice(obstacle_skins)})
fourth_obstacle_added = True
draw_game()
pygame.display.update()
# Update obstacles
for obstacle in obstacles:
obstacle["y"] += obstacle_speed
if obstacle["y"] > height:
obstacle["y"] = -obstacle_height
obstacle["lane"] = random.randint(0, lane_count - 1)
obstacle["skin"] = random.choice(obstacle_skins)
score += 1 # Increase score when an obstacle resets
# Smoothly move the car towards the target x position
if car_x < car_target_x:
car_x += min(car_speed, car_target_x - car_x)
elif car_x > car_target_x:
car_x -= min(car_speed, car_x - car_target_x)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN: # Detect key press
if event.key == pygame.K_LEFT and car_lane > 0:
car_lane -= 1
car_target_x = lanes[car_lane] - car_width // 2
elif event.key == pygame.K_RIGHT and car_lane < lane_count - 1:
car_lane += 1
car_target_x = lanes[car_lane] - car_width // 2
# Check for collisions
car_rect = pygame.Rect(car_x, car_y, car_width, car_height)
for obstacle in obstacles:
obstacle_x = lanes[obstacle["lane"]] - obstacle_width // 2
# Adjust obstacle hitbox to be smaller (10% of original size)
obstacle_hitbox_width = obstacle_width * 0.1
obstacle_hitbox_height = obstacle_height * 0.1
obstacle_hitbox_x = obstacle_x + (obstacle_width - obstacle_hitbox_width) // 2
obstacle_hitbox_y = obstacle["y"] + (obstacle_height - obstacle_hitbox_height) // 2
obstacle_rect = pygame.Rect(
obstacle_hitbox_x, obstacle_hitbox_y, obstacle_hitbox_width, obstacle_hitbox_height
)
if car_rect.colliderect(obstacle_rect):
end_game_screen() # Display end game screen
import pygame
import random
import os # For file handling
pygame.init()
# Window settings
width = 700
height = 600
win = pygame.display.set_mode((width, height))
pygame.display.set_caption("Car Game") # Updated title
# Colors
ASPHALT = (50, 50, 50)
WHITE = (255, 255, 255)
YELLOW = (255, 255, 0)
ROAD_EDGE = (180, 180, 180)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
# Road and lanes
road_left = 100
road_right = 600
lane_count = 5
lane_width = (road_right - road_left) // lane_count
lanes = [road_left + i * lane_width + lane_width // 2 for i in range(lane_count)] # center x of each lane
# Car settings (hitbox dimensions)
car_width = 70 # Player car hitbox width
car_height = 140 # Player car hitbox height
car_lane = 2 # Start in the middle lane
car_x = lanes[car_lane] - car_width // 2 # Current x position
car_target_x = car_x # Target x position for smooth movement
car_y = height - car_height - 10
car_speed = 10 # Speed of smooth movement (pixels per frame)
# Obstacle settings (hitbox dimensions)
obstacle_width = 70 # Obstacle car hitbox width
obstacle_height = 120 # Obstacle car hitbox height
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": None},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": None}, # Second car starts farther away
]
obstacle_speed = 60 # Initial speed set to 60 km/h
third_obstacle_added = False # Flag for adding a third obstacle
fourth_obstacle_added = False # Flag for adding a fourth obstacle
# Visual dimensions (for rendering only)
visual_car_width = 120 # Player car appears thicker
visual_obstacle_width = 70 # Obstacle car appears thinner
# Load car images with updated visual dimensions
player_car_img = pygame.image.load("car_player.png") # Replace with the path to your player's car image
player_car_img = pygame.transform.scale(player_car_img, (visual_car_width, car_height))
# Load multiple obstacle images
obstacle_skins = [
pygame.transform.scale(pygame.image.load("car_obstacle1.png"), (visual_obstacle_width, obstacle_height)),
pygame.transform.scale(pygame.image.load("car_obstacle2.png"), (visual_obstacle_width, obstacle_height)),
pygame.transform.scale(pygame.image.load("car_obstacle3.png"), (visual_obstacle_width, obstacle_height)),
pygame.transform.scale(pygame.image.load("car_obstacle4.png"), (visual_obstacle_width, obstacle_height)),
]
# Assign random skins to initial obstacles
for obstacle in obstacles:
obstacle["skin"] = random.choice(obstacle_skins)
clock = pygame.time.Clock()
font = pygame.font.Font(pygame.font.match_font('arial'), 36) # Stylish font
title_font = pygame.font.Font(pygame.font.match_font('arial'), 72)
# Load a monospace font for odometer style speed display
odometer_font = pygame.font.SysFont('consolas', 40, bold=True)
# Game variables
run = True
menu_active = True
score = 0
line_offset = 0 # Offset for moving dashed lines
# High score handling
high_score_file = "highscore.txt"
def load_high_score():
"""Load the high score from a file."""
if os.path.exists(high_score_file):
with open(high_score_file, "r") as file:
try:
return int(file.read().strip())
except ValueError:
return 0
return 0
def save_high_score(high_score):
"""Save the high score to a file."""
with open(high_score_file, "w") as file:
file.write(str(high_score))
# Initialize high score
high_score = load_high_score()
def draw_speedometer(speed):
# Format speed as 3-digit zero-padded string
speed_str = f"{speed:03d} km/h"
# Render the text
speed_text = odometer_font.render(speed_str, True, WHITE)
padding_x = 15
padding_y = 10
box_width = speed_text.get_width() + 2 * padding_x
box_height = speed_text.get_height() + 2 * padding_y
x = width - box_width - 20
y = height - box_height - 20
# Draw background rectangle (black) with rounded corners
pygame.draw.rect(win, BLACK, (x, y, box_width, box_height), border_radius=10)
# Draw white border rectangle
pygame.draw.rect(win, WHITE, (x, y, box_width, box_height), 3, border_radius=10)
# Blit speed text inside the box
win.blit(speed_text, (x + padding_x, y + padding_y))
def draw_highway():
# Draw the asphalt background
win.fill(ASPHALT)
# Draw road edges (shoulders)
pygame.draw.rect(win, ROAD_EDGE, (road_left - 20, 0, 20, height)) # Left shoulder
pygame.draw.rect(win, ROAD_EDGE, (road_right, 0, 20, height)) # Right shoulder
# Draw the road itself
pygame.draw.rect(win, ASPHALT, (road_left, 0, road_right - road_left, height)) # Road area
# Draw solid white lines for highway boundaries
pygame.draw.line(win, WHITE, (road_left, 0), (road_left, height), 4) # Left boundary
pygame.draw.line(win, WHITE, (road_right, 0), (road_right, height), 4) # Right boundary
# Draw moving dashed yellow lane dividers
global line_offset
line_offset = (line_offset + 5) % 40 # Speed of lane line movement
for i in range(1, lane_count):
lane_x = road_left + i * lane_width
for y in range(-line_offset, height, 40):
pygame.draw.rect(win, YELLOW, (lane_x - 2, y, 4, 20))
def draw_game():
draw_highway()
visual_car_x = car_x - (visual_car_width - car_width) // 2 # Adjust visual car to match hitbox
win.blit(player_car_img, (visual_car_x, car_y)) # Draw player's car
# Draw obstacles
for obstacle in obstacles:
obstacle_x = lanes[obstacle["lane"]] - visual_obstacle_width // 2
win.blit(obstacle["skin"], (obstacle_x, obstacle["y"]))
# Display the score
score_text = font.render(f"Score: {score}", True, WHITE)
win.blit(score_text, (10, 10))
# Draw odometer-style speedometer in bottom-right corner
draw_speedometer(obstacle_speed)
def end_game_screen():
global run, menu_active, score, high_score, obstacles, third_obstacle_added, fourth_obstacle_added
# Update high score if current score is higher
if score > high_score:
high_score = score
save_high_score(high_score) # Save the new high score
while True:
win.fill(ASPHALT)
end_text = title_font.render("Game Over", True, RED)
score_text = font.render(f"Your Score: {score}", True, WHITE)
high_score_text = font.render(f"High Score: {high_score}", True, WHITE)
play_again_text = font.render("Play Again", True, WHITE)
quit_text = font.render("Quit", True, WHITE)
play_again_button = pygame.Rect(width // 2 - 100, 300, 200, 50) # Play Again button
quit_button = pygame.Rect(width // 2 - 100, 400, 200, 50) # Quit button
# Draw Game Over screen
win.blit(end_text, (width // 2 - end_text.get_width() // 2, 100))
win.blit(score_text, (width // 2 - score_text.get_width() // 2, 200))
win.blit(high_score_text, (width // 2 - high_score_text.get_width() // 2, 250))
pygame.draw.rect(win, BLUE, play_again_button)
pygame.draw.rect(win, BLUE, quit_button)
win.blit(play_again_text, (play_again_button.x + play_again_button.width // 2 - play_again_text.get_width() // 2,
play_again_button.y + play_again_button.height // 2 - play_again_text.get_height() // 2))
win.blit(quit_text, (quit_button.x + quit_button.width // 2 - quit_text.get_width() // 2,
quit_button.y + quit_button.height // 2 - quit_text.get_height() // 2))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if play_again_button.collidepoint(event.pos): # Restart game
score = 0
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": random.choice(obstacle_skins)},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": random.choice(obstacle_skins)},
]
third_obstacle_added = False
fourth_obstacle_added = False
return # Exit the end game screen loop
elif quit_button.collidepoint(event.pos): # Quit game
pygame.quit()
exit()
def main_menu():
global menu_active, obstacles, score, high_score, third_obstacle_added, fourth_obstacle_added
while menu_active:
clock.tick(60)
# Update the background gameplay
for obstacle in obstacles:
obstacle["y"] += obstacle_speed
if obstacle["y"] > height:
obstacle["y"] = -obstacle_height
obstacle["lane"] = random.randint(0, lane_count - 1)
obstacle["skin"] = random.choice(obstacle_skins) # Assign a new random skin
# Draw the game in the background
draw_game()
# Draw menu overlay
title_text = title_font.render("Car Game", True, WHITE)
play_text = font.render("Play", True, WHITE)
high_score_text = font.render(f"High Score: {high_score}", True, WHITE)
play_button_rect = pygame.Rect(width // 2 - 100, 300, 200, 50) # Play button dimensions
# Draw title, high score, and button
win.blit(title_text, (width // 2 - title_text.get_width() // 2, 100))
win.blit(high_score_text, (width // 2 - high_score_text.get_width() // 2, 200))
pygame.draw.rect(win, BLUE, play_button_rect)
win.blit(play_text, (play_button_rect.x + play_button_rect.width // 2 - play_text.get_width() // 2,
play_button_rect.y + play_button_rect.height // 2 - play_text.get_height() // 2))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if play_button_rect.collidepoint(event.pos): # Start game
score = 0
obstacles = [
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": random.choice(obstacle_skins)},
{"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": random.choice(obstacle_skins)},
]
third_obstacle_added = False
fourth_obstacle_added = False
menu_active = False # Exit the menu
# Main loop
main_menu() # Display the main menu
while run:
clock.tick(60)
# Increase obstacle speed as score increases, starting at 60 km/h
obstacle_speed = 60 + (score // 10)
# Add a third obstacle when the score reaches 10
if score >= 10 and not third_obstacle_added:
obstacles.append({"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 400, "skin": random.choice(obstacle_skins)})
third_obstacle_added = True
# Add a fourth obstacle when the score reaches 20
if score >= 20 and not fourth_obstacle_added:
obstacles.append({"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 600, "skin": random.choice(obstacle_skins)})
fourth_obstacle_added = True
draw_game()
pygame.display.update()
# Update obstacles
for obstacle in obstacles:
obstacle["y"] += obstacle_speed
if obstacle["y"] > height:
obstacle["y"] = -obstacle_height
obstacle["lane"] = random.randint(0, lane_count - 1)
obstacle["skin"] = random.choice(obstacle_skins)
score += 1 # Increase score when an obstacle resets
# Smoothly move the car towards the target x position
if car_x < car_target_x:
car_x += min(car_speed, car_target_x - car_x)
elif car_x > car_target_x:
car_x -= min(car_speed, car_x - car_target_x)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN: # Detect key press
if event.key == pygame.K_LEFT and car_lane > 0:
car_lane -= 1
car_target_x = lanes[car_lane] - car_width // 2
elif event.key == pygame.K_RIGHT and car_lane < lane_count - 1:
car_lane += 1
car_target_x = lanes[car_lane] - car_width // 2
# Check for collisions
car_rect = pygame.Rect(car_x, car_y, car_width, car_height)
for obstacle in obstacles:
obstacle_x = lanes[obstacle["lane"]] - obstacle_width // 2
# Adjust obstacle hitbox to be smaller (10% of original size)
obstacle_hitbox_width = obstacle_width * 0.1
obstacle_hitbox_height = obstacle_height * 0.1
obstacle_hitbox_x = obstacle_x + (obstacle_width - obstacle_hitbox_width) // 2
obstacle_hitbox_y = obstacle["y"] + (obstacle_height - obstacle_hitbox_height) // 2
obstacle_rect = pygame.Rect(
obstacle_hitbox_x, obstacle_hitbox_y, obstacle_hitbox_width, obstacle_hitbox_height
)
if car_rect.colliderect(obstacle_rect):
end_game_screen() # Display end game screen
Summary of important updates:
obstacle_speed initialized to 60 km/h.
obstacle_speed updated in main loop as:
python
obstacle_speed = 60 + (score // 10)
Speedometer on screen shows this updated speed in the odometer style, bottom-right corner.
Let me know if you want me to assist with anything else!