write me a python snake game code
- User
write me a python snake game code
- 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
-
Python Installed: Make sure you have Python installed on your machine. You can download it from python.org.
-
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
-
Save the Code: Copy the above code into a file named
snake_game.py. -
Run the Game: Open a terminal or command prompt, navigate to the directory containing
snake_game.py, and run:python snake_game.pyThis 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
Cto play again orQto 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_speedvariable to make the game faster or slower. -
Change Window Size: Modify
dis_widthanddis_heightto 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
pipis up to date. You can upgradepipusing:pip install --upgrade pipThen 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!
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.