I am currently learning to create tic tac toe game using python. I need to compare the board with the list to know whether the player win or not by checking whether the board meet the win condition or not. But I don't know how to do it. Can anyone help?
board = {
1: 'X', 2: 'X', 3: 'X',
4: 'X', 5: 'O', 6: 'O',
7: 'O', 8: 'X', 9: 'O'
}
winCombinations = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[1, 5, 9],
[3, 5, 7],
[1, 4, 7],
[2, 5, 8],
[3, 6, 9]
]
CodePudding user response:
If you note 'X' as 0
and 'O' as 1
, the board can be represented as a 9-bit number, for example, for your board:
board = {
1: 'X', 2: 'X', 3: 'X',
4: 'X', 5: 'O', 6: 'O',
7: 'O', 8: 'X', 9: 'O'
}
is equivalent to:
board = 0b000011101 # 29
In a similar manner, the winning combinations can also be represented as 9-bit number:
winCombinations = np.array([
0b111000000, # 448
0b000111000, # 56
0b000000111, # 7
0b100010001, # 273
0b001010100, # 84
0b100100100, # 292
0b010010010, # 146
0b001001001 # 73
])
Using this method, you can check if a board has a winning combination via bitwise operation:
if np.any(board & winCombinations == winCombinations):
print('O won')
elif np.any(~c & winCombinations == winCombinations):
print('X won')
else:
print('Draw')
In case you want to be able to check non-complete boards as well, you can use 18 bits to describe a board (first 9 bits for 'X' and other 9 bits for 'O'). Using this method, the board representation will be:
board = 0b111100010000011101 # 246813
Then the checking will be:
if np.any(board & winCombinations == winCombinations):
print('O won')
elif np.any(board >> 9 & winCombinations == winCombinations):
print('X won')
else:
print('No winner')
CodePudding user response:
A very pythonic way to state the condition when a player wins with like this
def isWinner(board, player):
return any(
all(board[cell] == player for cell in line)
for line in winCombinations)
Then you use it like this
isWinner(board, 'O'), isWinner(board, 'X')
CodePudding user response:
I don't want to give you the exact answer because you probably want to learn it yourself. So I'll just give you an easy way to solve it !
You should iterate thought your winning combinations (assuming you gathered all the possible winning combinations) and for each winning combination : check if the 3 cell belong to the SAME player ! If they do, you know that this player won !
But be careful, you need to handle empty cells ! Because you don't want your function to return a winner because, for a given winning combinaison, your 3 cells are empty.
CodePudding user response:
This function should do it:
def winner(board, winning_combinations):
for combination in winning_combinations:
if board[combination[0]] == board[combination[1]] == board[combination[2]]:
return board[combination[0]]
return None
With your inputs it returns 'X'