I am creating a game of Tic-Tac-Toe in python and am struggling to create a module that detects if someone has won. I am passing in 2 things into the module, the Board and a set of winning combinations: win_comb=((0,1,2),(3,4,5),(6,7,8),(6,3,0),(7,4,1),(8,5,2),(6,4,2),(8,4,0))
The module in which I am using to check if someone has won. The module is called after 4 moves are made. If someone has won then it shall return a 1, yet if someone hasn't then it shall return a -1.
def Check_Results(Board,win_comb):
for each in win_comb:
try:
if (Board[each[0]] == Board[each[1]] and Board[each[1]]== Board[each[2]] and Board[each[0]]==Board[each[2]]):
return 1
else:
each=each+1
except:
pass
return -1
In your check if, you only need two checks.
Since the third equality will be implied (if a==b and b==c then a==c is implied)
Then you don't need to do each=each+1
since the for
will already loop for each winning combinations.
Finally your try/except
only prevent you from seeing that you cannot do each+1
since each is a tuple
and cannot be incremented.
def check_Results(board, win_comb):
for each in win_comb:
if (board[each[0]] == board[each[1]] and board[each[1]]== board[each[2]]):
return 1
return -1
Edit: note on naming convention, reserve CamelCase for Classed.
Also a one line solution:
return any(
(board[each[0]] == board[each[1]] and board[each[1]]== board[each[2]])
for each in win_comb)