用DFS写一个自动贪吃蛇小游戏
时间: 2024-01-07 16:02:29 浏览: 72
以下是用DFS(深度优先搜索)实现自动贪吃蛇小游戏的示例代码:
```python
import pygame
import random
# 定义游戏区域大小和每个格子大小
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 400
GRID_SIZE = 20
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 定义方向常量
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
# 定义贪吃蛇类
class Snake:
def __init__(self):
self.body = [(10, 10), (10, 11), (10, 12)] # 初始位置为 (10, 10), (10, 11), (10, 12)
self.direction = RIGHT # 初始方向向右
self.color = GREEN
def move(self):
# 根据方向移动蛇头
head = self.body[-1]
if self.direction == UP:
self.body.append((head[0], head[1] - 1))
elif self.direction == DOWN:
self.body.append((head[0], head[1] + 1))
elif self.direction == LEFT:
self.body.append((head[0] - 1, head[1]))
elif self.direction == RIGHT:
self.body.append((head[0] + 1, head[1]))
# 删除尾部,即蛇尾部分
self.body.pop(0)
def change_direction(self, direction):
# 防止蛇头掉头
if self.direction == UP and direction == DOWN:
return
elif self.direction == DOWN and direction == UP:
return
elif self.direction == LEFT and direction == RIGHT:
return
elif self.direction == RIGHT and direction == LEFT:
return
# 修改方向
self.direction = direction
def draw(self, surface):
# 绘制蛇的每一节
for i, pos in enumerate(self.body):
pygame.draw.rect(surface, self.color, (pos[0] * GRID_SIZE, pos[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE))
pygame.draw.rect(surface, BLACK, (pos[0] * GRID_SIZE, pos[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE), 1)
# 定义食物类
class Food:
def __init__(self):
self.pos = (0, 0) # 食物的初始位置
self.color = RED
def generate(self, snake_body):
# 生成一个新的食物位置
while True:
x = random.randint(0, SCREEN_WIDTH // GRID_SIZE - 1)
y = random.randint(0, SCREEN_HEIGHT // GRID_SIZE - 1)
if (x, y) not in snake_body:
self.pos = (x, y)
break
def draw(self, surface):
# 绘制食物
pygame.draw.rect(surface, self.color, (self.pos[0] * GRID_SIZE, self.pos[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE))
# 定义游戏主函数
def main():
# 初始化 pygame
pygame.init()
# 创建游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# 创建贪吃蛇
snake = Snake()
# 创建食物
food = Food()
food.generate(snake.body)
# 设置游戏帧率
clock = pygame.time.Clock()
# 游戏主循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
snake.change_direction(UP)
elif event.key == pygame.K_DOWN:
snake.change_direction(DOWN)
elif event.key == pygame.K_LEFT:
snake.change_direction(LEFT)
elif event.key == pygame.K_RIGHT:
snake.change_direction(RIGHT)
# 移动贪吃蛇
snake.move()
# 判断是否吃到食物
if snake.body[-1] == food.pos:
food.generate(snake.body)
snake.body.insert(0, snake.body[0])
# 绘制背景和游戏元素
screen.fill(WHITE)
snake.draw(screen)
food.draw(screen)
# 更新屏幕
pygame.display.update()
# 控制帧率
clock.tick(10)
if __name__ == '__main__':
main()
```
以上代码实现了一个基本的贪吃蛇游戏,通过键盘控制蛇的方向。如果要使用DFS实现自动贪吃蛇,可以考虑在每次移动之前,通过DFS搜索下一步的最佳方向,然后再移动蛇。具体实现方法可以参考一些相关的文章和代码。
阅读全文