import pygame import random import sys # Initialize Pygame pygame.init() # Constants SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) FONT = pygame.font.Font(None, 36) # Player properties player_size = 50 player_pos = [SCREEN_WIDTH // 2, SCREEN_HEIGHT - 2 * player_size] player_speed = 10 # Obstacle properties obstacle_size = 50 obstacle_pos = [random.randint(0, SCREEN_WIDTH - obstacle_size), 0] obstacle_list = [obstacle_pos] obstacle_speed = 5 # Score score = 0 # Initialize the screen screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("Dodger Game") # Clock to control the frame rate clock = pygame.time.Clock() # Function to create obstacles def create_obstacles(): delay = random.random() if delay < 0.1: x_pos = random.randint(0, SCREEN_WIDTH - obstacle_size) y_pos = 0 obstacle_list.append([x_pos, y_pos]) # Function to move obstacles def move_obstacles(): global score for idx, obstacle in enumerate(obstacle_list): if obstacle[1] >= 0 and obstacle[1] < SCREEN_HEIGHT: obstacle[1] += obstacle_speed score += 1 else: obstacle_list.pop(idx) # Function to draw obstacles def draw_obstacles(): for obstacle in obstacle_list: pygame.draw.rect(screen, BLACK, (obstacle[0], obstacle[1], obstacle_size, obstacle_size)) # Function to update the screen def update_screen(): screen.fill(WHITE) draw_obstacles() pygame.draw.rect(screen, RED, (player_pos[0], player_pos[1], player_size, player_size)) draw_text("Score: " + str(score), FONT, BLACK, 10, 10) pygame.display.update() # Function to draw text def draw_text(text, font, color, x, y): text_surface = font.render(text, True, color) screen.blit(text_surface, (x, y)) # Main game loop while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: player_pos[0] -= player_speed if keys[pygame.K_RIGHT]: player_pos[0] += player_speed create_obstacles() move_obstacles() update_screen() # Collision detection for obstacle in obstacle_list: if (obstacle[1] >= player_pos[1] and obstacle[1] <= player_pos[1] + player_size) or \ (obstacle[1] + obstacle_size >= player_pos[1] and obstacle[1] + obstacle_size <= player_pos[1] + player_size): if (obstacle[0] >= player_pos[0] and obstacle[0] <= player_pos[0] + player_size) or \ (obstacle[0] + obstacle_size >= player_pos[0] and obstacle[0] + obstacle_size <= player_pos[0] + player_size): pygame.quit() sys.exit() # Set frame rate clock.tick(30)