我最近遇到了使用tic tac toe游戏功能的另一个问题。我希望这个功能做的是检查是否有任何玩家通过该功能赢得了胜利#39;。该函数适用于我的原始代码,但这需要我重写4次。我希望通过使它成为一个函数来简化它,但我似乎无法让它工作。我尝试在函数的开头添加全局变量,但似乎并非如此。
Pure\Something
干杯
答案 0 :(得分:1)
我不理解您的代码,但您可以通过从函数返回endgame来使其工作。在函数末尾添加:
def win(x):
...
#all the if/elif statements#
...
return endgame
另外我不知道为什么你要调用所有的while循环。 我建议如下:
endgame = win(player1_mark)
if endgame == True:
print "You win!"
干杯
答案 1 :(得分:1)
快速修改将如下所示(返回equal
值,删除第二个while
,并删除具有更长布尔公式的重复代码):
num1 = '1'
num2 = '2'
num3 = '3'
num4 = '4'
num5 = '5'
num6 = '6'
num7 = '7'
num8 = '8'
num9 = '9'
player1_mark = "X"
player2_mark = "O"
def drawBoard():
''' Prints the board'''
print
def win(x):
if (num1 == x and num2 == x and num3 == x) or (
num1 == x and num5 == x and num9 == x) or (
num1 == x and num4 == x and num7 == x) or (
num4 == x and num5 == x and num6 == x) or (
num7 == x and num8 == x and num9 == x) or (
num7 == x and num5 == x and num3 == x) or (
num1 == x and num2 == x and num3 == x) or (
num8 == x and num5 == x and num2 == x) or (
num9 == x and num6 == x and num3 == x) :
drawBoard()
print "The computer wins!"
return True
elif (num1 != '1' and num2 != '2' and num3 != '3' and num4 != '4' and num5 != '5' and num6 != '6' and num7 != '7' and num8 != '8' and num9 != '9'):
drawBoard()
print "Draw"
return True
else:
return False
'''Lets say that the player gets the row 1 2 and 3'''
num1 = 'X'
num2 = 'X'
num3 = 'X'
while True:
endgame = win(player1_mark)
if(endgame):
print 'You win!'
break