Creating a complete Snake game with pygame requires quite a bit of code. I'll provide you with a simple, yet complete Snake game using pygame below.
import pygame
import sys
import random
# Initialize pygame
pygame.init()
# Set up game window
WINDOW_WIDTH = 640
WINDOW_HEIGHT = 480
GRID_SIZE = 20
GRID_WIDTH = WINDOW_WIDTH // GRID_SIZE
GRID_HEIGHT = WINDOW_HEIGHT // GRID_SIZE
FPS = 10
WINDOW = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("Snake Game")
CLOCK = pygame.time.Clock()
# Set up colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
def draw_grid():
for x in range(0, WINDOW_WIDTH, GRID_SIZE):
for y in range(0, WINDOW_HEIGHT, GRID_SIZE):
rect = pygame.Rect(x, y, GRID_SIZE, GRID_SIZE)
pygame.draw.rect(WINDOW, WHITE, rect, 1)
class Snake:
def __init__(self):
self.body = [(GRID_WIDTH // 2, GRID_HEIGHT // 2)]
self.direction = (1, 0)
def move(self):
head_x, head_y = self.body[0]
dir_x, dir_y = self.direction
new_head = (head_x + dir_x, head_y + dir_y)
if new_head in self.body:
return False
if new_head[0] < 0 or new_head[0] >= GRID_WIDTH or new_head[1] < 0 or new_head[1] >= GRID_HEIGHT:
return False
self.body.insert(0, new_head)
self.body.pop()
return True
def change_direction(self, new_direction):
if (new_direction[0] * -1, new_direction[1] * -1) == self.direction:
return
self.direction = new_direction
def grow(self):
tail = self.body[-1]
self.body.append(tail)
def draw(self):
for segment in self.body:
x, y = segment
pygame.draw.rect(WINDOW, GREEN, (x * GRID_SIZE, y * GRID_SIZE, GRID_SIZE, GRID_SIZE))
class Food:
def __init__(self):
self.position = (random.randint(0, GRID_WIDTH - 1), random.randint(0, GRID_HEIGHT - 1))
def respawn(self, snake):
while self.position in snake.body:
self.position = (random.randint(0, GRID_WIDTH - 1), random.randint(0, GRID_HEIGHT - 1))
def draw(self):
x, y = self.position
pygame.draw.rect(WINDOW, RED, (x * GRID_SIZE, y * GRID_SIZE, GRID_SIZE, GRID_SIZE))
def main():
snake = Snake()
food = Food()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
snake.change_direction((0, -1))
elif event.key == pygame.K_DOWN:
snake.change_direction((0, 1))
elif event.key == pygame.K_LEFT:
snake.change_direction((-1, 0))
elif event.key == pygame.K_RIGHT:
snake.change_direction((1, 0))
if not snake.move():
break
if snake.body[0] == food.position:
snake.grow()
food.respawn(snake)
WINDOW.fill(BLACK)
draw_grid()
snake.draw()
food.draw()
pygame.display.update()
CLOCK.tick(FPS)
if __name__ == "__main__":
main()
Simply copy and paste this code into a Python (.py) file, and run it (you'll need to have pygame installed - pip install pygame). This game features basic Snake functionality, player controls, and food mechanics. You can, of course, modify and expand the game as desired, e.g., by adding a scoring system, game over screen, or even difficulty levels.