首先,我们需要导入pygame
库来实现游戏的图形化界面:
import pygame
然后,定义一些常量来表示游戏窗口的宽度和高度、蛇身的大小、食物的大小等:
WIDTH = 600
HEIGHT = 400
SNAKE_SIZE = 20
FOOD_SIZE = 20
接下来,定义一个Snake
类来表示蛇的属性和行为:
class Snake:
def __init__(self):
self.head = [100, 50] # 蛇头的位置
self.body = [[100, 50], [90, 50], [80, 50]] # 蛇身的位置
self.direction = "RIGHT" # 蛇的移动方向
def move(self):
if self.direction == "RIGHT":
self.head[0] += SNAKE_SIZE
elif self.direction == "LEFT":
self.head[0] -= SNAKE_SIZE
elif self.direction == "UP":
self.head[1] -= SNAKE_SIZE
elif self.direction == "DOWN":
self.head[1] += SNAKE_SIZE
# 将新的蛇头位置添加到蛇身中
self.body.insert(0, list(self.head))
# 如果蛇头和食物的位置重合,则蛇吃到了食物,身体增长
if self.head[0] == food.position[0] and self.head[1] == food.position[1]:
food.generate() # 生成新的食物
else:
self.body.pop() # 否则,蛇身减少一个位置
def change_direction(self, direction):
# 不允许蛇直接掉头
if direction == "RIGHT" and self.direction != "LEFT":
self.direction = "RIGHT"
elif direction == "LEFT" and self.direction != "RIGHT":
self.direction = "LEFT"
elif direction == "UP" and self.direction != "DOWN":
self.direction = "UP"
elif direction == "DOWN" and self.direction != "UP":
self.direction = "DOWN"
然后,定义一个Food
类来表示食物的属性和行为:
class Food:
def __init__(self):
self.position = [0, 0]
def generate(self):
# 随机生成食物的位置
self.position[0] = random.randint(1, (WIDTH - FOOD_SIZE) / FOOD_SIZE) * FOOD_SIZE
self.position[1] = random.randint(1, (HEIGHT - FOOD_SIZE) / FOOD_SIZE) * FOOD_SIZE
接下来,初始化游戏并创建蛇和食物的实例:
pygame.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇小游戏")
snake = Snake()
food = Food()
food.generate()
然后,创建一个游戏循环,处理用户的输入和游戏逻辑:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
snake.change_direction("RIGHT")
elif event.key == pygame.K_LEFT:
snake.change_direction("LEFT")
elif event.key == pygame.K_UP:
snake.change_direction("UP")
elif event.key == pygame.K_DOWN:
snake.change_direction("DOWN")
snake.move()
# 判断蛇是否撞到墙壁或自己的身体
if snake.head[0] >= WIDTH or snake.head[0] < 0 or snake.head[1] >= HEIGHT or snake.head[1] < 0 or snake.head in snake.body[1:]:
pygame.quit()
sys.exit()
window.fill((255, 255, 255))
# 绘制蛇的身体
for pos in snake.body:
pygame.draw.rect(window, (0, 255, 0), pygame.Rect(pos[0], pos[1], SNAKE_SIZE, SNAKE_SIZE))
# 绘制食物
pygame.draw.rect(window, (255, 0, 0), pygame.Rect(food.position[0], food.position[1], FOOD_SIZE, FOOD_SIZE))
pygame.display.update