Files
tictactoe/main.cpp

93 lines
2.1 KiB
C++

#include <iostream>
#include <windows.h>
#include <iomanip>
#include <vector>
using namespace std;
string spielfeld[3][3] = {
{" ", " ", " "},
{" ", " ", " "},
{" ", " ", " "}
};
struct userInput {
bool ok;
int zeile;
int spalte;
};
struct gameState {
bool running = true;
char winner;
};
void render() {
system("cls");
cout << " | 1 | 2 | 3 |" << endl;
cout << "---------------" << endl;
for (int i = 0; i < 3; i++) {
cout << i+1 << " | ";
for (int j = 0; j < 3; j++) {
cout << spielfeld[i][j] << " | ";
}
cout << endl;
cout << "---------------" << endl;
}
}
userInput getUserInput() {
int inputSpalte, inputZeile;
cout << "Zeile: ";
cin >> inputZeile;
cout << "Spalte: ";
cin >> inputSpalte;
cout << endl;
if (spielfeld[inputZeile-1][inputSpalte-1] == " ") {
return {true, inputZeile-1, inputSpalte-1};
} else {
cout << endl << "Input konnte nicht gelesen werden" << endl;
return getUserInput();
}
}
void checkforWin(gameState &state) {
// TODO: implement a proper efficent check that doesnt end when every tile is filled
// we simulate for debugging purposes that once every field in the spielfeld array is filled, the game ends
int counter = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (spielfeld[i][j] != " ") {
counter++;
}
}
}
if (counter == 9) {
state.running = false;
render();
return;
}
}
int main() {
SetConsoleOutputCP(CP_UTF8);
cout << fixed << setprecision(2);
gameState state;
int counter = 1;
while (state.running) {
render();
string current_player = counter++ % 2 == 1 ? "X" : "O";
cout << endl << "Am Zug ist Spieler: " << current_player << endl;
if (auto [ok, zeile, spalte] = getUserInput(); ok) {
spielfeld[zeile][spalte] = current_player;
}
checkforWin(state);
}
system("pause");
return 0;
}