In python, my current code works to a certain point. I have another function called check_X_win_status()
which does the same thing that the one below does, except it checks for 1, instead of -1. Anyone have any ideas as to how to make this more compact? Also, I sometimes get an error in which the code prints "win" even if the game_status = -1, 1,-1, 0, 0, 0, 0, 0, 0
game_status = [-1,-1,-1,0,0,0,0,0,0]
def check_O_win_status():
if game_status[0] and game_status[1] and game_status[2] == -1:
print("O wins!")
if game_status[3] and game_status[4] and game_status[5] == -1:
print("O wins!")
if game_status[6] and game_status[7] and game_status[8] == -1:
print("O wins!")
if game_status[0] and game_status[3] and game_status[6] == -1:
print("O wins!")
if game_status[1] and game_status[4] and game_status[7] == -1:
print("O wins!")
if game_status[2] and game_status[5] and game_status[8] == -1:
print("O wins!")
if game_status[0] and game_status[4] and game_status[8] == -1:
print("O wins!")
if game_status[2] and game_status[4] and game_status[6] == -1:
print("O wins!")
You could simplify this a bit by preparing a list of winning patterns expressed as tuples of indexes. Then, for each pattern, use all() to check if all 3 indexes have a -1 in the game_status:
def check_O_win_status():
winPatterns = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(0,4,8),(2,4,6)]
if any(all(game_status[i]==-1 for i in patrn) for patrn in winPatterns):
print("O wins")
In Python, A and B and C == -1
doesn't test that all 3 variables are equal to -1. It will use the first two variables as booleans, extracting their Truthy value as if you had done (A == True) and (B == True) and (C==-1)
.
To test that all 3 variables are -1, you can express the condition like this: A == B == C == -1
.