#include #include #ifdef _WIN32 #include #endif using namespace std; const int N = 3; struct userInput { bool ok; int zeile; int spalte; }; struct gameState { bool running = true; char winner = ' '; char board[N][N]; int filledCells = 0; // Per-player (0=X, 1=O) counters for rows, cols, and both diagonals. // Win-check is O(1): increment on each move, compare to N. int rowCount[2][N] = {}; int colCount[2][N] = {}; int diagCount[2] = {}; int antiDiagCount[2] = {}; }; void render(const gameState &state) { #ifdef _WIN32 system("cls"); #endif #ifdef linux system("clear"); #endif cout << " | "; for (int j = 0; j < N; j++) cout << j + 1 << " | "; cout << endl; for (int i = 0; i < N * 4 + 3; i++) cout << "-"; cout << endl; for (int i = 0; i < N; i++) { cout << i + 1 << " | "; for (int j = 0; j < N; j++) cout << state.board[i][j] << " | "; cout << endl; for (int k = 0; k < N * 4 + 3; k++) cout << "-"; cout << endl; } } userInput getUserInput(const gameState &state) { while (true) { int inputZeile, inputSpalte; cout << "Zeile: "; cin >> inputZeile; cout << "Spalte: "; cin >> inputSpalte; cout << endl; if (!cin) { cin.clear(); cin.ignore(1000, '\n'); cout << "Ungueltige Eingabe, bitte nochmal." << endl; continue; } if (inputZeile >= 1 && inputZeile <= N && inputSpalte >= 1 && inputSpalte <= N && state.board[inputZeile - 1][inputSpalte - 1] == ' ') { return {true, inputZeile - 1, inputSpalte - 1}; } cout << "Feld bereits belegt oder ausserhalb des Spielfelds." << endl; } } void checkforWin(gameState &state, int zeile, int spalte, char player) { int p = (player == 'X') ? 0 : 1; state.rowCount[p][zeile]++; state.colCount[p][spalte]++; if (zeile == spalte) state.diagCount[p]++; if (zeile + spalte == N - 1) state.antiDiagCount[p]++; if (state.rowCount[p][zeile] == N || state.colCount[p][spalte] == N || state.diagCount[p] == N || state.antiDiagCount[p] == N) { state.running = false; state.winner = player; return; } if (state.filledCells >= N * N) { state.running = false; state.winner = '-'; } } int main() { #ifdef _WIN32 SetConsoleOutputCP(CP_UTF8); #endif gameState state; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) state.board[i][j] = ' '; int counter = 1; while (state.running) { render(state); char current_player = counter++ % 2 == 1 ? 'X' : 'O'; cout << endl << "Am Zug ist Spieler: " << current_player << endl; auto [ok, zeile, spalte] = getUserInput(state); if (ok) { state.board[zeile][spalte] = current_player; state.filledCells++; checkforWin(state, zeile, spalte, current_player); } } render(state); if (state.winner == '-') { cout << endl << "Unentschieden!" << endl; } else { cout << endl << "Der Gewinner ist: " << state.winner << endl; } #ifdef _WIN32 system("pause"); #endif return 0; }