I have recently came across another problem with using functions for a tic tac toe game. What I want this function to do is check if any of the players have won through the function 'win'. The function works in my original code but that required me to re write it 4 times. I wanted to simplify it by making it a function but I cannot seem to get it to work. I have tried adding global variables in the beginning of the function, but that doesn't seem to be the case.
num1 = '1'
num2 = '2'
num3 = '3'
num4 = '4'
num5 = '5'
num6 = '6'
num7 = '7'
num8 = '8'
num9 = '9'
player1_mark = "X"
player2_mark = "O"
endgame = False
def drawBoard():
''' Prints the board'''
print
def win(x):
if (num1 == x and num2 == x and num3 == x):
drawBoard()
print "The computer wins!"
endgame = True
elif (num1 == x and num5 == x and num9 == x):
drawBoard()
print "The computer wins!"
endgame = True
elif (num1 == x and num4 == x and num7 == x):
drawBoard()
print "The computer wins!"
endgame = True
elif (num4 == x and num5 == x and num6 == x):
drawBoard()
print "The computer wins!"
endgame = True
elif (num7 == x and num8 == x and num9 == x):
drawBoard()
print "The computer wins!"
endgame = True
elif (num7 == x and num5 == x and num3 == x):
drawBoard()
print "The computer wins!"
endgame = True
elif (num1 == x and num2 == x and num3 == x):
drawBoard()
print "The computer wins!"
endgame = True
elif (num8 == x and num5 == x and num2 == x):
drawBoard()
print "The computer wins!"
endgame = True
elif (num9 == x and num6 == x and num3 == x):
drawBoard()
print "The computer wins!"
endgame = 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"
endgame = True
'''Lets say that the player gets the row 1 2 and 3'''
num1 = 'X'
num2 = 'X'
num3 = 'X'
while True:
win(player1_mark)
while endgame == True:
print 'You win!'
break
Cheers
(num1 == x and num2 == x and num3 == x)? I suspect it's your design, all the repetitions, that eventually makes it hard to follow the logic.