From 410ad8911b9674d4100c1504aec0158cdd8e844a Mon Sep 17 00:00:00 2001 From: Lukas Hoffleit <lukas.hoffleit03@gmail.com> Date: Fri, 11 Apr 2025 09:56:22 +0200 Subject: [PATCH] Typehints vergessen --- tictactoe.py | 58 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 55 insertions(+), 3 deletions(-) diff --git a/tictactoe.py b/tictactoe.py index 4b849cf..ea276da 100644 --- a/tictactoe.py +++ b/tictactoe.py @@ -1,6 +1,58 @@ +from enum import Enum + +class Player(Enum): + one = 1 + two = 2 + undefined = 3 + class TicTacToe(): def __init__(self) -> None: - pass + self.grid = [] + for i in range(3): + self.grid.append([Player.undefined, Player.undefined, Player.undefined]) + + def add(self, row:int, col:int, player:Player|int) -> bool: + """ Change the value of a undefined field. + The player can be passed as Player Object or plain Int. + Returns True, if executed correctly. + Returns False, if the field is already occupied + or the player number is invalid. + """ + if isinstance(player, int): + try: player = Player(player) + except ValueError: return False # invalid player number + + if self.check_field(row, col): + self.grid[row][col] = player + return True + return False + + def check_field(self, row:int, col:int) -> bool: + """Checks, if a field is occupied""" + if self.grid[row][col] != Player.undefined: + return False + return True + + def print_grid(self) -> None: + symbols = { + Player.one: "X", + Player.two: "O", + Player.undefined: " " + } + + print("┌───┬───┬───┐") + for i, row in enumerate(self.grid): + print("│", end="") + for field in row: + print(f" {symbols[field]} │", end="") + if i < len(self.grid) - 1: + print("\n├───┼───┼───┤") + print("\n└───┴───┴───┘\n") + - def calc_best_move(self) -> None: - pass +if __name__ == "__main__": + ttt = TicTacToe() + ttt.add(1, 1, 1) + ttt.print_grid() + ttt.add(1, 2, Player.two) + ttt.print_grid() -- GitLab