easyAI
1.0.0
EasyAi(这里的完整文档)是一个纯净的Python人工智能框架,用于两人抽象游戏,例如TIC TAC TOE,CONNECT 4,RECRVERSI等。它可以轻松定义游戏的机制,并与计算机进行游戏或解决游戏。在引擎盖下,AI是一种Negamax算法,如Wikipedia所述,带有α-Beta修剪和换位表。
如果已安装了pip ,请在终端中输入
sudo pip安装easyai
否则,请下载源代码(例如在github上),将所有内容解压缩到一个文件夹中,并在此文件夹中,在一个终端中,类型
sudo python setup.py安装
此外,您需要安装Numpy才能运行一些示例。
让我们定义游戏规则,并开始与AI的比赛:
from easyAI import TwoPlayerGame , Human_Player , AI_Player , Negamax
class GameOfBones ( TwoPlayerGame ):
""" 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 = None ):
self . players = players
self . pile = 20 # start with 20 bones in the pile
self . current_player = 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个骨头 玩家1您玩什么? 3 移动#1:播放器1播放3: 17个骨头留在堆中 移动#2:播放器2播放1: 一堆留下16个骨头 玩家1您玩什么?
现在让我们解决游戏:
from easyAI import solve_with_iterative_deepening
r , d , m = solve_with_iterative_deepening (
game = GameOfBones (),
ai_depths = range ( 2 , 20 ),
win_score = 100
)我们获得r=1 ,这意味着,如果两个球员都表现出色,那么第一个玩的球员总是可以获胜(-1将始终输), d=10 ,这意味着胜利将以十分胜(即每位播放器5个动作)或更少, m='3' ,这表明第一名球员的第一步应该是'3' 。
这些计算可以使用一个换位表加速,该表将存储所遇到的情况,并且每种情况的最佳动作:
tt = TranspositionTable ()
GameOfBones . ttentry = lambda game : game . pile # key for the table
r , d , m = solve_with_iterative_deepening (
game = GameOfBones (),
ai_depths = 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许可发布的开源软件。欢迎捐款!一些想法:用于不完整的信息游戏的AI算法,更好的游戏解决策略,(有效)使用数据库存储移动,使用并行化的AI算法。
对于故障排除和错误报告,目前最好的是在Github上询问。
每次MR合并到主人中时,都会发生自动发布: