import pygame import random def init_game(): pygame.init() screen = pygame.display.set_mode((800, 400)) clock = pygame.time.Clock() font = pygame.font.SysFont("Arial", 30) return screen, clock, font def reset_game(): return pygame.Rect(100, 200, 30, 30), [], [], 7, 6, 0, 1 def update_player(player, gravity, height): player.y += gravity if player.top < 0: player.top = 0 if player.bottom > height: player.bottom = height return player def update_obstacles(walls, coins, width, height, speed, count): # Spawning Logic safe_gap = 150 + (speed * 10) if len(walls) == 0 or walls[-1].right < width - safe_gap: count += 1 w = random.randint(100, 400) h = random.randint(50, 280) if count % 2 == 0: walls.append(pygame.Rect(width, 0, w, h)) coins.append(pygame.Rect(width + 50, height - 50, 20, 20)) else: walls.append(pygame.Rect(width, height - h, w, h)) coins.append(pygame.Rect(width + 50, 50, 20, 20)) # Movement & Cleanup for w in walls: w.x -= speed for c in coins: c.x -= speed if walls and walls[0].right < 0: walls.pop(0) if coins and coins[0].right < 0: coins.pop(0) return walls, coins, count def draw_game(screen, font, player, walls, coins, score, active): screen.fill((10, 10, 30)) pygame.draw.rect(screen, (57, 255, 20), player) for w in walls: pygame.draw.rect(screen, (255, 50, 50), w) for c in coins: pygame.draw.rect(screen, (255, 255, 0), c) score_surf = font.render(f"Score: {score}", True, (255, 255, 255)) screen.blit(score_surf, (20, 20)) if not active: over_surf = font.render("Press SPACE to Restart", True, (255, 255, 255)) screen.blit(over_surf, (250, 180)) pygame.display.flip() # --- MAIN EXECUTION --- screen, clock, font = init_game() player, walls, coins, gravity, speed, score, count = reset_game() game_active = True while True: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: if game_active: gravity *= -1 else: player, walls, coins, gravity, speed, score, count = reset_game() game_active = True if game_active: player = update_player(player, gravity, 400) walls, coins, count = update_obstacles(walls, coins, 800, 400, speed, count) # Collision Logic player_rect = player if player_rect.collidelist(walls) != -1: game_active = False coin_hit = player_rect.collidelist(coins) if coin_hit != -1: coins.pop(coin_hit) score += 5 speed += 0.2 if walls and walls[0].right < 0: score += 1 draw_game(screen, font, player, walls, coins, score, game_active) clock.tick(60)