Sure! Here's a simple implementation of the classic snake game in Python using the Pygame library:
python
import pygame
import sys
import random
# Define some constants
WIDTH = 800
HEIGHT = 600
SNAKE_SPEED = 20
GRID_SIZE = 20
SCORE_FONT = pygame.font.SysFont("arial", 25)
class Snake:
def __init__(self):
self.length = 1
self.positions = [((WIDTH / 2), (HEIGHT / 2))]
self.direction = random.choice([pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT])
self.color = (17, 24, 47)
def get_head_position(self):
return self.positions[0]
def turn(self, point):
if self.length > 1 and (point[0] * -1, point[1] * -1) == self.direction:
return
else:
self.direction = point
def move(self):
cur = self.get_head_position()
x, y = self.direction
new = (((cur[0] +(x*GRID_SIZE)) % WIDTH), (cur[1] +(y*GRID_SIZE)) % HEIGHT)
if len(self.positions) > 2 and new in self.positions[2:]:
return False
else:
self.positions.insert(0, new)
if len(self.positions) > self.length:
self.positions.pop()
return True
def grow(self):
self.length += 1
self.positions.append(self.positions[-1])
class Fruit:
def __init__(self):
self.position = (0, 0)
self.color = (111, 210, 46)
def reset(self):
self.position = (random.randint(0, 49) * GRID_SIZE, random.randint(0, 39) * GRID_SIZE)
def draw(self, surface):
r = pygame.Rect((self.position[0], self.position[1], GRID_SIZE, GRID_SIZE))
pygame.draw.rect(surface, self.color, r)
pygame.draw.rect(surface, (93, 216, 39), r, 1)
class Game:
def __init__(self):
pygame.init()
self.surface = pygame.display.set_mode((WIDTH, HEIGHT))
self.snake = Snake()
self.fruit = Fruit()
self.fruit.reset()
self.score = 0
self.clock = pygame.time.Clock()
def play_step(self):
self.snake.move()
self.draw_border()
self.draw_score()
self.fruit.draw(self.surface)
self.draw_snake()
self.handle_collision()
pygame.display.flip()
self.clock.tick(SNAKE_SPEED)
def draw_border(self):
for point in [((0, 0), (WIDTH, 0), (WIDTH, HEIGHT), (0, HEIGHT)):
pygame.draw.rect(self.surface, (80, 80, 80), pygame.Rect(point))
def draw_score(self):
score_text = SCORE_FONT.render("Score: %s" % (self.score), True, (255, 255, 255))
self.surface.blit(score_text, [0, 0])
def draw_snake(self):
for pos in self.snake.positions:
x = pos[0]
y = pos[1]
r = pygame.Rect((x, y, GRID_SIZE, GRID_SIZE))
pygame.draw.rect(self.surface, self.snake.color, r)
pygame.draw.rect(self.surface, (66,