python吃豆人AI

本文介绍了如何编程实现Pac-Man游戏AI,使用BFS算法规划吃豆人避开鬼怪的路径,确保吃到所有豆子并利用PowerPellets战术。

Pac-Man

You need to program the Pac-Man game, and its screenshot is shown in
Figure 1. The player controls Pac-Man, who must eat all the dots inside an
enclosed maze while avoiding four colored ghosts. Eating large flashing
dots called “Power Pellets” causes the ghosts to temporarily turn blue,
allowing Pac-Man to eat them for bonus points.
Yor can search Pac-Man and try to play the game first.

运行截图

在这里插入图片描述

算法简述

目标是避开鬼吃掉所有豆子
每走一步循环如下语句:

  1. 若没有目标豆子, 选择一个曼哈顿距离最近的豆子作为目标豆子
  2. bfs寻找前往目标豆子最近的路, 不能吃的鬼视作障碍物
  3. 根据最短路径的选择前进方向前进

例如:
初始吃豆人坐标为 start: (14, 15)
目标豆子坐标为 focus: [11, 15]
计算出的最短路径为 result: [(14, 15), (13, 15), (12, 15), (11, 15)]
则更换吃豆人方向为向上
走了一步后,
start: (13, 15)
focus: [11, 15]
result: [(13, 15), (12, 15), (11, 15)]
吃豆人方向为向上, 继续前进

算法AI代码如下:

class AI:
    def __init__(self):
        self.focus_pac = None
        self.pacman_location = None
        self.first = True
        
    def action(self):
        self.pacman_location = [int(game.pacman.row), int(game.pacman.col)]
		
		# 如果没有focus, 寻找一个豆子为目标
        if not self.focus_pac:
            self.focus_pac = self.get_nearst_pac()

        # 判断focus的豆子被吃没有, 被吃后换新的豆子
        if gameBoard[self.focus_pac[0]][self.focus_pac[1]] == 1:
            self.focus_pac = self.get_nearst_pac()

        # 规划前往focus的路线
        global visited, path, result
        m, n = len(gameBoard), len(gameBoard[
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值