Racing Game - Py
Racing Game - Py
import random
# Initialize
pygame.init()
# Screen setup
WIDTH, HEIGHT = 500, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Simple Racing Game")
# Colors
WHITE = (255, 255, 255)
GRAY = (100, 100, 100)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
# Clock
clock = pygame.time.Clock()
# Player car
player_car = pygame.Rect(WIDTH // 2 - 25, HEIGHT - 100, 50, 80)
# Enemy cars
enemy_car = pygame.Rect(random.randint(0, WIDTH - 50), -100, 50, 80)
enemy_speed = 5
# Game loop
running = True
while running:
screen.fill(GRAY)
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Move player
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player_car.left > 0:
player_car.move_ip(-5, 0)
if keys[pygame.K_RIGHT] and player_car.right < WIDTH:
player_car.move_ip(5, 0)
# Move enemy
enemy_car.move_ip(0, enemy_speed)
if enemy_car.top > HEIGHT:
enemy_car.top = -100
enemy_car.left = random.randint(0, WIDTH - 50)
# Check collision
if player_car.colliderect(enemy_car):
print("You Crashed!")
running = False
# Draw cars
pygame.draw.rect(screen, RED, player_car)
pygame.draw.rect(screen, YELLOW, enemy_car)
# Update display
pygame.display.flip()
clock.tick(60)
pygame.quit()