In python, my current code works to a certain point. I have another function called def 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!")
CodePudding user response:
Firstly and does not work that way, 1 and -1 == -1
will return true
when it's false
, you need to check each element ie: 1 == -1 and -1 == -1
Secondly why use two functions you can just pass a argument through the function and then compare. ei:
def check_win_status(num):
if game_status[0] == num and game_status[1] == num and game_status[2] == num:
elif game_status[3] == num and game_status[4] == num and game_status[5] == num:
#rest of your code here
additionally use elif to check the next elements rather than if, this will eliminate cases where the input triggers multiple ifs and it starts printing multiple times like shown above
CodePudding user response:
You could simplify this a bit by preparing a list of winning patterns expressed as tuples of indexes. Then use all() to check if all 3 indexes have a -1 at 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[p]==-1 for p 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
.