Untitled
unknown
plain_text
a month ago
8.2 kB
2
Indexable
import pygame import random import sys # Initialize Pygame pygame.init() # Game Window WIDTH = 500 HEIGHT = 600 win = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Car Racing Game") # Colors WHITE = (255, 255, 255) GRAY = (100, 100, 100) RED = (200, 0, 0) BLUE = (0, 0, 255) # Clock clock = pygame.time.Clock() FPS = 60 # Player Car player_car = pygame.Rect(200, 500, 50, 100) # Enemy Cars enemy_cars = [pygame.Rect(random.randint(50, 450), -150 * i, 50, 100) for i in range(3)] # Speed player_speed = 5 enemy_speed = 5 # Game loop def game_loop(): run = True while run: clock.tick(FPS) win.fill(GRAY) # Events for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.quit() sys.exit() # Key Presses keys = pygame.key.get_pressed() if keys[pygame.K_LEFT] and player_car.left > 50: player_car.x -= player_speed if keys[pygame.K_RIGHT] and player_car.right < WIDTH - 50: player_car.x += player_speed # Move enemy cars for enemy in enemy_cars: enemy.y += enemy_speed if enemy.y > HEIGHT: enemy.y = -150 enemy.x = random.randint(50, 450) # Collision if player_car.colliderect(enemy): print("Game Over!") run = False # Draw Road Borders pygame.draw.rect(win, WHITE, (40, 0, 10, HEIGHT)) pygame.draw.rect(win, WHITE, (WIDTH - 50, 0, 10, HEIGHT)) # Draw Cars pygame.draw.rect(win, BLUE, player_car) for enemy in enemy_cars: pygame.draw.rect(win, RED, enemy) # Update Display pygame.display.update() game_loop()
Editor is loading...
Leave a Comment