易于使用的游戏人工智能算法(Negamax等)
easyA的Python项目详细描述
easyai(full documentationhere)是一个纯python人工智能框架,用于两个玩家的抽象游戏,如tic tac toe、connect 4、reversi等。 它使得定义一个游戏的机制、与计算机对抗或解决游戏变得很容易。 在幕后,ai是一个negamax算法,具有alpha-beta剪枝和换位表,如Wikipedia所述。
安装
如果已安装pip,请在终端中键入此命令
sudo pip install easyAI
否则,请下载源代码(例如Github),将所有内容解压缩到一个文件夹中,然后在此文件夹中的终端中键入
sudo python setup.py install
另外,您需要安装numpy才能运行一些示例。
一个简单的例子
让我们定义游戏规则并开始与ai的比赛:
from easyAI import TwoPlayersGame, Human_Player, AI_Player, Negamax class GameOfBones( TwoPlayersGame ): """ In turn, the players remove one, two or three bones from a pile of bones. The player who removes the last bone loses. """ def __init__(self, players): self.players = players self.pile = 20 # start with 20 bones in the pile self.nplayer = 1 # player 1 starts def possible_moves(self): return ['1','2','3'] def make_move(self,move): self.pile -= int(move) # remove bones. def win(self): return self.pile<=0 # opponent took the last bone ? def is_over(self): return self.win() # Game stops when someone wins. def show(self): print "%d bones left in the pile"%self.pile def scoring(self): return 100 if game.win() else 0 # For the AI # Start a match (and store the history of moves when it ends) ai = Negamax(13) # The AI will think 13 moves in advance game = GameOfBones( [ Human_Player(), AI_Player(ai) ] ) history = game.play()
结果:
20 bones left in the pile Player 1 what do you play ? 3 Move #1: player 1 plays 3 : 17 bones left in the pile Move #2: player 2 plays 1 : 16 bones left in the pile Player 1 what do you play ?
解决游戏
现在让我们来解决这个游戏:
from easyAI import id_solve r,d,m = id_solve(GameOfBones, ai_depths=range(2,20), win_score=100)
我们得到r=1,这意味着如果两个玩家都玩得很好,第一个玩家总是可以赢(-1意味着总是输),d=10,这意味着赢将在10步之内(即每个玩家5步)或者更少,并且m='3',这意味着第一个玩家的第一步应该是'3'。
这些计算可以使用转置表来加速,转置表将存储遇到的情况和每个情况下的最佳移动:
tt = TT() GameOfBones.ttentry = lambda game : game.pile # key for the table r,d,m = id_solve(GameOfBones, range(2,20), win_score=100, tt=tt)
运行这些行之后,变量tt包含一个换位表,其中存储了可能的情况(这里是可能的堆大小)和要执行的最佳移动。有了tt,你就可以在没有思考的情况下完美地演奏了:
game = GameOfBones( [ AI_Player( tt ), Human_Player() ] ) game.play() # you will always lose this game :)
贡献!
easyai是一个开源软件,最初由Zulko编写,在mit许可下发布。它可以做一些改进,所以如果您是一个python/ai大师,也许您可以通过Github做出贡献。一些想法:不完全信息游戏的人工智能算法,更好的游戏解决策略,(高效)使用数据库存储移动,使用并行的人工智能算法。
对于故障排除和错误报告,现在最好是询问Github。