import pygame import random import sys pygame.init() # Window setup WIDTH, HEIGHT = 600, 700 win = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption(“Car Racing Game”) # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (200, 0, 0) GREEN = (0, 200, 0) clock = pygame.time.Clock() # Car car_width = 50 car_height = 100 car_img = pygame.Surface((car_width, car_height)) car_img.fill(GREEN) car_x = WIDTH // 2 – car_width // 2 car_y = HEIGHT – car_height – 20 car_speed = 7 # Obstacles obs_width = 50 obs_height = 100 obs_speed = 7 def new_obstacle(): x = random.randint(50, WIDTH – 50 – obs_width) y = -obs_height rect = pygame.Rect(x, y, obs_width, obs_height) return rect obstacles = [new_obstacle()] score = 0 font = pygame.font.Font(None, 50) # —- MAIN LOOP —- running = True while running: clock.tick(60) win.fill(WHITE) # Events for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # Key Input keys = pygame.key.get_pressed() if keys[pygame.K_LEFT] and car_x > 0: car_x -= car_speed if keys[pygame.K_RIGHT] and car_x < WIDTH - car_width: car_x += car_speed # Draw car car_rect = pygame.Rect(car_x, car_y, car_width, car_height) pygame.draw.rect(win, GREEN, car_rect) # Obstacles for obs in obstacles: obs.y += obs_speed pygame.draw.rect(win, RED, obs) # Collision check if car_rect.colliderect(obs): game_over_text = font.render("GAME OVER!", True, RED) win.blit(game_over_text, (WIDTH//2 - 120, HEIGHT//2)) pygame.display.update() pygame.time.delay(2000) pygame.quit() sys.exit() # Respawn obstacle if obs.y > HEIGHT: obstacles.remove(obs) obstacles.append(new_obstacle()) score += 1 # Score Display score_text = font.render(f”Score: {score}”, True, BLACK) win.blit(score_text, (10, 10)) pygame.display.update()