build snake game in python
- User
build snake game in python
- Assistant
build snake game in python
Creating a Snake game is a great way to practice your Python programming skills, especially using the pygame library, which is popular for building simple games. Below, I'll guide you through building a basic Snake game step-by-step.
pygame library, which is used for game development in Python.You can install pygame using pip:
pip install pygame
Start by importing the necessary libraries and initializing pygame.
import pygame
import time
import random
# Initialize pygame
pygame.init()
Define some basic colors and set up the dimensions for the game window.
# 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 settings
dis_width = 800
dis_height = 600
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Game by ChatGPT')
Define the clock for controlling the frame rate and set the size of each block of the snake.
clock = pygame.time.Clock()
snake_block = 10
snake_speed = 15
# Set up fonts
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)
Create functions to display the current score and to draw the snake.
def Your_score(score):
value = score_font.render("Your Score: " + str(score), True, white)
dis.blit(value, [0, 0])
def our_snake(snake_block, snake_List):
for x in snake_List:
pygame.draw.rect(dis, green, [x[0], x[1], snake_block, snake_block])
def message(msg, color):
mesg = font_style.render(msg, True, color)
dis.blit(mesg, [dis_width / 6, dis_height / 3])
Implement the core game logic within the main game loop.
def gameLoop():
game_over = False
game_close = False
# Starting position of the snake
x1 = dis_width / 2
y1 = dis_height / 2
# Movement increments
x1_change = 0
y1_change = 0
# Snake body 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 == True:
dis.fill(black)
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()
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# Handle key presses
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
# Update the position
x1 += x1_change
y1 += y1_change
dis.fill(blue)
# Draw food
pygame.draw.rect(dis, red, [foodx, foody, snake_block, snake_block])
# Update the snake's body
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_List.append(snake_Head)
# Maintain the snake's length
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
# Draw the snake and score
our_snake(snake_block, snake_List)
Your_score(Length_of_snake - 1)
pygame.display.update()
# Check if the 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
clock.tick(snake_speed)
pygame.quit()
quit()
# Start the game
gameLoop()
Save the entire code in a Python file, for example, snake_game.py. Open your terminal or command prompt, navigate to the directory containing snake_game.py, and run:
python snake_game.py
Initialization: The game initializes pygame and sets up the display window with specified width and height.
Colors: Common colors are defined using RGB tuples for easy reference.
Fonts: Different fonts are set up for displaying the score and messages.
Helper Functions:
Your_score(score): Displays the current score at the top-left corner.our_snake(snake_block, snake_List): Draws the snake by iterating through the snake_List.message(msg, color): Displays messages in the middle of the screen.Main Game Loop (gameLoop):
Game Over Screen: When the snake loses, a message is displayed with options to quit or play again.
To make the game more interesting, you can add the following features:
Here's how you might implement increasing difficulty by adjusting the snake's speed based on the length:
# Adjust speed based on score
clock.tick(snake_speed + Length_of_snake // 5)
Add the above line right before clock.tick(snake_speed) to make the game progressively faster as the snake grows.
You've now created a basic Snake game using Python and pygame. This serves as a solid foundation, and you can build upon it by adding more features and improving the graphics and gameplay mechanics. Happy coding!
Not yet included in a published release.