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

Write code to create a snake game

  1. User

    Write code to create a snake game

  2. Assistant

    Certainly! Below is a simple implementation of the classic Snake game using Python's pygame library. This code creates a window where you can control a snake to collect food and grow in length. The game ends if the snake collides with the boundaries of the window or with itself.


    Prerequisites

    • Python 3 installed on your system.

    • Pygame library installed. If you haven't installed it yet, you can install it using pip:

      pip install pygame
      

    Snake Game Code

    import pygame
    import sys
    import random
    
    # Initialize pygame
    pygame.init()
    
    # Game window dimensions
    WINDOW_WIDTH = 600
    WINDOW_HEIGHT = 400
    CELL_SIZE = 20
    
    # Colors (R, G, B)
    WHITE = (255, 255, 255)
    GRAY = (40, 40, 40)
    BLACK = (0, 0, 0)
    RED = (200, 0, 0)
    GREEN = (0, 180, 0)
    
    # Set up the display
    window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
    pygame.display.set_caption('Snake Game')
    
    # Frames per second controller
    clock = pygame.time.Clock()
    
    # Font for displaying score
    font = pygame.font.SysFont('arial', 24)
    
    def draw_grid():
        for x in range(0, WINDOW_WIDTH, CELL_SIZE):
            pygame.draw.line(window, GRAY, (x, 0), (x, WINDOW_HEIGHT))
        for y in range(0, WINDOW_HEIGHT, CELL_SIZE):
            pygame.draw.line(window, GRAY, (0, y), (WINDOW_WIDTH, y))
    
    def random_food_position():
        x = random.randint(0, (WINDOW_WIDTH - CELL_SIZE) // CELL_SIZE) * CELL_SIZE
        y = random.randint(0, (WINDOW_HEIGHT - CELL_SIZE) // CELL_SIZE) * CELL_SIZE
        return (x, y)
    
    def game_over():
        game_over_font = pygame.font.SysFont('arial', 48)
        game_over_surface = game_over_font.render('Game Over', True, RED)
        game_over_rect = game_over_surface.get_rect()
        game_over_rect.midtop = (WINDOW_WIDTH / 2, WINDOW_HEIGHT / 4)
        window.blit(game_over_surface, game_over_rect)
        pygame.display.flip()
        pygame.time.wait(2000)
        pygame.quit()
        sys.exit()
    
    def main():
        # Initial snake position and direction
        snake_pos = [100, 50]
        snake_body = [[100, 50], [80, 50], [60, 50]]
        direction = 'RIGHT'
        change_to = direction
    
        # Initial food position
        food_pos = random_food_position()
        food_spawn = True
    
        score = 0
    
        # Main loop
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
    
                # Whenever a key is pressed
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                        change_to = 'RIGHT'
                    if event.key == pygame.K_LEFT or event.key == pygame.K_a:
                        change_to = 'LEFT'
                    if event.key == pygame.K_UP or event.key == pygame.K_w:
                        change_to = 'UP'
                    if event.key == pygame.K_DOWN or event.key == pygame.K_s:
                        change_to = 'DOWN'
                    if event.key == pygame.K_ESCAPE:
                        pygame.quit()
                        sys.exit()
    
            # Validate direction to prevent snake from moving in the opposite direction
            if change_to == 'RIGHT' and not direction == 'LEFT':
                direction = 'RIGHT'
            if change_to == 'LEFT' and not direction == 'RIGHT':
                direction = 'LEFT'
            if change_to == 'UP' and not direction == 'DOWN':
                direction = 'UP'
            if change_to == 'DOWN' and not direction == 'UP':
                direction = 'DOWN'
    
            # Update snake position
            if direction == 'RIGHT':
                snake_pos[0] += CELL_SIZE
            if direction == 'LEFT':
                snake_pos[0] -= CELL_SIZE
            if direction == 'UP':
                snake_pos[1] -= CELL_SIZE
            if direction == 'DOWN':
                snake_pos[1] += CELL_SIZE
    
            # Snake body growing mechanism
            snake_body.insert(0, list(snake_pos))
            if snake_pos == food_pos:
                score += 1
                food_spawn = False
            else:
                snake_body.pop()
            
            # Spawn new food
            if not food_spawn:
                food_pos = random_food_position()
            food_spawn = True
    
            # Clear screen
            window.fill(BLACK)
    
            # Draw grid
            draw_grid()
    
            # Draw snake
            for block in snake_body:
                pygame.draw.rect(window, GREEN, pygame.Rect(block[0], block[1], CELL_SIZE, CELL_SIZE))
    
            # Draw food
            pygame.draw.rect(window, RED, pygame.Rect(food_pos[0], food_pos[1], CELL_SIZE, CELL_SIZE))
    
            # Game Over conditions
            # Boundary collision
            if snake_pos[0] < 0 or snake_pos[0] >= WINDOW_WIDTH:
                game_over()
            if snake_pos[1] < 0 or snake_pos[1] >= WINDOW_HEIGHT:
                game_over()
            # Self collision
            for block in snake_body[1:]:
                if snake_pos == block:
                    game_over()
    
            # Display score
            score_surface = font.render(f'Score: {score}', True, WHITE)
            score_rect = score_surface.get_rect()
            window.blit(score_surface, (10, 10))
    
            # Refresh game screen
            pygame.display.update()
    
            # Frame Per Second /Refresh Rate
            clock.tick(10)
    
    if __name__ == '__main__':
        main()
    

    How to Run the Game

    1. Save the code in a file named snake_game.py.

    2. Install Pygame if you haven't already:

      pip install pygame
      
    3. Run the game using the command:

      python snake_game.py
      

    Instructions to Play

    • Use the arrow keys or WASD to control the direction of the snake:

      • Right / D: Move right
      • Left / A: Move left
      • Up / W: Move up
      • Down / S: Move down
    • Objective: Guide the snake to eat the red food squares. Each time the snake eats food, it grows longer, and your score increases by 1.

    • Game Over Conditions:

      • The game ends if the snake collides with the edges of the window.
      • The game ends if the snake runs into itself.
    • Exit the Game: Press the Escape key or close the game window.


    Customization Tips

    Feel free to modify the game to enhance your experience:

    • Adjust Speed: Change the value in clock.tick(10) to make the game faster or slower.

    • Change Grid Size: Modify CELL_SIZE for larger or smaller blocks.

    • Change Colors: Experiment with different RGB values in the color definitions.

    • Add Walls or Obstacles: Introduce new elements to increase the difficulty.


    Conclusion

    This basic implementation provides a foundation for the Snake game. You can build upon it by adding features like sound effects, a start menu, levels with increasing difficulty, or high score tracking.

    Enjoy your game development journey!