好吧,所以我正在编写一个tic tac toe游戏,并且遇到了一个我似乎无法解决的非常糟糕的错误。我已经创建了一个函数,如果玩家即将获胜,计算机将阻止玩家,但是,如果成功阻止一次,即使条件满足,它也不会再触发。该函数的代码是:
def block():
for t in range(0, 9, 3):
if slot[t] == user_team and slot[t+1] == user_team and (slot[t+2] \
!= user_team) and (slot[t+2] != computer_team):
slot[int(t+2)] = computer_team
return
elif slot[t+1] == user_team and slot[t+2] == user_team and (slot[t] \
!= user_team) and (slot[t] != computer_team):
slot[int(t)] = computer_team
return
elif slot[t] == user_team and slot[t+2] == user_team and (slot[t+1] \
!= user_team) and (slot[t+1] != computer_team):
slot[int(t+1)] = computer_team
return
for t in range(3):
if slot[t] == user_team and slot[t+3] == user_team and (slot[t + 6] \
!= user_team) and (slot[t+6] != computer_team):
slot[int(t+6)] = computer_team
return
elif slot[t+3] == user_team and slot[t+6] == user_team and (slot[t] \
!= user_team) and (slot[t] != computer_team):
slot[int(t)] = computer_team
return
elif slot[t] == user_team and slot[t+6] == user_team and (slot[t+3] \
!= user_team) and (slot[t+3] != computer_team):
slot[int(t+3)] = computer_team
此外,user_team和computer_team会返回该播放器是X还是O,而slot[int()] = computer_team
用于将移动放置在电路板上。
下面是调用函数的地方(以防我搞砸了。):
else:
draw_board()
'''win()'''
block()
cmove()
turn = "user"
if end_game() == True:
computer_win += 1
draw_board()
print ("The computer has won! But... We already knew that would happen. (:")
playing = False
elif end_game() == "Tie":
tie_win += 1
draw_board()
print ("The game is a tie. You're going to have to try harder " \
+ "\n" + "if you wish to beat the computer!" + "\n")
playing = False
else:
pass
如果你们中的任何一个人能告诉我哪里出错了,那么那将是我的一天。 C:
Board(打印是缩进的,它只是不想在这里。)
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")
新错误:
这是我进入第4步后的我的董事会
计算机主板移动4(两次移动,并替换x)
答案 0 :(得分:2)
我相信您的问题符合block
函数的逻辑。
这是你的董事会:
0 1 2
3 4 5
6 7 8
遍历第一对嵌套for
循环,让我们看看你的代码做了什么:
for t in range(0,9,3):
for y in range(1, 9, 3):
这将为您提供以下t, y
对:(0,1),(0,4),(0,7),(3,1),(3,4),(3, 7),(6,1),(6,4)和(6,7)。马上,我认为这不是你想要的。据我所知,你试图检查玩家是否连续两个标记。
这个问题很容易解决 - 您不需要两个for
循环。相反,只需使用t
,t+1
和t+2
即可。
接下来,考虑一行:
0 1 2
要检查三个条件,玩家的标记为0和1,标记为0和2,或者标记为1和2.您只检查其中两个条件 - 0和1,以及1和2。
此外,if
语句没有按照您的想法执行:
if ... and slot[y+1] != user_team and computer_team:
这相当于:
if ... and (slot[y+1] != user_team) and computer_team:
我认为computer_team
是'x'
或'o'
,在这种情况下,python会在True
语句中使用它与if
相同。你想要的是这个:
if ... and (slot[y+1] != user_team) and (slot[y+1] != computer_team):
这也可能是您的代码只能运行一次的原因 - 下次评估之前找到的同一行或列时,if
语句将再次评估为True
,并且将再次设置相同的空间,看起来好像什么也没做。
检查列的代码具有相同的问题。希望我已经指出的问题足以让您弄清楚如何修复代码。祝你好运!