目录
这次,我们转换一种思路,不再在主函数中直接使用循环运行游戏,而是使用定义游戏类,在类的方法中使用循环,并在游戏类中定义食物产生、蛇头移动、键盘移动、游戏运行等方法
一、前言
这次,我们使用python实现简易的贪吃蛇,食物会在限定屏幕区域随机出现,当蛇头触碰到食物时,食物消失,同时蛇的长度增加一。当蛇头触碰到蛇身任意一个地方时,游戏结束。当蛇头或蛇身超出屏幕范围时,不会判定死亡,而是会在屏幕对应的另一端出现。
二、代码详解
首先,我们完成游戏的基本设置,包括导入库和设置游戏窗口的大小、蛇移动的方向
import pygame
import random
pygame.init()
# 游戏窗口的宽度和高度
WIDTH, HEIGHT = 640, 480
# 定义颜色
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 定义方向
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
这次,我们转换一种思路,不再在主函数中直接使用循环运行游戏,而是使用定义游戏类,在类的方法中使用循环,并在游戏类中定义食物产生、蛇头移动、键盘移动、游戏运行等方法
食物产生方法中,通过随机数产生食物的随机横纵坐标
在移动方法中,当蛇头的坐标和食物坐标重合时,更新新的“蛇头”,同时产生新的食物(调用食物产生方法)
事件处理方法用于捕获玩家操控的按键,并作出相应的方向变换
class SnakeGame:
def __init__(self):
self.width, self.height = WIDTH, HEIGHT
self.window = pygame.display.set_mode((self.width, self.height))
pygame.display.set_caption("贪吃蛇")
self.clock = pygame.time.Clock()
self.snake = [(self.width // 2, self.height // 2)]
self.food = self.spawn_food()
self.direction = RIGHT
def spawn_food(self):
x = random.randrange(1, self.width // 10) * 10
y = random.randrange(1, self.height // 10) * 10
return x, y
def move(self):
head = self.snake[-1]
x, y = self.direction
new_head = ((head[0] + x * 10) % self.width, (head[1] + y * 10) % self.height)
if new_head in self.snake:
return False
self.snake.append(new_head)
if new_head == self.food:
self.food = self.spawn_food()
else:
self.snake.pop(0)
return True
def handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and self.direction != DOWN:
self.direction = UP
elif event.key == pygame.K_DOWN and self.direction != UP:
self.direction = DOWN
elif event.key == pygame.K_LEFT and self.direction != RIGHT:
self.direction = LEFT
elif event.key == pygame.K_RIGHT and self.direction != LEFT:
self.direction = RIGHT
def run(self):
while True:
self.handle_events()
if not self.move():
break
self.window.fill(WHITE)
pygame.draw.rect(self.window, GREEN, (self.food[0], self.food[1], 10, 10))
for segment in self.snake:
pygame.draw.rect(self.window, RED, (segment[0], segment[1], 10, 10))
pygame.display.update()
self.clock.tick(15) # 控制贪吃蛇的速度
三、最终成果展示
最终代码
import pygame
import random
pygame.init()
# 游戏窗口的宽度和高度
WIDTH, HEIGHT = 640, 480
# 定义颜色
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 定义方向
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
class SnakeGame:
def __init__(self):
self.width, self.height = WIDTH, HEIGHT
self.window = pygame.display.set_mode((self.width, self.height))
pygame.display.set_caption("贪吃蛇")
self.clock = pygame.time.Clock()
self.snake = [(self.width // 2, self.height // 2)]
self.food = self.spawn_food()
self.direction = RIGHT
def spawn_food(self):
x = random.randrange(1, self.width // 10) * 10
y = random.randrange(1, self.height // 10) * 10
return x, y
def move(self):
head = self.snake[-1]
x, y = self.direction
new_head = ((head[0] + x * 10) % self.width, (head[1] + y * 10) % self.height)
if new_head in self.snake:
return False
self.snake.append(new_head)
if new_head == self.food:
self.food = self.spawn_food()
else:
self.snake.pop(0)
return True
def handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and self.direction != DOWN:
self.direction = UP
elif event.key == pygame.K_DOWN and self.direction != UP:
self.direction = DOWN
elif event.key == pygame.K_LEFT and self.direction != RIGHT:
self.direction = LEFT
elif event.key == pygame.K_RIGHT and self.direction != LEFT:
self.direction = RIGHT
def run(self):
while True:
self.handle_events()
if not self.move():
break
self.window.fill(WHITE)
pygame.draw.rect(self.window, GREEN, (self.food[0], self.food[1], 10, 10))
for segment in self.snake:
pygame.draw.rect(self.window, RED, (segment[0], segment[1], 10, 10))
pygame.display.update()
self.clock.tick(15) # 控制贪吃蛇的速度
if __name__ == "__main__":
game = SnakeGame()
game.run()