#include <iostream>
#include <limits>
const char PLAYER_ONE = 'X';
const char PLAYER_TWO = 'O';
const char EMPTY = '-';
void drawBoard(const int fieldSize, char** board) {
for (int i = 0; i < fieldSize; ++i) {
for (int j = 0; j < fieldSize; ++j) {
std::cout << board[i][j] << ' ';
}
std::cout << std::endl;
}
}
bool checkWin(const int fieldSize, char** board, char player) {
for (int i = 0; i < fieldSize; ++i) {
bool rowWin = true;
bool colWin = true;
for (int j = 0; j < fieldSize; ++j) {
rowWin &= (board[i][j] == player);
colWin &= (board[j][i] == player);
}
if (rowWin || colWin) {
return true;
}
}
bool diagonalWin = true;
bool reverseDiagonalWin = true;
for (int i = 0; i < fieldSize; ++i) {
diagonalWin &= (board[i][i] == player);
reverseDiagonalWin &= (board[i][fieldSize - i - 1] == player);
}
return diagonalWin || reverseDiagonalWin;
}
int main() {
int fieldSize;
std::cout << "Enter the field size: ";
if (!(std::cin >> fieldSize)) {
std::cout << "Error. Field size can only be set as a number" << std::endl;
return 1;
}
char** board = new char*[fieldSize];
for (int i = 0; i < fieldSize; ++i) {
board[i] = new char[fieldSize];
for (int j = 0; j < fieldSize; ++j) {
board[i][j] = EMPTY;
}
}
bool playerOneTurn = true;
int moves = fieldSize * fieldSize;
while (moves > 0) {
drawBoard(fieldSize, board);
int row, col;
std::cout << "Player " << (playerOneTurn ? "1" : "2") << ", enter your move (row, col): ";
std::cin >> row >> col;
row -= 1; // subtract 1 from row
col -= 1; // subtract 1 from column
while (std::cin.fail() || row < 0 || row >= fieldSize || col < 0 || col >= fieldSize || board[row][col] != EMPTY) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid input. Please enter a valid move (row, col): ";
std::cin >> row >> col;
row -= 1; // subtract 1 from row
col -= 1; // subtract 1 from column
}
// Fix the bug here:
board[row][col] = playerOneTurn ? PLAYER_ONE : PLAYER_TWO;
if (checkWin(fieldSize, board, playerOneTurn ? PLAYER_ONE : PLAYER_TWO)) {
drawBoard(fieldSize, board);
std::cout << "Player " << (playerOneTurn ? "1" : "2") << " wins!" << std::endl;
break;
}
playerOneTurn = !playerOneTurn;
--moves;
}
if (moves == 0) {
drawBoard(fieldSize, board);
std::cout << "It's a draw!" << std::endl;
}
for (int i = 0; i < fieldSize; ++i) {
delete[] board[i];
}
delete[] board;
return 0;
}