Python自动寻路贪吃蛇:广度优先搜索与Turtle库实战

想学习如何使用Python创建自动寻路的贪吃蛇游戏吗?本文将带你使用广度优先搜索算法(BFS)和Turtle库实现这一目标。

代码实现pythonimport turtleimport queueimport random

游戏窗口的大小window_width = 400window_height = 400

格子的大小grid_size = 20

snake_color = 'green'food_color = 'red'

定义蛇的类class Snake: def init(self): self.head = [0, 0] self.body = [[0, 0]]

def move(self, direction):        if direction == 'up':            self.head[1] += grid_size        elif direction == 'down':            self.head[1] -= grid_size        elif direction == 'left':            self.head[0] -= grid_size        elif direction == 'right':            self.head[0] += grid_size

    self.body.insert(0, list(self.head))        self.body.pop()

def eat_food(self, food):        if self.head == food.position:            self.body.append(food.position)            return True        return False

def check_collision(self):        if (            self.head[0] >= window_width / 2            or self.head[0] < -window_width / 2            or self.head[1] >= window_height / 2            or self.head[1] < -window_height / 2        ):            return True        for body_part in self.body[1:]:            if self.head == body_part:                return True        return False

def draw(self):        turtle.penup()        turtle.goto(self.head[0], self.head[1])        turtle.pendown()        turtle.pensize(grid_size)        turtle.pencolor(snake_color)        turtle.goto(self.head[0], self.head[1])        turtle.penup()

    for body_part in self.body[1:]:            turtle.goto(body_part[0], body_part[1])            turtle.pendown()            turtle.goto(body_part[0], body_part[1])            turtle.penup()

定义食物的类class Food: def init(self, position): self.position = position

def draw(self):        turtle.penup()        turtle.goto(self.position[0], self.position[1])        turtle.pendown()        turtle.pensize(grid_size)        turtle.pencolor(food_color)        turtle.goto(self.position[0], self.position[1])        turtle.penup()

广度优先搜索算法来寻找路径def bfs_search(start, end, obstacles): q = queue.Queue() q.put(start) visited = set() path = {} found = False

while not q.empty():        current = q.get()

    if current == end:            found = True            break

    x, y = current        next_positions = [(x+grid_size, y), (x-grid_size, y), (x, y+grid_size), (x, y-grid_size)]

    for next_pos in next_positions:            if next_pos not in obstacles and next_pos not in visited:                q.put(next_pos)                visited.add(next_pos)                path[next_pos] = current

if found:        shortest_path = []        current = end        while current != start:            shortest_path.append(current)            current = path[current]        shortest_path.reverse()        return shortest_path

return None

初始化游戏界面def setup_game(): turtle.setup(window_width, window_height) turtle.bgcolor('black') turtle.tracer(0)

主游戏循环def game_loop(): snake = Snake() food = Food([grid_sizerandom.randint(-window_width//grid_size//2+1, window_width//grid_size//2-1), grid_sizerandom.randint(-window_height//grid_size//2+1, window_height//grid_size//2-1)])

while True:        turtle.clear()        snake.draw()        food.draw()        turtle.update()

    # 使用广度优先搜索算法寻找蛇头到食物的路径        obstacles = list(snake.body)        path = bfs_search(snake.head, food.position, obstacles)

    if path:            # 获取蛇头下一步要走的方向            next_pos = path[0]            if next_pos[0] > snake.head[0]:                direction = 'right'            elif next_pos[0] < snake.head[0]:                direction = 'left'            elif next_pos[1] > snake.head[1]:                direction = 'up'            else:                direction = 'down'

        snake.move(direction)        else:            break

    if snake.eat_food(food):            food = Food([grid_size*random.randint(-window_width//grid_size//2+1, window_width//grid_size//2-1),                         grid_size*random.randint(-window_height//grid_size//2+1, window_height//grid_size//2-1)])

    if snake.check_collision():            break

    turtle.delay(100)

turtle.goto(0, 0)    turtle.write('Game Over', align='center', font=('Arial', 16, 'normal'))    turtle.done()

启动游戏if name == 'main': setup_game() game_loop()

代码解释

  • 游戏对象: 我们定义了 SnakeFood 类来表示贪吃蛇和食物。- 广度优先搜索: bfs_search 函数实现了广度优先搜索算法,用于寻找蛇头到食物的最短路径。- 游戏循环: game_loop 函数是游戏的核心循环,控制着蛇的移动、食物的生成以及碰撞检测。- 自动寻路: 在每一帧中,游戏都会使用 bfs_search 函数计算蛇头到食物的最短路径,并根据路径移动蛇。

总结

通过结合广度优先搜索算法和 Turtle 库,我们成功地创建了一个自动寻路的贪吃蛇游戏。你可以根据自己的喜好修改代码,例如改变游戏速度、添加障碍物等等。

Python自动寻路贪吃蛇:广度优先搜索与Turtle库实战

原文地址: https://www.cveoy.top/t/topic/XLm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录