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

write me a python snake game code

  1. User

    write me a python snake game code

  2. Assistant

    Sure! Below is a simple implementation of the classic Snake game using Python and the Pygame library. This game allows you to control the snake using the arrow keys to collect food, grow longer, and avoid colliding with the walls or itself.

    Prerequisites

    1. Python Installed: Make sure you have Python installed on your machine. You can download it from python.org.

    2. Pygame Installed: Install the Pygame library, which is used for creating games in Python. You can install it using pip:

      pip install pygame
      

    Complete Snake Game Code

    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 Window Size
    dis_width = 800
    dis_height = 600
    
    # Create Display
    dis = pygame.display.set_mode((dis_width, dis_height))
    pygame.display.set_caption('Snake Game by ChatGPT')
    
    # Clock Object to Control Game Speed
    clock = pygame.time.Clock()
    
    # Snake Block Size and Speed
    snake_block = 20
    snake_speed = 15
    
    # Fonts for Text
    font_style = pygame.font.SysFont("bahnschrift", 25)
    score_font = pygame.font.SysFont("comicsansms", 35)
    
    
    def your_score(score):
        """Display the current score on the screen."""
        value = score_font.render("Your Score: " + str(score), True, yellow)
        dis.blit(value, [0, 0])
    
    
    def our_snake(snake_block, snake_list):
        """Draw 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):
        """Display a message in the center of the screen."""
        mesg = font_style.render(msg, True, color)
        dis.blit(mesg, [dis_width / 6, dis_height / 3])
    
    
    def gameLoop():
        """Main function to run the game loop."""
        game_over = False
        game_close = False
    
        # Starting position of the snake
        x1 = dis_width / 2
        y1 = dis_height / 2
    
        # Change in position
        x1_change = 0
        y1_change = 0
    
        # Initialize Snake List and Length
        snake_List = []
        Length_of_snake = 1
    
        # Spawn the first food
        foodx = round(random.randrange(0, dis_width - snake_block) / 20.0) * 20.0
        foody = round(random.randrange(0, dis_height - snake_block) / 20.0) * 20.0
    
        while not game_over:
    
            while game_close:
                dis.fill(blue)
                message("You Lost! Press C-Play Again or Q-Quit", red)
                your_score(Length_of_snake - 1)
                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()
                    if event.type == pygame.QUIT:
                        game_over = True
                        game_close = False
    
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    game_over = True
                # Control the snake with arrow 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 for 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])
    
            # Update snake's position
            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 for collision with itself
            for x in snake_List[:-1]:
                if x == snake_Head:
                    game_close = True
    
            our_snake(snake_block, snake_List)
            your_score(Length_of_snake - 1)
    
            pygame.display.update()
    
            # Check if snake has eaten the food
            if x1 == foodx and y1 == foody:
                foodx = round(random.randrange(0, dis_width - snake_block) / 20.0) * 20.0
                foody = round(random.randrange(0, dis_height - snake_block) / 20.0) * 20.0
                Length_of_snake += 1
    
            clock.tick(snake_speed)
    
        pygame.quit()
        quit()
    
    
    if __name__ == "__main__":
        gameLoop()
    

    How to Run the Game

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

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

      python snake_game.py
      

      This will launch the Snake game window.

    How to Play

    • Control the Snake: Use the arrow keys (Left, Right, Up, Down) to move the snake in the desired direction.

    • Objective: Navigate the snake to eat the green food blocks. Each time the snake eats food, it grows longer, and your score increases.

    • Game Over: The game ends if the snake collides with the walls of the window or runs into itself.

    • Restart or Quit: When the game is over, press C to play again or Q to quit.

    Customize the Game

    Feel free to modify various aspects of the game to enhance it or add new features:

    • Change Colors: Modify the color variables to change the appearance of the snake, food, and background.

    • Adjust Speed: Alter the snake_speed variable to make the game faster or slower.

    • Change Window Size: Modify dis_width and dis_height to change the size of the game window.

    • Add Sound Effects: Incorporate Pygame's mixer to add sounds for eating food or game over events.

    Troubleshooting

    • Pygame Installation Issues: If you encounter issues installing Pygame, ensure that you're using a compatible Python version and that your pip is up to date. You can upgrade pip using:

      pip install --upgrade pip
      

      Then try reinstalling Pygame.

    • Game Window Not Responding: If the game window becomes unresponsive, try clicking on it to ensure it's in focus, and use the close button or the designated keys to exit.

    Enjoy coding and playing your Snake game!

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