【发布时间】:2013-10-04 21:03:04
【问题描述】:
好的,所以我正在编写一个井字游戏,并且遇到了一个我似乎无法解决的非常糟糕的错误。我创建了一个功能,如果玩家即将获胜,计算机将阻止玩家,但是,如果成功阻止一次,即使条件满足也不会再触发。该函数的代码是:
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 步后的棋盘
X | ○ | X
O | 4 | 5
X | 7 | X
第4步后电脑的棋盘(两步,替换一个x)
X | ○ | X
O | 4 |哦
O | 7 | X
【问题讨论】:
-
这里的错误是什么?请务必包含完整的回溯。
-
请注意,将
else:套件与if:一起使用从来不是必需;else: pass语句可以安全删除。 -
没有真正的跟踪簿,因为它不会产生一个实际的“错误”。发生的情况是,在计算机阻塞一次之后,程序似乎只是跳过了 block() 函数。 (如果条件满足,则不会做出阻止玩家获胜的动作)
-
我没有看到任何可能或可能无法在代码中的任何位置调用
block()的条件。 -
我也没有,这就是我感到困惑的原因。 :O 你想看看完整的源代码吗?