好的,我还有一个关于我正在构建的井字游戏的问题。:P 我正在做的是编写一个无与伦比的 AI,所以我现在的工作是,如果计算机先启动,它将遵循必要的步骤来赢得或平局,但是,我不知道如何使用算法,主要是 minimax(),(因为这是我正在制作的第一个实际程序)并且不太完全确定如何简化我所有的 if - 语句。
到目前为止,我为 AI 提供的代码如下:
if strategy == False:
slot[0] = computer_team
if slot[1] == user_team or slot [2] == user_team and (slot[3] != user_team) \
and (slot[3] != computer_team):
slot[3] = computer_team
if slot[6] == user_team and (slot[4] != user_team) and (slot[4] != computer_team):
slot[4] = computer_team
else:
return
if slot[3] == user_team or slot[4] == user_team or slot[6] == user_team \
and (slot[1] != user_team) and (slot[1] != computer_team):
slot[1] = computer_team
if slot[2] == user_team and (slot[4] != user_team) and (slot[4] != computer_team):
slot[4] = computer_team
elif slot[2] == user_team and slot[4] == user_team and (slot[6] != user_team) \
and (slot[6] != computer_team):
slot[6] = computer_team
if slot[4] == user_team and (slot[5] != user_team) and (slot[5] != computer_team):
slot[5] = computer_team
elif slot[7] == user_team and slot[5] == computer_team and (slot[8] != user_team) and (slot[8] != computer_team):
slot[8] = computer_team
else:
return
else:
return
我发现一个问题是,一旦 if 语句到目前为止嵌套,它们就会停止执行(在这种情况下,最后一个 elif 插槽 [7])。我知道这段代码效率低下,但这是我知道如何做到这一点的唯一方法。(我不确定我将如何在此处使用语句或范围)。因此,如果你们中的任何人对算法有任何建议,或者如果嵌套混乱如何简化这一点,那么我很乐意听到。C:
编辑:所有插槽混乱都是指我的板,即:
def draw_board():
'''Opted to use lists so that the numbers can be replaced with either
X or O later on and so that testing whether the game is over is simpler'''
print (" " + str(slot[0]) + " | " + str(slot[1]) + " | " + str(slot[2]))
print ("-----------")
print (" " + str(slot[3]) + " | " + str(slot[4]) + " | " + str(slot[5]))
print ("-----------")
print (" " + str(slot[6]) + " | " + str(slot[7]) + " | " + str(slot[8]))
print ("\n")
user_team/computer_team 持有“X”或“O”,这取决于玩家选择使用哪一个。