Skip to content

game.cpp #685

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

game.cpp #685

wants to merge 1 commit into from

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