Skip to content

game.cpp#685

Open
Hamdialkohlani wants to merge 1 commit inton3d1117:mainfrom
Hamdialkohlani:patch-1
Open

game.cpp#685
Hamdialkohlani wants to merge 1 commit inton3d1117:mainfrom
Hamdialkohlani:patch-1

Conversation

@Hamdialkohlani
Copy link

// game.cpp
#include "game.hpp"

TicTacToe::TicTacToe() {
board = std::vector(9, ' ');
currentPlayer = 'X';
}

void TicTacToe::displayBoard() {
std::cout << "\n";
for (int i = 0; i < 9; i++) {
std::cout << " " << (board[i] == ' ' ? std::to_string(i + 1) : std::string(1, board[i])) << " ";
if (i % 3 != 2) std::cout << "|";
if (i % 3 == 2 && i != 8) std::cout << "\n---+---+---\n";
}
std::cout << "\n\n";
}

bool TicTacToe::makeMove(int position) {
if (position < 1 || position > 9 || board[position - 1] != ' ') {
return false;
}
board[position - 1] = currentPlayer;
return true;
}

bool TicTacToe::checkWin() {
const int wins[8][3] = {
{0,1,2}, {3,4,5}, {6,7,8}, // rows
{0,3,6}, {1,4,7}, {2,5,8}, // columns
{0,4,8}, {2,4,6} // diagonals
};

for (auto& w : wins) {
    if (board[w[0]] == currentPlayer && board[w[1]] == currentPlayer && board[w[2]] == currentPlayer) {
        return true;
    }
}
return false;

}

bool TicTacToe::checkDraw() {
for (char c : board) {
if (c == ' ') return false;
}
return true;
}

void TicTacToe::switchPlayer() {
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}

char TicTacToe::getCurrentPlayer() {
return currentPlayer;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant