import pygame
import random
pygame.init()
WIDTH, HEIGHT = 600, 400
GRID_SIZE = 20
GRID_WIDTH, GRID_HEIGHT = WIDTH // GRID_SIZE, HEIGHT // GRID_SIZE
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLACK = (0, 0, 0)
class Snake:
def __init__(self):
self.body = [(GRID_WIDTH // 2, GRID_HEIGHT // 2)]
self.direction = (1, 0)
def move(self):
head = self.body[0]
new_head = (head[0] + self.direction[0], head[1] + self.direction[1])
self.body = [new_head] + self.body[:-1]
def grow(self):
tail = self.body[-1]
new_tail = (tail[0] - self.direction[0], tail[1] - self.direction[1])
self.body.append(new_tail)
def draw(self, screen):
for segment in self.body:
pygame.draw.rect(screen, GREEN, (segment[0] * GRID_SIZE, segment[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE))
def check_collision(self):
head = self.body[0]
return head in self.body[1:]
class Food:
def __init__(self):
self.position = (random.randint(0, GRID_WIDTH - 1), random.randint(0, GRID_HEIGHT - 1))
def draw(self, screen):
pygame.draw.rect(screen, RED, (self.position[0] * GRID_SIZE, self.position[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE))
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇")
snake = Snake()
food = Food()
clock = pygame.time.Clock()
running = True
while running:
screen.fill(BLACK)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and snake.direction != (0, 1):
snake.direction = (0, -1)
elif event.key == pygame.K_DOWN and snake.direction != (0, -1):
snake.direction = (0, 1)
elif event.key == pygame.K_LEFT and snake.direction != (1, 0):
snake.direction = (-1, 0)
elif event.key == pygame.K_RIGHT and snake.direction != (-1, 0):
snake.direction = (1, 0)
snake.move()
if snake.body[0] == food.position:
snake.grow()
food = Food()
if snake.check_collision() or snake.body[0][0] < 0 or snake.body[0][0] >= GRID_WIDTH or \
snake.body[0][1] < 0 or snake.body[0][1] >= GRID_HEIGHT:
running = False
snake.draw(screen)
food.draw(screen)
pygame.display.flip()
clock.tick(10)
pygame.quit()