Generate a Python3 snake game
- User
Generate a Python3 snake game
- Assistant
Generate a Python3 snake game
Sure! Below is a complete implementation of the classic Snake game using Python 3 and the pygame library. Follow the instructions to set it up and play.
Python 3.x Installed: Ensure you have Python 3 installed on your system. You can download it from python.org.
Pygame Library: This game uses the pygame library for handling graphics and user input. You can install it using pip:
pip install pygame
If you’re using pip3, you might need to use:
pip3 install pygame
Objective: Control the snake to eat the food that appears randomly on the screen. Each time the snake eats food, it grows longer. The game ends if the snake collides with the walls or itself.
Controls:
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)
# Set display dimensions
dis_width = 800
dis_height = 600
# Create the display
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Game by ChatGPT')
# Set clock
clock = pygame.time.Clock()
# Set snake parameters
snake_block = 20
snake_speed = 15
# Set fonts
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)
def your_score(score):
"""Function to display the current score."""
value = score_font.render("Your Score: " + str(score), True, yellow)
dis.blit(value, [0, 0])
def our_snake(snake_block, snake_list):
"""Function to 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):
"""Function to display messages on 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
x1 = dis_width / 2
y1 = dis_height / 2
x1_change = 0
y1_change = 0
snake_List = []
Length_of_snake = 1
# Generate food coordinates
foodx = round(random.randrange(0, dis_width - snake_block) / snake_block) * snake_block
foody = round(random.randrange(0, dis_height - snake_block) / snake_block) * snake_block
while not game_over:
while game_close == True:
dis.fill(blue)
message("You Lost! Press Q-Quit or C-Play Again", 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()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
if x1_change == snake_block:
pass # Prevent the snake from reversing
else:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
if x1_change == -snake_block:
pass
else:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
if y1_change == snake_block:
pass
else:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
if y1_change == -snake_block:
pass
else:
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)
pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
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) / snake_block) * snake_block
foody = round(random.randrange(0, dis_height - snake_block) / snake_block) * snake_block
Length_of_snake += 1
clock.tick(snake_speed)
pygame.quit()
quit()
if __name__ == "__main__":
gameLoop()
Save the Code:
snake_game.py (or any name you prefer) and paste the entire code above into it.Run the Game:
Open your terminal or command prompt.
Navigate to the directory where you saved snake_game.py.
Run the game using the following command:
python snake_game.py
Or if you're using python3:
python3 snake_game.py
Play:
Here's a brief overview of how the code works:
Initialization:
Main Game Loop (gameLoop function):
Helper Functions:
your_score: Displays the current score on the screen.our_snake: Draws the snake on the screen.message: Displays messages (like game over) on the screen.Feel free to customize the game further:
snake_speed variable to make the game faster or slower.dis_width and dis_height to adjust the game window size.Pygame Installation Issues:
Ensure you're using the correct pip associated with your Python 3 installation.
If you encounter issues, try upgrading pip:
pip install --upgrade pip
Game Not Starting:
Enjoy building and playing your Snake game! If you have any questions or need further assistance, feel free to ask.