ai人工智能python_人工智能与Python –游戏

ai人工智能python_人工智能与Python –游戏_第1张图片

ai人工智能python

人工智能与Python –游戏 (AI with Python – Gaming)

Games are played with a strategy. Every player or team would make a strategy before starting the game and they have to change or build new strategy according to the current situation(s) in the game.

游戏是一种策略。 每个玩家或团队都会在开始游戏之前制定策略,并且他们必须根据游戏的当前情况来更改或建立新策略。

搜索算法 (Search Algorithms)

You will have to consider computer games also with the same strategy as above. Note that Search Algorithms are the ones that figure out the strategy in computer games.

您还必须考虑具有与上述相同策略的计算机游戏。 请注意,搜索算法是找出计算机游戏策略的算法。

这个怎么运作 (How it works)

The goal of search algorithms is to find the optimal set of moves so that they can reach at the final destination and win. These algorithms use the winning set of conditions, different for every game, to find the best moves.

搜索算法的目标是找到最佳移动方式,以便它们可以到达最终目的地并获胜。 这些算法使用获胜的条件集(每场比赛都不同)来找出最佳动作。

Visualize a computer game as the tree. We know that tree has nodes. Starting from the root, we can come to the final winning node, but with optimal moves. That is the work of search algorithms. Every node in such tree represents a future state. The search algorithms search through this tree to make decisions at each step or node of the game.

将计算机游戏可视化为树。 我们知道树上有节点。 从根开始,我们可以到达最终的获胜节点,但要采取最佳措施。 那就是搜索算法的工作。 这样的树中的每个节点都代表一个未来状态。 搜索算法搜索该树以在游戏的每个步骤或节点处做出决策。

组合搜寻 (Combinational Search)

The major disadvantage of using search algorithms is that they are exhaustive in nature, which is why they explore the entire search space to find the solution that leads to wastage of resources. It would be more cumbersome if these algorithms need to search the whole search space for finding the final solution.

使用搜索算法的主要缺点是它们本质上是详尽无遗的,这就是为什么他们探索整个搜索空间以找到导致资源浪费的解决方案的原因。 如果这些算法需要搜索整个搜索空间以找到最终解决方案,则将更加麻烦。

To eliminate such kind of problem, we can use combinational search which uses the heuristic to explore the search space and reduces its size by eliminating the possible wrong moves. Hence, such algorithms can save the resources. Some of the algorithms that use heuristic to search the space and save the resources are discussed here −

为了消除此类问题,我们可以使用组合搜索,该组合搜索使用启发式方法探索搜索空间,并通过消除可能的错误举动来减小搜索空间的大小。 因此,这样的算法可以节省资源。 这里讨论了一些使用启发式搜索空间并节省资源的算法-

极小极大算法 (Minimax Algorithm)

It is the strategy used by combinational search that uses heuristic to speed up the search strategy. The concept of Minimax strategy can be understood with the example of two player games, in which each player tries to predict the next move of the opponent and tries to minimize that function. Also, in order to win, the player always try to maximize its own function based on the current situation.

组合搜索使用的策略是使用启发式方法来加快搜索策略的速度。 可以通过两个玩家游戏的例子来理解Minimax策略的概念,其中每个玩家都试图预测对手的下一步行动并尝试最小化该功能。 另外,为了获胜,玩家总是尝试根据当前情况最大化其自身的功能。

Heuristic plays an important role in such kind of strategies like Minimax. Every node of the tree would have a heuristic function associated with it. Based on that heuristic, it will take the decision to make a move towards the node that would benefit them the most.

启发式算法在诸如Minimax之类的策略中起着重要作用。 树的每个节点都将具有与之关联的启发式功能。 基于这种启发式方法,将决定朝着最有利于他们的节点前进。

Alpha-Beta修剪 (Alpha-Beta Pruning)

A major issue with Minimax algorithm is that it can explore those parts of the tree that are irrelevant, leads to the wastage of resources. Hence there must be a strategy to decide which part of the tree is relevant and which is irrelevant and leave the irrelevant part unexplored. Alpha-Beta pruning is one such kind of strategy.

Minimax算法的一个主要问题是它可以探索树上不相关的部分,从而导致资源浪费。 因此,必须有一种策略来确定树的哪一部分是相关的,哪一部分是不相关的,并且不进行探索的。 Alpha-Beta修剪就是这样一种策略。

The main goal of Alpha-Beta pruning algorithm is to avoid the searching those parts of the tree that do not have any solution. The main concept of Alpha-Beta pruning is to use two bounds named Alpha, the maximum lower bound, and Beta, the minimum upper bound. These two parameters are the values that restrict the set of possible solutions. It compares the value of the current node with the value of alpha and beta parameters, so that it can move to the part of the tree that has the solution and discard the rest.

Alpha-Beta修剪算法的主要目标是避免搜索树上那些没有任何解决方案的部分。 Alpha-Beta修剪的主要概念是使用两个界限,分别是最大下界Alpha和最小上界Beta 。 这两个参数是限制可能的解决方案集的值。 它将当前节点的值与alpha和beta参数的值进行比较,以便它可以移至树中具有解的部分,并丢弃其余部分。

Negamax算法 (Negamax Algorithm)

This algorithm is not different from Minimax algorithm, but it has a more elegant implementation. The main disadvantage of using Minimax algorithm is that we need to define two different heuristic functions. The connection between these heuristic is that, the better a state of a game is for one player, the worse it is for the other player. In Negamax algorithm, the same work of two heuristic functions is done with the help of a single heuristic function.

该算法与Minimax算法没有什么不同,但是它的实现更为优雅。 使用Minimax算法的主要缺点是我们需要定义两个不同的启发式函数。 这些启发式方法之间的联系是,一个玩家的游戏状态越好,另一玩家的游戏状态越差。 在Negamax算法中,借助单个启发式函数完成两个启发式函数的相同工作。

建立机器人玩游戏 (Building Bots to Play Games)

For building bots to play two player games in AI, we need to install the easyAI library. It is an artificial intelligence framework that provides all the functionality to build two-player games. You can download it with the help of the following command −

为了使机器人能够在AI中玩两个玩家游戏,我们需要安装easyAI库。 这是一个人工智能框架,提供了构建两人游戏的所有功能。 您可以在以下命令的帮助下下载它-


pip install easyAI

玩最后一枚硬币的机器人 (A Bot to Play Last Coin Standing)

In this game, there would be a pile of coins. Each player has to take a number of coins from that pile. The goal of the game is to avoid taking the last coin in the pile. We will be using the class LastCoinStanding inherited from the TwoPlayersGame class of the easyAI library. The following code shows the Python code for this game −

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

Import the required packages as shown −

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


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

Now, inherit the class from the TwoPlayerGame class to handle all operations of the game −

现在,从TwoPlayerGame类继承该类以处理游戏的所有操作-


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

Now, define the players and the player who is going to start the game.

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


self.players = players
self.nplayer = 1

Now, define the number of coins in the game, here we are using 15 coins for the game.

现在,定义游戏中的硬币数量,此处我们使用15个游戏硬币。


self.num_coins = 15

Define the maximum number of coins a player can take in a move.

定义玩家可以移动的最大硬币数。


self.max_coins = 4

Now there are some certain things to define as shown in the following code. Define possible moves.

现在,需要定义一些特定的东西,如以下代码所示。 定义可能的动作。


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

Define the removal of the coins

定义硬币的去除


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

Define who took the last coin.

定义谁拿了最后一个硬币。


def win_game(self):
   return self.num_coins <= 0

Define when to stop the game, that is when somebody wins.

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


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

Define how to compute the score.

定义如何计算分数。


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

Define number of coins remaining in the pile.

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


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

Solving the game with the following code block −

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


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

Deciding who will start the game

决定谁开始游戏


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

You can find the following output and a simple play of this game −

您可以找到以下输出和该游戏的简单玩法-


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

玩井字游戏的机器人 (A Bot to Play Tic Tac Toe)

Tic-Tac-Toe is very familiar and one of the most popular games. Let us create this game by using the easyAI library in Python. The following code is the Python code of this game −

井字游戏非常熟悉,是最受欢迎的游戏之一。 让我们通过使用Python中的easyAI库来创建此游戏。 以下代码是该游戏的Python代码-

Import the packages as shown −

如图所示导入软件包-


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

Inherit the class from the TwoPlayerGame class to handle all operations of the game −

TwoPlayerGame类继承该类以处理游戏的所有操作-


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

Now, define the players and the player who is going to start the game −

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


self.players = players
self.nplayer = 1

Define the type of board −

定义板的类型-


self.board = [0] * 9

Now there are some certain things to define as follows −

现在有一些定义如下:

Define possible moves

定义可能的动作


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

Define the move of a player −

定义玩家的动作-


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

To boost AI, define when a player makes a move −

为了增强AI,请定义玩家何时行动-


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

Define the lose condition that an opponent have three in a line

定义对手连续三局输掉的条件


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])

Define a check for the finish of game

定义比赛结束的检查


def is_over(self):
   return (self.possible_moves() == []) or self.condition_for_lose()

Show the current position of the players in the game

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


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)]))

Compute the scores.

计算分数。


def scoring(self):
   return -100 if self.condition_for_lose() else 0

Define the main method to define the algorithm and start the game −

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


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

You can see the following output and a simple play of this game −

您可以看到以下输出和该游戏的简单玩法-


. . .
. . .
. . .
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.tutorialspoint.com/artificial_intelligence_with_python/artificial_intelligence_with_python_gaming.htm

ai人工智能python

你可能感兴趣的:(游戏,算法,人工智能,python,java)