LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 192|回复: 0

建设机器人玩游戏

[复制链接]
发表于 2024-1-3 18:02:40 | 显示全部楼层 |阅读模式
建设机器人玩游戏
要在AI中构建机器人玩两个玩家游戏,需要安装easyAI库。 这是一个人工智能框架,提供了构建双人游戏的所有功能。 可以通过以下命令下载它 -

pip install easyAI

一个机器人玩最后的硬币

在这场比赛中,会有一堆硬币。 每个玩家必须从该堆中取出一些硬币。这场比赛的目标是避免拿下最后一枚硬币。 我们将使用继承自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 <= 0

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

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


//更多请阅读:https://www.yiibai.com/ai_with_python/ai_with_python_gaming.html


您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表