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

self.grid ist jetzt ein np.array; check_winner

parent cb8e7cc9
Branches
No related tags found
No related merge requests found
from enum import Enum from enum import Enum
import numpy as np
import numpy.typing as npt
class Player(Enum): class Player(Enum):
undefined = 0 undefined = 0
...@@ -10,9 +12,10 @@ class TicTacToeError(Exception): ...@@ -10,9 +12,10 @@ class TicTacToeError(Exception):
class TicTacToe(): class TicTacToe():
def __init__(self) -> None: def __init__(self) -> None:
self.grid = [] grid = []
for i in range(3): for _ in range(3):
self.grid.append([Player.undefined, Player.undefined, Player.undefined]) grid.append([Player.undefined, Player.undefined, Player.undefined])
self.grid = np.array(grid)
def _get_player_from_int(self, player:Player|int) -> Player: def _get_player_from_int(self, player:Player|int) -> Player:
if isinstance(player, int): if isinstance(player, int):
...@@ -55,17 +58,41 @@ class TicTacToe(): ...@@ -55,17 +58,41 @@ class TicTacToe():
print(f" {symbols[field]}", end="") print(f" {symbols[field]}", end="")
if i < len(self.grid) - 1: if i < len(self.grid) - 1:
print("\n├───┼───┼───┤") print("\n├───┼───┼───┤")
print("\n└───┴───┴───┘\n") print("\n└───┴───┴───┘\n\n")
def get_best_move(self, player:Player|int) -> tuple[int, int]: def check_winner(self) -> Player:
return (0, 0) """ Checks, if the game is won.
If the game is won by a player, returns this player.
Else, returns Player.undefined """
# Vertical line
for row in self.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]
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]
# Base Case - No winner
return Player.undefined
if __name__ == "__main__": if __name__ == "__main__":
ttt = TicTacToe() ttt = TicTacToe()
ttt.add(1, 1, 1) ttt.add(0, 2, Player.two)
ttt.print_grid()
print(ttt.check_winner())
ttt.add(1, 2, Player.one)
ttt.print_grid() ttt.print_grid()
ttt.add(1, 2, Player.two) print(ttt.check_winner())
ttt.add(1, 0, Player.one)
ttt.print_grid() 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