易于使用的游戏人工智能算法(Negamax等)
项目描述
EasyAI(完整文档在此)是一个纯Python人工智能框架,用于两位玩家的抽象游戏,如井字棋、四子棋、翻转棋等。它使得定义游戏机制变得容易,可以与电脑对弈或解决游戏。在底层,AI是一个具有alpha-beta剪枝和置换表的Negamax算法,如维基百科所述。
安装
如果您已安装pip,请在终端中输入以下内容
sudo pip install easyAI
否则,下载源代码(例如在Github上),将所有内容解压缩到一个文件夹中,然后在终端中输入
sudo python setup.py install
此外,您还需要安装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 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 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,这意味着胜利将在十步之内(即每名玩家五步),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 提问。
维护者
项目详情
下载文件
下载适合您平台的文件。如果您不确定选择哪个,请了解有关 安装包 的更多信息。
源代码分布
easyAI-2.0.12.tar.gz (29.3 kB 查看哈希值)
构建分布
easyAI-2.0.12-py3-none-any.whl (42.2 kB 查看哈希值)
关闭
easyAI-2.0.12.tar.gz 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 8c4d2d488bcd81578e1b48d38158bc50353dfd4ab3ab04e4ddac637e08378fbe |
|
MD5 | 988b0973c1a1f97f61c337921a2c95e6 |
|
BLAKE2b-256 | 5ff20f799df322bdeffd2dca758c9b64905b8cc7a27415701b751f415a81180b |
关闭
easyAI-2.0.12-py3-none-any.whl 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 9ad5444bdc729b60baa39c60d28dd9c677aaec12e27b7972183859f1a0946ee1 |
|
MD5 | 0c66a61ce05687f32254fd7a761eac57 |
|
BLAKE2b-256 | 632a927324350557a2da87d59830588ce0c58f67e75384b55af4e82883f0b9cc |