Skip to content
Snippets Groups Projects
Commit 309edd39 authored by Lukas Hoffleit's avatar Lukas Hoffleit
Browse files

check winner mit optionalem spielbrett

parent 833f9fb1
No related branches found
No related tags found
No related merge requests found
from enum import Enum
import numpy as np
import numpy.typing as npt
class Player(Enum):
undefined = 0
......@@ -60,39 +59,45 @@ class TicTacToe():
print("\n├───┼───┼───┤")
print("\n└───┴───┴───┘\n\n")
def check_winner(self) -> Player:
def check_winner(self, grid:np.ndarray|None = None) -> Player:
""" Checks, if the game is won.
If the game is won by a player, returns this player.
Else, returns Player.undefined """
if grid is None:
grid = self.grid
# Vertical line
for row in self.grid:
for row in grid:
if (row[0] == row[1] == row[2] and row[0] != Player.undefined):
return row[0]
# Horizontal line
for i in range(len(self.grid)):
col = self.grid[:, i]
for i in range(len(grid)):
col = grid[:, i]
if (col[0] == col[1] == col[2] and col[0] != Player.undefined):
return col[0]
# Diagonal line
if (self.grid[0, 0] == self.grid[1, 1] == self.grid[2, 2]
or self.grid[0, 2] == self.grid[1, 1] == self.grid[2, 0]):
if self.grid[1, 1] != Player.undefined:
return self.grid[1, 1]
if (grid[0, 0] == grid[1, 1] == grid[2, 2]
or grid[0, 2] == grid[1, 1] == grid[2, 0]):
if grid[1, 1] != Player.undefined:
return grid[1, 1]
# Base Case - No winner
return Player.undefined
def is_won(self, player:Player|int) -> bool:
player = self._get_player_from_int(player)
return self.check_winner() == player
if __name__ == "__main__":
ttt = TicTacToe()
ttt.add(0, 2, Player.two)
ttt.add(1, 1, 1)
ttt.print_grid()
ttt.add(0, 1, 2)
ttt.print_grid()
print(ttt.check_winner())
ttt.add(1, 2, Player.one)
ttt.add(0, 0, 1)
ttt.print_grid()
print(ttt.check_winner())
ttt.add(1, 0, Player.one)
ttt.add(0, 2, 2)
ttt.print_grid()
print(ttt.check_winner())
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment