【发布时间】:2016-05-17 19:12:31
【问题描述】:
我是 python 新手,作为作业的一部分,我必须创建一个 connect 4 游戏。我有这个函数的 valid_moves 部分,但我不知道如何检查对手的棋子是否在哪里,以及我应该如何将我的棋子放在避免对手获胜但为我提供获胜优势的位置。代码如下:
def ai_player(board, turn, valid_moves):
"""
Inputs:
board: numpy array of the disks for each player, e.g.
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 2, 0, 0, 0, 0, 0],
[0, 0, 1, 2, 1, 0, 0, 0, 0, 0]]
- 0 empty locations
- 1 your disks
- 2 your opponents disks
turn: integer turn counter (starts from 1)
valid_moves: numpy array of valid col index numbers where a disk can be
placed, e.g. [0, 1, 2, 3, 4, 5, 6]
Return:
col index number --> an integer number of the col where you want to
place a disk e.g. 0 (NB: this return value must
appear in the valid_moves array)
"""
colIndex = range(10)
for i in range(len(valid_moves) - 1):
if turn == 1:
ind = colIndex[4]
elif turn > 1 and (len(valid_moves) > 0):
if valid_moves[colIndex[i] + 1] == 0 and colIndex[i] < 10:
ind += 1
elif valid_moves[colIndex[i] - 1] == 0:
ind -= 1
else:
# choose a random move to make from the valid_moves list
ind = random.randint(0, len(valid_moves)-1)
#This is my code to add my coin (1) at an empty position and after the opponents coin (2)
for j in range(len(valid_moves) - 1):
if(colIndex[i] == 2):
colIndex[i + 1] = 1
elif colIndex[i] == 0 and colIndex[i] == 1 and colIndex[i] != 2:
colIndex[i + 1] = 1
return valid_moves[ind]
任何帮助将不胜感激。
【问题讨论】:
-
我认为这确实是一个过于宽泛的问题,但作为一种天真的第一种方法,我会检查每列 4 的每个可能位置、每行 4 的每个位置和每个位置4 的对角线。如果你发现你的颜色有 3 个,而另一个空间是一个空隙,检查你是否可以在空隙中放置一个标记,并且你是否可以移动。如果你没有找到任何获胜的动作,重复寻找你的对手可能获胜的地方,你可以阻止。如果还是没找到招式,那就随机放置一个token(然后再考虑如何改进这一步)
-
我还会考虑将我的电路板建模为令牌堆栈而不是二维数组,这将简化添加令牌并且不会使搜索变得更加困难。
标签: python python-3.x