Untitled
unknown
plain_text
a month ago
2.4 kB
3
Indexable
# Python - Simple Car Racing Game import pygame import random # Initialize Pygame pygame.init() # Game Constants SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 CAR_WIDTH = 50 CAR_HEIGHT = 100 FPS = 60 # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (200, 0, 0) BLUE = (0, 0, 200) # Create game screen screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("Car Racing Game") # Load car image or use a rectangle as placeholder # For simplicity, we'll use rectangle # car_img = pygame.image.load("car.png") # Car starting position car_x = SCREEN_WIDTH // 2 - CAR_WIDTH // 2 car_y = SCREEN_HEIGHT - CAR_HEIGHT - 10 car_speed = 5 # Obstacle settings obstacle_width = 50 obstacle_height = 100 obstacle_speed = 5 obstacle_x = random.randint(0, SCREEN_WIDTH - obstacle_width) obstacle_y = -obstacle_height # Clock for controlling FPS clock = pygame.time.Clock() # Score score = 0 font = pygame.font.SysFont(None, 35) def display_score(score): text = font.render("Score: " + str(score), True, BLACK) screen.blit(text, (10, 10)) def game_loop(): global car_x, car_y, obstacle_x, obstacle_y, score running = True move_left = False move_right = False while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Key press if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: move_left = True if event.key == pygame.K_RIGHT: move_right = True if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: move_left = False if event.key == pygame.K_RIGHT: move_right = False # Move car if move_left and car_x > 0: car_x -= car_speed if move_right and car_x < SCREEN_WIDTH - CAR_WIDTH: car_x += car_speed # Move obstacle obstacle_y += obstacle_speed if obstacle_y > SCREEN_HEIGHT: obstacle_y = -obstacle_height obstacle_x = random.randint(0, SCREEN_WIDTH - obstacle_width) score += 1 # Collision detection if (car_y < obstacle_y + obstacle_height and car_y + CAR_HEIGHT > obstacle_y and car_x < obstacle_x + obstacle_width and car_x + CAR_WIDTH > obstacle_x): print("Game Over! Final Score:", score) running = False # Drawing everything screen.fill(WHITE) pygame.draw.rect(screen, BLUE, (car_x, car_y, CAR_WIDTH, CAR_HEIGHT)) pygame.draw.rect(screen, RED, (obstacle_x, obstacle_y, obstacle_width, obstacle_height)) display_score(score) pygame.display.update() clock.tick(FPS) pygame.quit() # Start the game if __name__ == "__main__": game_loop()Editor is loading...
Leave a Comment