LinuxSir.cn,穿越时空的Linuxsir!

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

机器人玩井字游戏

[复制链接]
发表于 2024-1-4 19:10:01 | 显示全部楼层 |阅读模式

机器人玩井字游戏

Tic-Tac-Toe非常熟悉,是最受欢迎的游戏之一。我们通过使用Python中的easyAI库来创建这个游戏。 以下代码是这款游戏的Python代码 -
如下所示导入软件包 -

from easyAI import TwoPlayersGame, AI_Player, Negamax
from easyAI.Player import Human_Player

继承TwoPlayerGame中的类来处理游戏的所有操作 -

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

现在,定义玩家并开始游戏 -

self.players = players
self.nplayer = 1

定义板的类型 -

self.board = [0] * 9

定义可能的举措(动作)

def possible_moves(self):
    return [x + 1 for x, y in enumerate(self.board) if y == 0]

定义一个玩家的举措(动作) -

def make_move(self, move):
    self.board[int(move) - 1] = self.nplayer

定义一个玩家何时进行移动 -

def umake_move(self, move):
   self.board[int(move) - 1] = 0

定义输条件是对手在一条线上有三个 -
  
def condition_for_lose(self):
   possible_combinations = [[1,2,3], [4,5,6], [7,8,9],
      [1,4,7], [2,5,8], [3,6,9], [1,5,9], [3,5,7]]
   return any([all([(self.board[z-1] == self.nopponent)
      for z in combination]) for combination in possible_combinations])

定义游戏结束的条件 -
  
def is_over(self):
   return (self.possible_moves() == []) or self.condition_for_lose()

显示玩家在游戏中的当前位置 -

def show(self):
   print('\n'+'\n'.join([' '.join([['.', 'O', 'X'][self.board[3*j + i]]
      for i in range(3)]) for j in range(3)]))

计算分数代码 -
  
def scoring(self):
   return -100 if self.condition_for_lose() else 0

定义定义算法并开始游戏的主要方法 -

if __name__ == "__main__":
   algo = Negamax(7)
   TicTacToe_game([Human_Player(), AI_Player(algo)]).play()

可以看到下面的输出和这个游戏的简单玩法 -
. . .
. . .
. . .
Player 1 what do you play ? 1
Move #1: player 1 plays 1 :
O . .
. . .
. . .
Move #2: player 2 plays 5 :
O . .
. X .
121
. . .
Player 1 what do you play ? 3
Move #3: player 1 plays 3 :
O . O
. X .
. . .
Move #4: player 2 plays 2 :
O X O
. X .
. . .
Player 1 what do you play ? 4
Move #5: player 1 plays 4 :
O X O
O X .
. . .
Move #6: player 2 plays 8 :
O X O
O X .
. X .
//更多请阅读:https://www.yiibai.com/ai_with_python/ai_with_python_gaming.html


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

本版积分规则

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