我想创建一种算法,为计算机生成井字棋移动的最佳位置。另外,井字棋函数的行和列值必须随机生成,然后需要检查最佳位置。它还必须在一个函数 get_computer_move() 中完成。我所做的考虑了一些情况,但它并不总是计算出最佳的移动。有什么办法可以做到吗?
代码:
import random
def choose_computer_move(board):
# develop code to let the computer chose a cell to put a nought in
# and return row and col
# Option Lists
vertical = [[[0,0],[0,1],[0,2]],[[0,1],[1,1],[2,1]],[[0,2],[1,2],[2,2]]]
horizonal = [[[0,0],[0,1],[0,2]],[[1,0],[1,1],[1,2]],[[2,0], [2,1], [2,2]]]
diagonal = [[[0,0],[1,1],[2,2]],[[2,0],[1,1],[0,2]]]
# Generate row col
while True:
row = random.randint(0,2)
col = random.randint(0,2)
if board[row][col] == " ":
break
types = [vertical, horizonal, diagonal]
for t in types:
# Total amount of lists ins inside list
for i in range(len(t)):
# If the value is inside the 2nd List
if [row,col] in t[i]:
# Generate the index inside the list
coord = t[i].index([row,col])
# Check if the other values == O inside the list
num_list = [0,1,2]
num_list.remove(coord)
t_val = t[i][num_list[0]]
t_val2 = t[i][num_list[1]]
if board[t_val[0]][t_val[1]] == "O" and board[t_val2[0]][t_val2[1]] == "O":
print(row,col)
return row,col
else:
print("Not in row col")
for v in types:
# Total amount of lists ins inside list
for j in range(len(v)):
# If the value is inside the 2nd List
if [row,col] in v[j]:
# Generate the index inside the list
coord_two = v[j].index([row,col])
# Check if the other values == O inside the list
num_two_list = [0,1,2]
num_two_list.remove(coord_two)
v_val = v[j][num_list[0]]
v_val2 = v[j][num_list[1]]
if board[v_val[0]][v_val[1]] == "O" or board[v_val2[0]][v_val2[1]] == "O":
print(row,col)
return row,col
else:
print("Not in row col")
我希望它生成最佳函数,但我想不出一种方法可以考虑所有情况,然后生成最佳位置。
我曾经使用 alpha-beta 剪枝算法创建了 tic-tac-toe 游戏,以找到优化的动作,以便用户和计算机都可以公平地玩。这是要点:https://gist.github.com/Anonym0usWork1221/a0966f7e73671a59ef148e2766a5c88d