Skip to content
The Chat Archive
o1-preview-2024-09-12· OpenAI WildChat-4.8M (AI2)

Help me code up a Snake game in Python

  1. User

    Help me code up a Snake game in Python

  2. Assistant

    Sure! I'd be happy to help you create a simple Snake game using Python and the Pygame library. Pygame is a popular library for making games in Python, and it's perfect for creating 2D games like Snake.

    Prerequisites:

    • Python installed on your system (Python 3.x recommended).

    • Pygame library installed. You can install it using pip:

      pip install pygame
      

    Step-by-Step Guide to Creating the Snake Game

    1. Import Required Modules

    We need to import pygame, sys, and random modules.

    import pygame
    import sys
    import random
    

    2. Initialize Pygame and Set Up the Game Window

    pygame.init()
    
    # Game window dimensions
    WINDOW_WIDTH = 600
    WINDOW_HEIGHT = 400
    
    # Create the game window
    game_window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
    pygame.display.set_caption('Snake Game')
    
    # Frames per second controller
    fps = pygame.time.Clock()
    

    3. Define Colors and Game Variables

    # Colors (R, G, B)
    BLACK = (0, 0, 0)      # Background color
    WHITE = (255, 255, 255)  # Snake color
    RED = (255, 0, 0)        # Food color
    
    # Snake starting position and body
    snake_pos = [100, 50]
    snake_body = [[100, 50], [90, 50], [80, 50]]
    
    # Food position
    food_pos = [random.randrange(1, (WINDOW_WIDTH // 10)) * 10,
                random.randrange(1, (WINDOW_HEIGHT // 10)) * 10]
    food_spawn = True
    
    # Initial direction
    direction = 'RIGHT'
    change_to = direction
    
    # Initial score
    score = 0
    

    4. Create Game Over Function

    def game_over():
        # Create font object
        font = pygame.font.SysFont('times new roman', 50)
        
        # Render the text
        game_over_surface = font.render('Your Score: ' + str(score), True, RED)
        
        # Get the rectangle for positioning
        game_over_rect = game_over_surface.get_rect()
        game_over_rect.midtop = (WINDOW_WIDTH / 2, WINDOW_HEIGHT / 4)
        
        # Blit text onto the screen
        game_window.fill(BLACK)
        game_window.blit(game_over_surface, game_over_rect)
        
        pygame.display.flip()
        
        # Wait and then exit
        pygame.time.sleep(2)
        pygame.quit()
        sys.exit()
    

    5. Main Game Loop

    def game_loop():
        global change_to, direction, score, food_spawn, snake_pos, snake_body, food_pos
        
        while True:
            # Handle key events
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                # When a key is pressed down
                elif event.type == pygame.KEYDOWN:
                    # Movement keys
                    if event.key == pygame.K_UP or event.key == ord('w'):
                        change_to = 'UP'
                    elif event.key == pygame.K_DOWN or event.key == ord('s'):
                        change_to = 'DOWN'
                    elif event.key == pygame.K_LEFT or event.key == ord('a'):
                        change_to = 'LEFT'
                    elif event.key == pygame.K_RIGHT or event.key == ord('d'):
                        change_to = 'RIGHT'
                    # Exit game
                    elif event.key == pygame.K_ESCAPE:
                        pygame.quit()
                        sys.exit()
            
            # Validate direction (no reverse gear)
            if change_to == 'UP' and direction != 'DOWN':
                direction = 'UP'
            elif change_to == 'DOWN' and direction != 'UP':
                direction = 'DOWN'
            elif change_to == 'LEFT' and direction != 'RIGHT':
                direction = 'LEFT'
            elif change_to == 'RIGHT' and direction != 'LEFT':
                direction = 'RIGHT'
            
            # Update snake position
            if direction == 'UP':
                snake_pos[1] -= 10
            elif direction == 'DOWN':
                snake_pos[1] += 10
            elif direction == 'LEFT':
                snake_pos[0] -= 10
            elif direction == 'RIGHT':
                snake_pos[0] += 10
            
            # Snake body growing mechanism
            snake_body.insert(0, list(snake_pos))
            if snake_pos == food_pos:
                score += 10
                food_spawn = False
            else:
                snake_body.pop()
            
            # Spawn new food
            if not food_spawn:
                food_pos = [random.randrange(1, (WINDOW_WIDTH // 10)) * 10,
                            random.randrange(1, (WINDOW_HEIGHT // 10)) * 10]
            food_spawn = True
            
            # Draw background
            game_window.fill(BLACK)
            
            # Draw snake
            for pos in snake_body:
                pygame.draw.rect(game_window, WHITE, pygame.Rect(pos[0], pos[1], 10, 10))
            
            # Draw food
            pygame.draw.rect(game_window, RED, pygame.Rect(food_pos[0], food_pos[1], 10, 10))
            
            # Check for collisions
            # Boundary collisions
            if snake_pos[0] < 0 or snake_pos[0] > WINDOW_WIDTH - 10:
                game_over()
            if snake_pos[1] < 0 or snake_pos[1] > WINDOW_HEIGHT - 10:
                game_over()
            
            # Self collisions
            for block in snake_body[1:]:
                if snake_pos == block:
                    game_over()
            
            # Display score
            show_score()
            
            # Update display
            pygame.display.update()
            
            # Control game speed
            fps.tick(15)
    

    6. Function to Display Score

    def show_score():
        font = pygame.font.SysFont('times new roman', 20)
        score_surface = font.render('Score: ' + str(score), True, WHITE)
        score_rect = score_surface.get_rect()
        score_rect.midtop = (WINDOW_WIDTH / 10, 15)
        game_window.blit(score_surface, score_rect)
    

    7. Run the Game

    if __name__ == '__main__':
        game_loop()
    

    Complete Code

    Here's the full code consolidated:

    import pygame
    import sys
    import random
    
    pygame.init()
    
    WINDOW_WIDTH = 600
    WINDOW_HEIGHT = 400
    game_window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
    pygame.display.set_caption('Snake Game')
    fps = pygame.time.Clock()
    
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)
    RED = (255, 0, 0)
    
    snake_pos = [100, 50]
    snake_body = [[100, 50], [90, 50], [80, 50]]
    
    food_pos = [random.randrange(1, (WINDOW_WIDTH // 10)) * 10,
                random.randrange(1, (WINDOW_HEIGHT // 10)) * 10]
    food_spawn = True
    
    direction = 'RIGHT'
    change_to = direction
    
    score = 0
    
    def game_over():
        font = pygame.font.SysFont('times new roman', 50)
        game_over_surface = font.render('Your Score: ' + str(score), True, RED)
        game_over_rect = game_over_surface.get_rect()
        game_over_rect.midtop = (WINDOW_WIDTH / 2, WINDOW_HEIGHT / 4)
        game_window.fill(BLACK)
        game_window.blit(game_over_surface, game_over_rect)
        pygame.display.flip()
        pygame.time.sleep(2)
        pygame.quit()
        sys.exit()
    
    def show_score():
        font = pygame.font.SysFont('times new roman', 20)
        score_surface = font.render('Score: ' + str(score), True, WHITE)
        score_rect = score_surface.get_rect()
        score_rect.midtop = (WINDOW_WIDTH / 10, 15)
        game_window.blit(score_surface, score_rect)
    
    def game_loop():
        global change_to, direction, score, food_spawn, snake_pos, snake_body, food_pos
        
        while True:
            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 or event.key == ord('w'):
                        change_to = 'UP'
                    elif event.key == pygame.K_DOWN or event.key == ord('s'):
                        change_to = 'DOWN'
                    elif event.key == pygame.K_LEFT or event.key == ord('a'):
                        change_to = 'LEFT'
                    elif event.key == pygame.K_RIGHT or event.key == ord('d'):
                        change_to = 'RIGHT'
                    elif event.key == pygame.K_ESCAPE:
                        pygame.quit()
                        sys.exit()
            
            if change_to == 'UP' and direction != 'DOWN':
                direction = 'UP'
            elif change_to == 'DOWN' and direction != 'UP':
                direction = 'DOWN'
            elif change_to == 'LEFT' and direction != 'RIGHT':
                direction = 'LEFT'
            elif change_to == 'RIGHT' and direction != 'LEFT':
                direction = 'RIGHT'
            
            if direction == 'UP':
                snake_pos[1] -= 10
            elif direction == 'DOWN':
                snake_pos[1] += 10
            elif direction == 'LEFT':
                snake_pos[0] -= 10
            elif direction == 'RIGHT':
                snake_pos[0] += 10
            
            snake_body.insert(0, list(snake_pos))
            if snake_pos == food_pos:
                score += 10
                food_spawn = False
            else:
                snake_body.pop()
            
            if not food_spawn:
                food_pos = [random.randrange(1, (WINDOW_WIDTH // 10)) * 10,
                            random.randrange(1, (WINDOW_HEIGHT // 10)) * 10]
            food_spawn = True
            
            game_window.fill(BLACK)
            
            for pos in snake_body:
                pygame.draw.rect(game_window, WHITE, pygame.Rect(pos[0], pos[1], 10, 10))
            
            pygame.draw.rect(game_window, RED, pygame.Rect(food_pos[0], food_pos[1], 10, 10))
            
            if snake_pos[0] < 0 or snake_pos[0] > WINDOW_WIDTH - 10:
                game_over()
            if snake_pos[1] < 0 or snake_pos[1] > WINDOW_HEIGHT - 10:
                game_over()
            
            for block in snake_body[1:]:
                if snake_pos == block:
                    game_over()
            
            show_score()
            pygame.display.update()
            fps.tick(15)
    
    if __name__ == '__main__':
        game_loop()
    

    Explanation

    • Imports and Initialization:

      • Imported necessary modules and initialized Pygame.
      • Set up the game window dimensions and created the display surface.
      • Defined colors using RGB tuples.
    • Game Variables:

      • snake_pos: The x and y coordinates of the snake's head.
      • snake_body: A list containing positions of each segment of the snake's body.
      • food_pos: Randomly generated position for the food using random.randrange().
      • direction and change_to: Strings representing the current and next direction of the snake.
      • score: An integer to keep track of the player's score.
    • Game Over Function:

      • Displays the player's score when the game ends.
      • Waits for 2 seconds before quitting the game.
    • Main Game Loop (game_loop function):

      • Event Handling:
        • Listens for key presses to change the snake's direction.
        • Exits the game if the player closes the window or presses ESC.
      • Direction Validation:
        • Ensures the snake cannot move in the opposite direction instantly.
      • Snake Movement:
        • Updates the snake's position based on the direction.
        • The snake moves by adding a new head and removing the tail if it hasn't eaten food.
      • Food Mechanics:
        • Checks if the snake has eaten the food.
        • Spawns new food at a random position if the snake eats the current one.
      • Rendering:
        • Fills the background.
        • Draws the snake and the food on the game window.
      • Collision Detection:
        • Ends the game if the snake collides with the boundaries or itself.
      • Score Display:
        • Calls show_score() to render the current score on the screen.
      • Updating the Screen:
        • Updates the entire display surface to the screen.
      • Control Game Speed:
        • Uses fps.tick(15) to control the frame rate at 15 FPS.
    • Score Display Function (show_score):

      • Renders and displays the current score at the top-left corner of the screen.

    Running the Game

    To run the game:

    1. Save the code in a file named snake_game.py (or any name you prefer).

    2. Open a terminal in the directory where the file is saved.

    3. Run the script:

      python snake_game.py
      

    Controls:

    • Use the arrow keys or W (up), A (left), S (down), D (right) to control the snake.
    • Press ESC to exit the game.

    Possible Enhancements

    Feel free to expand on this basic Snake game by adding features such as:

    • Increasing the game speed as the player's score increases.
    • Adding sound effects when the snake eats food or the game ends.
    • Implementing a high score system.
    • Adding a start menu or pause functionality.

    I hope this helps you create your Snake game! If you have any questions or need further assistance, feel free to ask. Happy coding!