Code a snake game in python
- User
Code a snake game in python
- Assistant
Certainly! You can create a simple Snake game in Python using the
pygamelibrary, which is perfect for creating 2D games and visualizations. Below is a complete example of how to build a Snake game.First, make sure you have
pygameinstalled. You can install it using:pip install pygameHere's the code for the Snake game:
import pygame import time import random # Initialize the 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) # Set display dimensions dis_width = 600 dis_height = 400 # Create the display surface object dis = pygame.display.set_mode((dis_width, dis_height)) pygame.display.set_caption('Snake Game by OpenAI') clock = pygame.time.Clock() # Set snake block size and speed snake_block = 10 snake_speed = 15 # Set fonts for displaying score and messages font_style = pygame.font.SysFont("bahnschrift", 25) score_font = pygame.font.SysFont("comicsansms", 35) # Function to display the player's score def Your_score(score): value = score_font.render("Your Score: " + str(score), True, yellow) dis.blit(value, [0, 0]) # Function to draw the snake def our_snake(snake_block, snake_list): for x in snake_list: pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block]) # Function to display messages on the screen def message(msg, color): mesg = font_style.render(msg, True, color) mesg_rect = mesg.get_rect(center=(dis_width/2, dis_height/3)) dis.blit(mesg, mesg_rect) # Main game loop function def gameLoop(): game_over = False game_close = False # Starting coordinates of the snake x1 = dis_width / 2 y1 = dis_height / 2 # Change in coordinates x1_change = 0 y1_change = 0 # List to keep track of the snake's body snake_List = [] Length_of_snake = 1 # Initial position of the food 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 # Game loop while not game_over: # Game over screen while game_close == True: dis.fill(blue) message("You Lost! Press C to Play Again or Q to Quit", red) Your_score(Length_of_snake - 1) pygame.display.update() # Event handling for game over screen 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 # Event handling during the game for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT and x1_change == 0: x1_change = -snake_block y1_change = 0 elif event.key == pygame.K_RIGHT and x1_change == 0: x1_change = snake_block y1_change = 0 elif event.key == pygame.K_UP and y1_change == 0: y1_change = -snake_block x1_change = 0 elif event.key == pygame.K_DOWN and y1_change == 0: y1_change = snake_block x1_change = 0 # Check for boundary collision if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0: game_close = True # Update snake position x1 += x1_change y1 += y1_change # Fill the background dis.fill(blue) # Draw food pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block]) # Update snake's body 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 if the snake has hit itself for x in snake_List[:-1]: if x == snake_Head: game_close = True # Draw the snake our_snake(snake_block, snake_List) Your_score(Length_of_snake - 1) # Update the display 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) / 10.0) * 10.0 foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0 Length_of_snake += 1 # Control the speed of the game clock.tick(snake_speed) # Quit the game pygame.quit() quit() # Start the game gameLoop()Explanation of the Code:
-
Initialization: The game initializes with
pygame.init(), sets up colors, the display window, and clock for controlling the game's frame rate. -
Game Loop (
gameLoopfunction): Contains the main logic of the game, including event handling, updating the snake's position, collision detection, and rendering. -
Event Handling:
- Movement: The snake moves in response to arrow keys. The condition checks prevent the snake from reversing directly onto itself.
- Game Over Conditions: If the snake hits the boundary or itself, the game enters a "game over" state.
-
Rendering Functions:
our_snake(): Draws the snake based on the list of positions stored insnake_List.message(): Displays messages on the screen, such as "You Lost!".Your_score(): Displays the current score, which is based on the length of the snake.
-
Food Mechanics: When the snake's head position coincides with the food's position, the length of the snake increases, and new food coordinates are generated.
-
Game Speed: Controlled by
clock.tick(snake_speed), which sets the frames per second (FPS) of the game.
Running the Game:
- Save the code in a file named, for example,
snake_game.py. - Run the script using
python snake_game.py.
Controls:
- Use the arrow keys to control the direction of the snake.
- During the game over screen:
- Press
Cto play again. - Press
Qor close the window to quit the game.
- Press
Notes:
- The snake cannot move in the opposite direction instantly to prevent self-collision due to immediate reversal.
- The game's difficulty can be adjusted by changing
snake_speed. Increasing it makes the snake move faster. - The
snake_blockdetermines the size of each segment of the snake and the food. Adjusting this will change the overall scale of the game.
Have fun playing your Snake game!
-