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

Create a snake game using Python

  1. User

    Create a snake game using Python

  2. Assistant

    Creating a Snake game is a fun way to practice your Python programming skills. One of the most popular libraries for building simple games in Python is Pygame. Below, I'll guide you through the steps to create a basic Snake game using Pygame.

    Prerequisites

    1. Python Installed: Ensure you have Python installed on your computer. You can download it from python.org.

    2. Pygame Installed: Install Pygame using pip. Open your terminal or command prompt and run:

      pip install pygame
      

    Snake Game Code

    Here's a complete Python script for a simple Snake game:

    import pygame
    import time
    import random
    
    # Initialize Pygame
    pygame.init()
    
    # Define colors
    white = (255, 255, 255)
    yellow = (255, 255, 102)
    black = (0, 0, 0)
    red = (213, 50, 80)
    green = (0, 255, 0)
    blue = (50, 153, 213)
    
    # Display dimensions
    dis_width = 600
    dis_height = 400
    
    # Create display
    dis = pygame.display.set_mode((dis_width, dis_height))
    pygame.display.set_caption('Snake Game by ChatGPT')
    
    clock = pygame.time.Clock()
    
    # Snake properties
    snake_block = 10
    snake_speed = 15
    
    # Fonts
    font_style = pygame.font.SysFont(None, 50)
    score_font = pygame.font.SysFont(None, 35)
    
    def our_snake(snake_block, snake_list):
        """Draws the snake on the screen."""
        for x in snake_list:
            pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])
    
    def message(msg, color):
        """Displays a message on the screen."""
        mesg = font_style.render(msg, True, color)
        dis.blit(mesg, [dis_width / 6, dis_height / 3])
    
    def gameLoop():
        game_over = False
        game_close = False
    
        # Starting position
        x1 = dis_width / 2
        y1 = dis_height / 2
    
        # Change in position
        x1_change = 0
        y1_change = 0
    
        # Snake list and length
        snake_List = []
        Length_of_snake = 1
    
        # Food position
        foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
        foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
    
        while not game_over:
    
            while game_close:
                dis.fill(blue)
                message("You Lost! Press Q-Quit or C-Play Again", red)
                pygame.display.update()
    
                for event in pygame.event.get():
                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_q:
                            game_over = True
                            game_close = False
                        if event.key == pygame.K_c:
                            gameLoop()
    
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    game_over = True
                # Movement keys
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LEFT:
                        x1_change = -snake_block
                        y1_change = 0
                    elif event.key == pygame.K_RIGHT:
                        x1_change = snake_block
                        y1_change = 0
                    elif event.key == pygame.K_UP:
                        y1_change = -snake_block
                        x1_change = 0
                    elif event.key == pygame.K_DOWN:
                        y1_change = snake_block
                        x1_change = 0
    
            # Check boundaries
            if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
                game_close = True
    
            x1 += x1_change
            y1 += y1_change
            dis.fill(blue)
    
            # Draw food
            pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
    
            # Snake mechanics
            snake_Head = []
            snake_Head.append(x1)
            snake_Head.append(y1)
            snake_List.append(snake_Head)
            if len(snake_List) > Length_of_snake:
                del snake_List[0]
    
            # Check self-collision
            for x in snake_List[:-1]:
                if x == snake_Head:
                    game_close = True
    
            # Draw snake
            our_snake(snake_block, snake_List)
    
            # Display score
            score = Length_of_snake - 1
            value = score_font.render("Your Score: " + str(score), True, yellow)
            dis.blit(value, [0, 0])
    
            pygame.display.update()
    
            # Check if snake eats the food
            if x1 == foodx and y1 == foody:
                foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
                foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
                Length_of_snake += 1
    
            clock.tick(snake_speed)
    
        pygame.quit()
        quit()
    
    # Start the game
    gameLoop()
    

    Explanation of the Code

    1. Importing Libraries:

      • pygame: For game development.
      • time: For time-related functions.
      • random: To generate random positions for the food.
    2. Initializing Pygame and Colors: Sets up the game display and defines various colors using RGB tuples.

    3. Display Setup: Sets the width and height of the game window and initializes it.

    4. Game Clock: Controls the speed of the game.

    5. Snake Properties: Defines the size of each block of the snake and its speed.

    6. Fonts: Sets up the fonts for displaying messages and scores.

    7. our_snake Function: Draws the snake on the screen by iterating through its segments.

    8. message Function: Displays messages on the screen, such as game over prompts.

    9. gameLoop Function:

      • Game Initialization: Sets up initial positions, movement variables, and snake list.
      • Main Game Loop: Handles game states (running, game over), user inputs, snake movement, collision detection, and rendering.
      • Food Generation: Places the food at random positions on the screen.
      • Snake Growth: Increases the length of the snake when it eats food.
      • Collision Detection: Checks if the snake collides with the walls or itself.
      • Game Over Handling: Allows the player to quit or restart the game.
    10. Start the Game: Calls the gameLoop function to start the game.

    Running the Game

    1. Save the Script: Copy the above code into a file named snake_game.py.

    2. Run the Script: Open your terminal or command prompt, navigate to the directory containing snake_game.py, and run:

      python snake_game.py
      
    3. Gameplay Controls:

      • Arrow Keys: Control the direction of the snake.
      • Q Key: Quit the game when prompted.
      • C Key: Restart the game when prompted.

    Enhancements and Customizations

    Once you have the basic game up and running, you can enhance it in various ways:

    • Add Levels: Introduce different levels with increasing difficulty.
    • Sound Effects: Add sound effects for eating food or game over events.
    • High Score Tracking: Keep track of high scores using file handling.
    • Graphics: Replace the basic shapes with images or sprites for a more polished look.
    • Obstacles: Add obstacles that the snake must avoid.

    Troubleshooting

    • Pygame Installation Issues: If you encounter issues installing Pygame, ensure that pip is updated by running pip install --upgrade pip and try reinstalling Pygame.

    • Window Not Responding: Ensure that the game loop is running correctly and that events are being handled properly. If the window becomes unresponsive, you might need to check for infinite loops or unhandled events.

    Conclusion

    Building a Snake game with Python and Pygame is a rewarding project that helps you understand the basics of game development, event handling, and graphics rendering. Once comfortable with this, you can explore more complex game development concepts and create more intricate games.

    Happy coding!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.