From 833f9fb10b7d465c9c14a8c2d695bf8bec755025 Mon Sep 17 00:00:00 2001 From: Lukas Hoffleit <lukas.hoffleit03@gmail.com> Date: Sat, 12 Apr 2025 12:20:12 +0200 Subject: [PATCH] self.grid ist jetzt ein np.array; check_winner --- tictactoe.py | 43 +++++++++++++++++++++++++++++++++++-------- 1 file changed, 35 insertions(+), 8 deletions(-) diff --git a/tictactoe.py b/tictactoe.py index 60d82b3..fa51cab 100644 --- a/tictactoe.py +++ b/tictactoe.py @@ -1,4 +1,6 @@ from enum import Enum +import numpy as np +import numpy.typing as npt class Player(Enum): undefined = 0 @@ -10,9 +12,10 @@ class TicTacToeError(Exception): class TicTacToe(): def __init__(self) -> None: - self.grid = [] - for i in range(3): - self.grid.append([Player.undefined, Player.undefined, Player.undefined]) + grid = [] + for _ in range(3): + grid.append([Player.undefined, Player.undefined, Player.undefined]) + self.grid = np.array(grid) def _get_player_from_int(self, player:Player|int) -> Player: if isinstance(player, int): @@ -55,17 +58,41 @@ class TicTacToe(): print(f" {symbols[field]} │", end="") if i < len(self.grid) - 1: print("\n├───┼───┼───┤") - print("\n└───┴───┴───┘\n") + print("\n└───┴───┴───┘\n\n") - def get_best_move(self, player:Player|int) -> tuple[int, int]: - return (0, 0) + def check_winner(self) -> Player: + """ 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__": 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.add(1, 2, Player.two) + print(ttt.check_winner()) + ttt.add(1, 0, Player.one) ttt.print_grid() + print(ttt.check_winner()) -- GitLab