import pygame import sys import random # Initialize Pygame pygame.init() # Constants WIDTH, HEIGHT = 800, 300 GROUND_HEIGHT = 20 FPS = 60 # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) # Player player_width, player_height = 40, 60 player_x, player_y = 50, HEIGHT - GROUND_HEIGHT - player_height player_velocity = 8 is_jumping = False # Obstacle obstacle_width, obstacle_height = 20, 50 obstacle_velocity = 5 obstacle_frequency = 25 obstacles = [] # Set up the display screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Dinosaur Game") clock = pygame.time.Clock() def draw_player(x, y): pygame.draw.rect(screen, BLACK, [x, y, player_width, player_height]) def draw_obstacles(obstacles): for obstacle in obstacles: pygame.draw.rect(screen, BLACK, obstacle) def game_over(): font = pygame.font.SysFont(None, 55) text = font.render("Game Over", True, BLACK) screen.blit(text, (WIDTH // 2 - 100, HEIGHT // 2 - 30)) pygame.display.update() pygame.time.wait(2000) pygame.quit() sys.exit() def main(): global player_x, player_y, is_jumping, obstacles 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_SPACE] and not is_jumping: is_jumping = True if is_jumping: player_y -= player_velocity * 2 if player_y < 0: is_jumping = False if player_y < HEIGHT - GROUND_HEIGHT - player_height and not is_jumping: player_y += player_velocity # Spawn obstacles if random.randrange(0, obstacle_frequency) == 1: obstacle_x = WIDTH obstacle_y = HEIGHT - GROUND_HEIGHT - obstacle_height obstacles.append([obstacle_x, obstacle_y, obstacle_width, obstacle_height]) # Move obstacles for obstacle in obstacles: obstacle[0] -= obstacle_velocity # Remove off-screen obstacles obstacles = [obstacle for obstacle in obstacles if obstacle[0] > 0] # Check for collisions player_rect = pygame.Rect(player_x, player_y, player_width, player_height) for obstacle in obstacles: obstacle_rect = pygame.Rect(obstacle[0], obstacle[1], obstacle[2], obstacle[3]) if player_rect.colliderect(obstacle_rect): game_over() # Draw everything screen.fill(WHITE) draw_player(player_x, player_y) draw_obstacles(obstacles) # Update the display pygame.display.update() # Control the frame rate clock.tick(FPS) if __name__ == "__main__": main()