init and work on implementation

This commit is contained in:
Leon Vatthauer 2024-11-27 17:10:19 +01:00
commit 0ba6fe5be7
Signed by: leonv
SSH key fingerprint: SHA256:G4+ddwoZmhLPRB1agvXzZMXIzkVJ36dUYZXf5NxT+u8
3 changed files with 144 additions and 0 deletions

5
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,5 @@
{
"files.associations": {
"iostream": "cpp"
}
}

BIN
a.out Executable file

Binary file not shown.

139
ttt.cc Normal file
View file

@ -0,0 +1,139 @@
#include <iostream>
#include <string>
using namespace std;
const int ROWS = 3;
const int COLUMNS = 3;
/* Grid representing the tic-tac-toe field.
0 is empty,
1 is human,
-1 is computer.
*/
int grid[COLUMNS][ROWS];
void printGrid() {
for (int y = 0; y < ROWS; y++) {
for (int x = 0; x < 2 * COLUMNS + 1; x++) {
cout << '-';
}
cout << endl;
for (int x = 0; x < COLUMNS; x++) {
if (x == 0) {
cout << '|';
}
if (grid[x][y] > 0) {
cout << 'X';
} else if (grid [x][y] < 0) {
cout << 'O';
} else {
cout << ' ';
}
cout << '|';
}
cout << endl;
if (y == COLUMNS - 1) {
for (int x = 0; x < 2 * COLUMNS + 1; x++) {
cout << '-';
}
cout << endl;
}
}
}
bool parse_move(string move, int &x, int &y) {
// split string on comma
string x_str;
string y_str;
int pos = move.find(',');
// error if no comma found
if (pos == string::npos) {
return false;
}
// split on ','
x_str = move.substr(0, pos);
y_str = move.substr(pos + 1, move.length() - 1 - pos);
// convert to int
int x_local = stoi(x_str);
int y_local = stoi(y_str);
// check conversion and return expected result
if (x_local != -1 && y_local != -1) {
x = x_local;
y = y_local;
return true;
}
return false;
}
void player_move() {
string move;
int x;
int y;
while (true) {
cout << "Enter a valid move. (Format is 'x,y')" << endl;
cin >> move;
if (!parse_move(move, x, y)) {
cout << "Couldn't parse move." << endl;
continue;
}
if (x < 0 || y < 0 || x >= COLUMNS || y >= ROWS) {
cout << "Coordinates out of bounds." << endl;
continue;
}
break;
}
grid[x][y] = '1';
}
void computer_move() {
}
bool game_over() {
return false;
}
/* Play one game of tic tac toe,
/* returns 0 if the player won and 1 if the computer won.
*/
int play_game() {
// Query for starting player
int startPlayer = -1;
while (startPlayer != 0 && startPlayer != 1) {
cout << "Which player should start? (0 - You, 1 - Program)";
cin >> startPlayer;
}
// Do move according to startPlayer
if (startPlayer == 1) {
computer_move();
}
while(true) {
player_move();
if (game_over()) break;
computer_move();
if (game_over()) break;
}
return 0;
}
int main(int argc, char *argv[]) {
cout << "Hello world" << endl;
for (int y = 0; y < ROWS; y++) {
for (int x = 0; x < COLUMNS; x++) {
grid[x][y] = 1;
}
}
printGrid();
player_move();
}