EMPTY = 0 PL1 = 1 PL2 = 2 tafel = [ [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], ] COLUMNS = 3 ROWS = 3 def print_tafel(board): symbols = ("*", "X", "O") for zeile in board: for c in zeile: print(f"{symbols[c]} ",end="") print() def input_ok(tafel, r, c): is_in_tafel = (ROWS > r >=0) and (COLUMNS > c >= 0) if is_in_tafel: beleg = tafel[r][c] return beleg == EMPTY else: return False def user_input(user,tafel): print(f"Spieler {user} ist dran") print("Geben Sie die Zeile und Spalten ein") user_input_ok = False while not user_input_ok: r = int(input("Zeile: ")) - 1 c = int(input("Spalte: ")) - 1 user_input_ok = input_ok(tafel, r, c) if user_input_ok: tafel[r][c] = user else: print("Eingabe nicht in Ordnung") def pruefe_combination(p, board): r = p[0] c = p[1] combination = p[2] player = board[r][c] if combination == "hvd": h = (board[r][0] == player) and (board[r][1] == player) and (board[r][2] == player) v = (board[0][c] == player) and (board[1][c] == player) and (board[2][c] == player) d = (board[0][0] == player) and (board[1][1] == player) and (board[2][2] == player) return h or v or d elif combination == "v": return (board[0][c] == player) and (board[1][c] == player) and (board[2][c] == player) elif combination == "vd": v = (board[0][c] == player) and (board[1][c] == player) and (board[2][c] == player) d = (board[0][0] == player) and (board[1][1] == player) and (board[2][2] == player) return v or d elif combination == "h": return (board[r][0] == player) and (board[r][1] == player) and (board[r][2] == player) else: raise Error(f"combination {combination} ungültig" ) def has_spieler_gewonnen(player, board): position = [ (0,0, "hvd"), (0,1, "v"), (0,2,"vd"), (1,0, "h"), (2,0,"h") ] for p in position: r = p[0] c = p[1] print(p, player) if board[r][c] == player: return pruefe_combination(p, board) else: return False def spiel_bewerten(tafel): """ return: Ein Tupel 1. Element: True = Spiel beendet False = Spiel geht weiter 2. Element: 0 = unentschieden 1 = 1. Spieler gewonnen 2 = 2. Spieler gewonnen """ if has_spieler_gewonnen(PL1, tafel): return (True, PL1) elif has_spieler_gewonnen(PL2, tafel): return (True, PL2) empty_cells = ROWS * COLUMNS for row in tafel: for colum in row: if colum != EMPTY: empty_cells = empty_cells - 1 return (empty_cells == 0, 0) if __name__ == "__main__": print_tafel(tafel) aktuelle_spieler = 1 (spiel_ende, gewinner) = (False, 0) while not spiel_ende : user_input(aktuelle_spieler, tafel) print_tafel(tafel) (spiel_ende, gewinner) = spiel_bewerten(tafel) if aktuelle_spieler == 1: aktuelle_spieler = 2 else: aktuelle_spieler = 1 print("Spiel beendet!") print(f"Gewinner ist {gewinner}")