AI人工智能 构建一个玩 “最后一枚硬币站立” 游戏的机器人

2026-02-27 11:26 更新

在这个游戏中,会有一堆硬币。每个玩家都必须从那堆硬币中拿走一些硬币。游戏的目标是避免拿走堆中的最后一枚硬币。我们将使用 easyAI 库中的 TwoPlayersGame 类继承的 LastCoinStanding 类。以下代码显示了这个游戏的 Python 代码:

导入所需的包,如下所示:

from easyAI import TwoPlayersGame, id_solve, Human_Player, AI_Player
from easyAI.AI import TT

现在,从 TwoPlayerGame 类继承这个类,以处理游戏的所有操作:

class LastCoin_game(TwoPlayersGame):
    def __init__(self, players):

现在,定义玩家和将要开始游戏的玩家:

self.players = players
        self.nplayer = 1

现在,定义游戏中的硬币数量,这里我们在游戏中使用 15 枚硬币:

self.num_coins = 15

定义玩家在一次移动中可以拿走的最大硬币数量:

self.max_coins = 4

现在,有一些特定的事情需要定义,如以下代码所示。定义可能的移动:

def possible_moves(self):
        return [str(a) for a in range(1, self.max_coins + 1)]

定义拿走硬币的操作:

def make_move(self, move):
        self.num_coins -= int(move)

定义谁拿走了最后一枚硬币:

def win_game(self):
        return self.num_coins

定义何时停止游戏,即当有人获胜时:

def is_over(self):
        return self.win()

定义如何计算分数:

def score(self):
        return 100 if self.win_game() else 0

定义堆中剩余的硬币数量:

def show(self):
        print(self.num_coins, 'coins left in the pile')
if __name__ == "__main__":
    tt = TT()
    LastCoin_game.ttentry = lambda self: self.num_coins

使用以下代码块解决游戏:

r, d, m = id_solve(LastCoin_game,
        range(2, 20), win_score=100, tt=tt)
    print(r, d, m)

决定谁将开始游戏:

game = LastCoin_game([AI_Player(tt), Human_Player()])
    game.play()

你可以看到以下输出和这个游戏的简单玩法:

d:2, a:0, m:1
d:3, a:0, m:1
d:4, a:0, m:1
d:5, a:0, m:1
d:6, a:100, m:4
1 6 4
15 coins left in the pile
Move #1: player 1 plays 4 :
11 coins left in the pile
Player 2 what do you play ? 2
Move #2: player 2 plays 2 :
9 coins left in the pile
Move #3: player 1 plays 3 :
6 coins left in the pile
Player 2 what do you play ? 1
Move #4: player 2 plays 1 :
5 coins left in the pile
Move #5: player 1 plays 4 :
1 coins left in the pile
Player 2 what do you play ? 1
Move #6: player 2 plays 1 :
0 coins left in the pile
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号