Untitled
unknown
plain_text
a year ago
2.8 kB
9
Indexable
import pygame
import random
# Initialize Pygame
pygame.init()
# Game window dimensions
WIDTH = 600
HEIGHT = 800
window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Car Avoidance Game")
# Define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# Car settings
car_width = 50
car_height = 100
car_x = WIDTH // 2 - car_width // 2
car_y = HEIGHT - car_height - 10
car_speed = 10
# Obstacle settings
obstacle_width = 50
obstacle_height = 50
obstacle_speed = 5
obstacle_frequency = 25
# Game clock
clock = pygame.time.Clock()
def draw_car(x, y):
pygame.draw.rect(window, BLUE, [x, y, car_width, car_height])
def draw_obstacle(x, y):
pygame.draw.rect(window, RED, [x, y, obstacle_width, obstacle_height])
def game_loop():
global car_x
global car_y
# Initialize game variables
x_change = 0
y_change = 0
obstacles = []
# Game loop
game_running = True
while game_running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -car_speed
if event.key == pygame.K_RIGHT:
x_change = car_speed
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
# Move car and keep it within screen boundaries
car_x += x_change
if car_x < 0:
car_x = 0
if car_x > WIDTH - car_width:
car_x = WIDTH - car_width
# Update obstacle positions and remove off-screen obstacles
for obstacle in obstacles:
obstacle[1] += obstacle_speed
obstacles = [obstacle for obstacle in obstacles if obstacle[1] < HEIGHT]
# Add new obstacles
if random.randint(1, obstacle_frequency) == 1:
obstacle_x = random.randint(0, WIDTH - obstacle_width)
obstacles.append([obstacle_x, -obstacle_height])
# Check for collisions
for obstacle in obstacles:
if car_x < obstacle[0] + obstacle_width and car_x + car_width > obstacle[0] and car_y < obstacle[1] + obstacle_height and car_y + car_height > obstacle[1]:
game_running = False
# Fill background
window.fill(WHITE)
# Draw car and obstacles
draw_car(car_x, car_y)
for obstacle in obstacles:
draw_obstacle(obstacle[0], obstacle[1])
# Update the screen
pygame.display.update()
# Set the game's frame rate
clock.tick(60)
pygame.quit()
# Start the game
game_loop()
Editor is loading...
Leave a Comment