Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Improve and rework this code: [code]

  1. User

    Improve and rework this code:

    import pygame
    import random
    
    # Constants
    WIDTH, HEIGHT = 600, 600
    GRID_SIZE = 20
    GRID_WIDTH = WIDTH // GRID_SIZE
    GRID_HEIGHT = HEIGHT // GRID_SIZE
    FPS = 10
    
    # Colors
    WHITE = (255, 255, 255)
    BLACK = (0, 0, 0)
    GREEN = (0, 255, 0)
    RED = (255, 0, 0)
    BLUE = (0, 0, 255)
    YELLOW = (255, 255, 0)  # New: Portal color
    
    # Directions
    UP = (0, -1)
    DOWN = (0, 1)
    LEFT = (-1, 0)
    RIGHT = (1, 0)
    
    # New Mechanics:
    PORTALS = True       # Enable/Disable portals
    OBSTACLES = True    # Enable/Disable obstacles
    SPEED_BOOST = True  # Enable/Disable speed boost
    SCORE_MULTIPLIER = True  # Enable/Disable score multipliers
    
    class Snake:
        def __init__(self):
            self.body = [(GRID_WIDTH // 2, GRID_HEIGHT // 2)]
            self.direction = RIGHT
            self.growing = 0
    
        def move(self):
            head = (self.body[0][0] + self.direction[0], self.body[0][1] + self.direction[1])
            self.body.insert(0, head)
            if self.growing > 0:
                self.growing -= 1
            else:
                self.body.pop()
    
        def grow(self):
            self.growing += 3  # Grow by 3 segments
    
        def collides(self, obstacles):
            head = self.body[0]
            return (
                head[0] < 0 or head[0] >= GRID_WIDTH or
                head[1] < 0 or head[1] >= GRID_HEIGHT or
                head in self.body[1:] or head in obstacles
            )
    
        def draw(self, screen):
            for segment in self.body:
                pygame.draw.rect(screen, GREEN, (segment[0] * GRID_SIZE, segment[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE))
    
    class Food:
        def __init__(self, snake, obstacles, portal1, portal2):
            self.position = self.generate_position(snake, obstacles, portal1, portal2)
    
        def generate_position(self, snake, obstacles, portal1, portal2):
            while True:
                position = (random.randrange(GRID_WIDTH), random.randrange(GRID_HEIGHT))
                if position not in snake.body and position not in obstacles and position != portal1.position and position != portal2.position:
                    return position
    
        def draw(self, screen):
            pygame.draw.rect(screen, RED, (self.position[0] * GRID_SIZE, self.position[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE))
    
    class Portal:
        def __init__(self, snake, obstacles):
            self.position = self.generate_position(snake, obstacles)
    
        def generate_position(self, snake, obstacles):
            while True:
                position = (random.randrange(GRID_WIDTH), random.randrange(GRID_HEIGHT))
                if position not in snake.body and position not in obstacles:
                    return position
    
        def draw(self, screen):
            pygame.draw.rect(screen, YELLOW, (self.position[0] * GRID_SIZE, self.position[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE))
    
    class SpeedBoost:
        def __init__(self, snake, obstacles, food, portal1, portal2):
            self.position = self.generate_position(snake, obstacles, food, portal1, portal2)
            self.duration = 10  # Duration in seconds
    
        def generate_position(self, snake, obstacles, food, portal1, portal2):
            while True:
                position = (random.randrange(GRID_WIDTH), random.randrange(GRID_HEIGHT))
                if position not in snake.body and position not in obstacles and position != food.position and position != portal1.position and position != portal2.position:
                    return position
    
        def draw(self, screen):
            pygame.draw.rect(screen, BLUE, (self.position[0] * GRID_SIZE, self.position[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE))
    
    # Initialize Pygame
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("Snake Game")
    clock = pygame.time.Clock()
    
    # Game variables
    snake = Snake()
    obstacles = []  # List to store obstacle positions
    
    # Initialize obstacles before defining food and portals
    if OBSTACLES:
        num_obstacles = 10  # Number of obstacles to generate
        for _ in range(num_obstacles):
            while True:
                obstacle = (random.randrange(GRID_WIDTH), random.randrange(GRID_HEIGHT))
                if obstacle not in snake.body:  # Ensure obstacles don't overlap
                    obstacles.append(obstacle)
                    break
    
    # Initialize portals
    if PORTALS:
        portal1 = Portal(snake, obstacles)
        portal2 = Portal(snake, obstacles)
    
    # Initialize food after defining obstacles and portals
    food = Food(snake, obstacles, portal1, portal2)
    
    speed_boost_active = False
    speed_boost_start_time = 0
    
    speed_boost = None  # Initialize speed boost object
    
    multiplier_active = False
    multiplier_start_time = 0
    multiplier_duration = 5
    
    score_multiplier = 1
    score = 0
    
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP and snake.direction != DOWN:
                    snake.direction = UP
                elif event.key == pygame.K_DOWN and snake.direction != UP:
                    snake.direction = DOWN
                elif event.key == pygame.K_LEFT and snake.direction != RIGHT:
                    snake.direction = LEFT
                elif event.key == pygame.K_RIGHT and snake.direction != LEFT:
                    snake.direction = RIGHT
    
        snake.move()
    
        if snake.body[0] == food.position:
            score += 1 * score_multiplier
            snake.grow()
            food.position = food.generate_position(snake, obstacles, portal1, portal2)
    
            # Generate a speed boost with a 10% chance
            if SPEED_BOOST and random.random() < 0.1 and speed_boost is None:
                speed_boost = SpeedBoost(snake, obstacles, food, portal1, portal2)
    
            # Activate a score multiplier for a short time (5 seconds) with a 10% chance
            if SCORE_MULTIPLIER and random.random() < 0.1 and not multiplier_active:
                multiplier_active = True
                multiplier_start_time = pygame.time.get_ticks()
                score_multiplier = 2  # Double the score
    
        # Check for score multiplier duration
        if multiplier_active and pygame.time.get_ticks() - multiplier_start_time > multiplier_duration * 1000:
            multiplier_active = False
            score_multiplier = 1
    
        # Check for speed boost
        if SPEED_BOOST and speed_boost is not None and snake.body[0] == speed_boost.position:
            speed_boost_active = True
            speed_boost_start_time = pygame.time.get_ticks()
            speed_boost = None  # Remove the speed boost
            FPS = 20
    
        # Deactivate speed boost after its duration
        if speed_boost_active and pygame.time.get_ticks() - speed_boost_start_time > speed_boost.duration * 1000:
            speed_boost_active = False
            FPS = 10
    
        if PORTALS and snake.body[0] == portal1.position:
            snake.body[0] = portal2.position
        elif PORTALS and snake.body[0] == portal2.position:
            snake.body[0] = portal1.position
    
        if snake.collides(obstacles):
            print("Game Over! Score:", score)
            running = False
    
        # Drawing
        screen.fill(BLACK)
    
        for obstacle in obstacles:
            pygame.draw.rect(screen, WHITE, (obstacle[0] * GRID_SIZE, obstacle[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE))
    
        snake.draw(screen)
        food.draw(screen)
    
        if PORTALS:
            portal1.draw(screen)
            portal2.draw(screen)
    
        if SPEED_BOOST and speed_boost is not None:
            speed_boost.draw(screen)
    
        pygame.display.flip()
    
        clock.tick(FPS)
    
    pygame.quit()
    
  2. Assistant

    Certainly! Here's an improved and reworked version of your Snake game code. The enhancements include better code organization, modular design, improved handling of feature flags, enhanced collision detection, dynamic score display, a game over screen, and overall optimization for readability and maintainability.

    import pygame
    import random
    import sys
    
    # Initialize Pygame
    pygame.init()
    
    # =========================
    # Configuration and Constants
    # =========================
    
    # Screen dimensions
    WIDTH, HEIGHT = 600, 600
    GRID_SIZE = 20
    GRID_WIDTH = WIDTH // GRID_SIZE
    GRID_HEIGHT = HEIGHT // GRID_SIZE
    
    # Frames per second settings
    BASE_FPS = 10
    SPEED_BOOST_FPS = 20
    
    # Colors
    WHITE = (255, 255, 255)
    BLACK = (0, 0, 0)
    GREEN = (0, 255, 0)
    RED = (220, 20, 60)
    BLUE = (0, 191, 255)
    YELLOW = (255, 215, 0)
    
    # Directions
    UP = (0, -1)
    DOWN = (0, 1)
    LEFT = (-1, 0)
    RIGHT = (1, 0)
    
    # Feature Flags
    PORTALS_ENABLED = True
    OBSTACLES_ENABLED = True
    SPEED_BOOST_ENABLED = True
    SCORE_MULTIPLIER_ENABLED = True
    
    # Game Settings
    NUM_OBSTACLES = 10
    MULTIPLIER_DURATION = 5000  # milliseconds
    SPEED_BOOST_DURATION = 10000  # milliseconds
    SPEED_BOOST_CHANCE = 0.1
    MULTIPLIER_CHANCE = 0.1
    
    # Fonts
    FONT_SIZE = 24
    FONT = pygame.font.SysFont('Arial', FONT_SIZE)
    
    # =========================
    # Helper Functions
    # =========================
    
    def draw_text(surface, text, color, position):
        """Render text on the given surface at the specified position."""
        text_surface = FONT.render(text, True, color)
        surface.blit(text_surface, position)
    
    def get_random_position(exclude):
        """Generate a random position on the grid not in the exclude list."""
        while True:
            position = (random.randint(0, GRID_WIDTH - 1), random.randint(0, GRID_HEIGHT - 1))
            if position not in exclude:
                return position
    
    # =========================
    # Game Entities
    # =========================
    
    class Snake:
        def __init__(self):
            self.body = [(GRID_WIDTH // 2, GRID_HEIGHT // 2)]
            self.direction = RIGHT
            self.grow_segments = 0
    
        def move(self):
            """Move the snake in the current direction."""
            head_x, head_y = self.body[0]
            delta_x, delta_y = self.direction
            new_head = (head_x + delta_x, head_y + delta_y)
            self.body.insert(0, new_head)
            if self.grow_segments > 0:
                self.grow_segments -= 1
            else:
                self.body.pop()
    
        def change_direction(self, new_direction):
            """Change the snake's direction if it's not directly opposite."""
            opposite = (-self.direction[0], -self.direction[1])
            if new_direction != opposite:
                self.direction = new_direction
    
        def grow(self, segments=3):
            """Increase the snake's length."""
            self.grow_segments += segments
    
        def collides_with_self(self):
            """Check if the snake collides with itself."""
            return self.body[0] in self.body[1:]
    
        def collides_with_walls(self):
            """Check if the snake collides with the walls."""
            head_x, head_y = self.body[0]
            return not (0 <= head_x < GRID_WIDTH and 0 <= head_y < GRID_HEIGHT)
    
        def collides_with_obstacles(self, obstacles):
            """Check if the snake collides with any obstacles."""
            return self.body[0] in obstacles
    
        def draw(self, surface):
            """Draw the snake on the given surface."""
            for segment in self.body:
                pygame.draw.rect(surface, GREEN, (*segment, GRID_SIZE, GRID_SIZE))
    
    class Food:
        def __init__(self, snake, obstacles, portals):
            self.position = self.generate_position(snake, obstacles, portals)
    
        def generate_position(self, snake, obstacles, portals):
            """Generate a position for the food not occupied by snake, obstacles, or portals."""
            exclude = set(snake.body) | set(obstacles)
            if PORTALS_ENABLED:
                exclude.update([portal.position for portal in portals])
            return get_random_position(exclude)
    
        def respawn(self, snake, obstacles, portals):
            """Respawn the food at a new random position."""
            self.position = self.generate_position(snake, obstacles, portals)
    
        def draw(self, surface):
            """Draw the food on the given surface."""
            pygame.draw.rect(surface, RED, (*self.position, GRID_SIZE, GRID_SIZE))
    
    class Portal:
        def __init__(self, snake, obstacles, portals):
            self.position = self.generate_position(snake, obstacles, portals)
    
        def generate_position(self, snake, obstacles, portals):
            """Generate a position for the portal not occupied by snake, obstacles, or other portals."""
            exclude = set(snake.body) | set(obstacles)
            exclude.update([portal.position for portal in portals])
            return get_random_position(exclude)
    
        def draw(self, surface):
            """Draw the portal on the given surface."""
            pygame.draw.rect(surface, YELLOW, (*self.position, GRID_SIZE, GRID_SIZE))
    
    class SpeedBoost:
        def __init__(self, snake, obstacles, food, portals):
            self.position = self.generate_position(snake, obstacles, food, portals)
    
        def generate_position(self, snake, obstacles, food, portals):
            """Generate a position for the speed boost not occupied by snake, obstacles, food, or portals."""
            exclude = set(snake.body) | set(obstacles) | {food.position}
            if PORTALS_ENABLED:
                exclude.update([portal.position for portal in portals])
            return get_random_position(exclude)
    
        def draw(self, surface):
            """Draw the speed boost on the given surface."""
            pygame.draw.rect(surface, BLUE, (*self.position, GRID_SIZE, GRID_SIZE))
    
    # =========================
    # Game Class
    # =========================
    
    class Game:
        def __init__(self):
            self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
            pygame.display.set_caption("Enhanced Snake Game")
            self.clock = pygame.time.Clock()
            self.reset()
    
        def reset(self):
            """Reset the game to the initial state."""
            self.snake = Snake()
            self.obstacles = self.generate_obstacles() if OBSTACLES_ENABLED else []
            self.portals = self.generate_portals() if PORTALS_ENABLED else []
            self.food = Food(self.snake, self.obstacles, self.portals)
            self.speed_boost = None
            self.speed_boost_active = False
            self.speed_boost_end_time = 0
            self.score_multiplier = 1
            self.multiplier_active = False
            self.multiplier_end_time = 0
            self.score = 0
            self.game_over = False
    
        def generate_obstacles(self):
            """Generate a list of obstacle positions."""
            obstacles = []
            while len(obstacles) < NUM_OBSTACLES:
                pos = get_random_position(set(obstacles) | set(self.snake.body))
                obstacles.append(pos)
            return obstacles
    
        def generate_portals(self):
            """Generate a pair of portals."""
            portals = []
            while len(portals) < 2:
                portal = Portal(self.snake, self.obstacles, portals)
                portals.append(portal)
            return portals
    
        def spawn_speed_boost(self):
            """Spawn a speed boost item with a certain probability."""
            if SPEED_BOOST_ENABLED and self.speed_boost is None and random.random() < SPEED_BOOST_CHANCE:
                self.speed_boost = SpeedBoost(self.snake, self.obstacles, self.food, self.portals)
    
        def spawn_score_multiplier(self):
            """Activate score multiplier with a certain probability."""
            if SCORE_MULTIPLIER_ENABLED and not self.multiplier_active and random.random() < MULTIPLIER_CHANCE:
                self.multiplier_active = True
                self.score_multiplier = 2
                self.multiplier_end_time = pygame.time.get_ticks() + MULTIPLIER_DURATION
    
        def handle_events(self):
            """Handle user input and other events."""
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
    
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_UP:
                        self.snake.change_direction(UP)
                    elif event.key == pygame.K_DOWN:
                        self.snake.change_direction(DOWN)
                    elif event.key == pygame.K_LEFT:
                        self.snake.change_direction(LEFT)
                    elif event.key == pygame.K_RIGHT:
                        self.snake.change_direction(RIGHT)
                    elif event.key == pygame.K_r and self.game_over:
                        self.reset()
    
        def update(self):
            """Update the game state."""
            if self.game_over:
                return
    
            self.snake.move()
    
            # Check collisions
            head = self.snake.body[0]
            if (
                self.snake.collides_with_walls() or
                self.snake.collides_with_self() or
                self.snake.collides_with_obstacles(self.obstacles)
            ):
                self.game_over = True
    
            # Check food collision
            if head == self.food.position:
                self.score += 1 * self.score_multiplier
                self.snake.grow()
                self.food.respawn(self.snake, self.obstacles, self.portals)
                self.spawn_speed_boost()
                self.spawn_score_multiplier()
    
            # Check speed boost collision
            if SPEED_BOOST_ENABLED and self.speed_boost and head == self.speed_boost.position:
                self.speed_boost_active = True
                self.speed_boost_end_time = pygame.time.get_ticks() + SPEED_BOOST_DURATION
                self.speed_boost = None  # Remove the speed boost
    
            # Check portal collision
            if PORTALS_ENABLED and self.portals:
                for portal in self.portals:
                    if head == portal.position:
                        # Teleport to the other portal
                        other_portal = self.portals[1] if portal == self.portals[0] else self.portals[0]
                        new_head = other_portal.position
                        # Prevent teleporting into the snake's body
                        if new_head in self.snake.body:
                            self.game_over = True
                        else:
                            self.snake.body[0] = new_head
                        break
    
            # Handle speed boost timing
            if self.speed_boost_active:
                if pygame.time.get_ticks() >= self.speed_boost_end_time:
                    self.speed_boost_active = False
    
            # Handle score multiplier timing
            if self.multiplier_active:
                if pygame.time.get_ticks() >= self.multiplier_end_time:
                    self.multiplier_active = False
                    self.score_multiplier = 1
    
        def draw_grid(self):
            """Draw the grid lines."""
            for x in range(0, WIDTH, GRID_SIZE):
                pygame.draw.line(self.screen, WHITE, (x, 0), (x, HEIGHT))
            for y in range(0, HEIGHT, GRID_SIZE):
                pygame.draw.line(self.screen, WHITE, (0, y), (WIDTH, y))
    
        def draw(self):
            """Render all game elements."""
            self.screen.fill(BLACK)
    
            # Optional: Draw grid
            # self.draw_grid()
    
            # Draw obstacles
            for obstacle in self.obstacles:
                pygame.draw.rect(self.screen, WHITE, (*obstacle, GRID_SIZE, GRID_SIZE))
    
            # Draw portals
            if PORTALS_ENABLED:
                for portal in self.portals:
                    portal.draw(self.screen)
    
            # Draw food
            self.food.draw(self.screen)
    
            # Draw speed boost
            if SPEED_BOOST_ENABLED and self.speed_boost:
                self.speed_boost.draw(self.screen)
    
            # Draw snake
            self.snake.draw(self.screen)
    
            # Draw score
            draw_text(self.screen, f"Score: {self.score}", YELLOW, (10, 10))
            if SCORE_MULTIPLIER_ENABLED and self.multiplier_active:
                draw_text(self.screen, f"Multiplier: x{self.score_multiplier}", YELLOW, (10, 40))
    
            # Draw game over screen
            if self.game_over:
                overlay = pygame.Surface((WIDTH, HEIGHT))
                overlay.set_alpha(180)
                overlay.fill(BLACK)
                self.screen.blit(overlay, (0, 0))
    
                game_over_text = FONT.render("GAME OVER", True, RED)
                score_text = FONT.render(f"Final Score: {self.score}", True, WHITE)
                restart_text = FONT.render("Press 'R' to Restart", True, WHITE)
    
                self.screen.blit(
                    game_over_text,
                    game_over_text.get_rect(center=(WIDTH // 2, HEIGHT // 2 - 40))
                )
                self.screen.blit(
                    score_text,
                    score_text.get_rect(center=(WIDTH // 2, HEIGHT // 2))
                )
                self.screen.blit(
                    restart_text,
                    restart_text.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 40))
                )
    
            pygame.display.flip()
    
        def run(self):
            """Main game loop."""
            while True:
                self.clock.tick(SPEED_BOOST_FPS if self.speed_boost_active else BASE_FPS)
                self.handle_events()
                self.update()
                self.draw()
    
    # =========================
    # Main Execution
    # =========================
    
    if __name__ == "__main__":
        game = Game()
        game.run()
    

    Enhanced Features and Improvements

    1. Modular Design with Classes:

      • The game is encapsulated within a Game class, enhancing organization and maintainability.
      • Separate classes for Snake, Food, Portal, and SpeedBoost improve readability and separation of concerns.
    2. Feature Flags Handling:

      • Feature flags (PORTALS_ENABLED, OBSTACLES_ENABLED, SPEED_BOOST_ENABLED, SCORE_MULTIPLIER_ENABLED) control the activation of game features.
      • The code dynamically adjusts based on these flags, ensuring that disabled features don't interfere with game logic.
    3. Improved Collision Detection:

      • Enhanced collision detection ensures that the snake doesn't teleport into its own body when using portals.
      • The Snake class methods (collides_with_self, collides_with_walls, collides_with_obstacles) provide clear and reusable collision checks.
    4. Dynamic Score Display:

      • The current score and active score multiplier are displayed on the screen using Pygame's font rendering.
      • A game over screen presents the final score and instructions to restart, enhancing user experience.
    5. Enhanced Item Management:

      • SpeedBoost and ScoreMultiplier are managed with timers to handle their durations.
      • Items spawn with defined probabilities and ensure they don't overlap with other game elements.
    6. Optimized Game Loop:

      • The main game loop in the Game class handles event processing, state updates, and rendering in a structured manner.
      • The clock adjusts the FPS based on whether a speed boost is active, maintaining consistent game speed.
    7. User-Friendly Controls:

      • The snake's direction changes smoothly, preventing immediate reversals that could cause instant collisions.
      • Pressing 'R' resets the game after a game over, allowing for quick retries without restarting the program.
    8. Visual Enhancements:

      • Optional grid lines can be toggled for better visual alignment.
      • Distinct colors differentiate between the snake, food, obstacles, portals, and speed boosts, improving visual clarity.
    9. Code Readability and Documentation:

      • Clear comments and docstrings explain the purpose of classes, methods, and functions.
      • Helper functions like draw_text and get_random_position reduce code duplication and enhance clarity.
    10. Robustness:

      • The game handles edge cases, such as teleporting into occupied spaces, ensuring that the game state remains consistent.
      • Proper initialization and reset mechanisms prevent potential bugs during restarts.

    How to Use the Improved Code

    1. Dependencies:

      • Ensure that Pygame is installed. You can install it using pip:
        pip install pygame
        
    2. Running the Game:

      • Save the provided code into a file, for example, enhanced_snake.py.
      • Run the game using Python:
        python enhanced_snake.py
        
    3. Gameplay Controls:

      • Arrow Keys: Control the direction of the snake (Up, Down, Left, Right).
      • 'R' Key: Restart the game after a game over.
    4. Game Features:

      • Portals: Teleport from one portal to another. Ensure the portals are not placed on the snake's body or obstacles.
      • Obstacles: Static blocks that the snake must avoid.
      • Speed Boost: Temporarily increases the snake's speed, making the game more challenging.
      • Score Multiplier: Temporarily doubles the points gained from eating food.
    5. Customizing Settings:

      • Adjust feature flags at the top of the script to enable or disable specific game mechanics.
      • Modify constants like NUM_OBSTACLES, MULTIPLIER_DURATION, and SPEED_BOOST_DURATION to tweak game difficulty and behavior.

    Conclusion

    This enhanced version of the Snake game is more organized, scalable, and user-friendly. By implementing modular classes, handling feature flags effectively, and improving user interactions, the game offers a richer and more maintainable codebase. Feel free to further customize and expand upon this foundation to add more features or refine existing ones!