import pygame
import random
# initialize pygame
pygame.init()
# set up the game window
window_width = 400
window_height = 400
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('Snake Game')
# set up the game clock
clock = pygame.time.Clock()
# set up the colors
white = (255, 255, 255)
black = (0, 0, 0)
green = (0, 255, 0)
red = (255, 0, 0)
# set up the snake and food
snake_block_size = 10
snake_speed = 15
snake_list = []
snake_length = 1
food_x = round(random.randrange(0, window_width - snake_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - snake_block_size) / 10.0) * 10.0
# set up the font
font_style = pygame.font.SysFont(None, 30)
# define a function to display the message
def message(msg, color):
message = font_style.render(msg, True, color)
window.blit(message, [window_width/6, window_height/3])
# main game loop
game_over = False
while not game_over:
# handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# get the keys pressed
keys = pygame.key.get_pressed()
# move the snake
if keys[pygame.K_LEFT]:
x_change = -snake_block_size
y_change = 0
elif keys[pygame.K_RIGHT]:
x_change = snake_block_size
y_change = 0
elif keys[pygame.K_UP]:
x_change = 0
y_change = -snake_block_size
elif keys[pygame.K_DOWN]:
x_change = 0
y_change = snake_block_size
else:
x_change = 0
y_change = 0
# update the snake's position
if snake_length == 1:
snake_head = [window_width/2, window_height/2]
else:
snake_head = [snake_list[-1][0] + x_change, snake_list[-1][1] + y_change]
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
# check for collision with the wall
if snake_head[0] < 0 or snake_head[0] >= window_width or snake_head[1] < 0 or snake_head[1] >= window_height:
game_over = True
# check for collision with the food
if snake_head[0] == food_x and snake_head[1] == food_y:
food_x = round(random.randrange(0, window_width - snake_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - snake_block_size) / 10.0) * 10.0
snake_length += 1
# clear the screen
window.fill(white)
# draw the snake
for block in snake_list:
pygame.draw.rect(window, black, [block[0], block[1], snake_block_size, snake_block_size])
# draw the food
pygame.draw.rect(window, red, [food_x, food_y, snake