107 lines
2.0 KiB
C++
107 lines
2.0 KiB
C++
#include "game.h"
|
|
#include <Log.h>
|
|
|
|
const std::string Game::SYM_NAMES[3] = {"NONE", "X", "O"};
|
|
|
|
Game::Game() {
|
|
for(uint_fast8_t i = 0; i < SIZE * SIZE; ++i) {
|
|
field[i] = SYM::NONE;
|
|
}
|
|
}
|
|
|
|
void Game::setMessageID(uint32_t messageid) {
|
|
this->messageid = messageid;
|
|
}
|
|
|
|
|
|
void Game::setPlayerA(uint64_t player) {
|
|
playerA = player;
|
|
}
|
|
void Game::setPlayerB(uint64_t player) {
|
|
playerB = player;
|
|
}
|
|
|
|
bool Game::addPlayer(uint64_t player) {
|
|
if(!playerA) {
|
|
playerA = player;
|
|
return true;
|
|
}
|
|
|
|
if(!playerB && playerA != player) {
|
|
playerB = player;
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
uint64_t Game::getPlayerA() const {
|
|
return playerA;
|
|
}
|
|
|
|
uint64_t Game::getPlayerB() const {
|
|
return playerB;
|
|
}
|
|
|
|
bool Game::ready() const {
|
|
return playerA != 0 && playerB != 0 && !done();
|
|
}
|
|
|
|
bool Game::done() const {
|
|
return checkWinner() != SYM::NONE;
|
|
}
|
|
|
|
bool Game::turn(uint_fast8_t x, uint_fast8_t y, uint64_t player) {
|
|
if(!isInField(x, y)) return false;
|
|
if(!ready()) return false;
|
|
|
|
// playerA
|
|
if(player == playerA && nextturna) {
|
|
SYM s = getField(x, y);
|
|
if(s != SYM::NONE) {
|
|
return false;
|
|
}
|
|
setField(x, y, SYM::A);
|
|
}
|
|
|
|
//playerB
|
|
else if(player == playerB && !nextturna) {
|
|
SYM s = getField(x, y);
|
|
if(s != SYM::NONE) {
|
|
return false;
|
|
}
|
|
setField(x, y, SYM::B);
|
|
}
|
|
|
|
// other user -> not allowed
|
|
else return false;
|
|
|
|
nextturna = !nextturna;
|
|
return true;
|
|
}
|
|
|
|
const std::string& Game::getWinner() const {
|
|
Game::SYM winner = checkWinner();
|
|
if(winner == SYM::NONE) {
|
|
static const std::string EMPTY = "";
|
|
return EMPTY;
|
|
}
|
|
return SYM_NAMES[(int) winner];
|
|
}
|
|
|
|
Game::SYM Game::getPos(uint_fast8_t x, uint_fast8_t y) const {
|
|
return getField(x, y);
|
|
}
|
|
|
|
Game::SYM Game::checkWinner() const {
|
|
for(uint_fast8_t i = 0; i < SIZE; ++i) {
|
|
if(field[0 + i * SIZE] == field[1 + i * SIZE] && field[1 + i * SIZE] == field[2 + i * SIZE]) {
|
|
// spalte gleich
|
|
return field[0 + i * SIZE];
|
|
}
|
|
if (field[i + 0 * SIZE] == field[i + 1 * SIZE] && field[i + 1 * SIZE] == field[i + 2 * SIZE]) {
|
|
// zeile gleich
|
|
return field[i + 0 * SIZE];
|
|
}
|
|
}
|
|
return SYM::NONE;
|
|
} |