-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgameManager.cpp
More file actions
93 lines (84 loc) · 2.48 KB
/
Copy pathgameManager.cpp
File metadata and controls
93 lines (84 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include "gameManager.h"
const int PLAYER_INDEX = 64;
gameManager::gameManager(const std::string& str) : _board(str.substr(0, 64)), _curr(str[PLAYER_INDEX] == 0)
{
}
gameManager::~gameManager()
{
}
std::string gameManager::boardState()
{
return _board.getMatrixStr();
}
int gameManager::makeTurn(std::string move)
{
Position* src;
Position* dst;
// Checking if the 2 positions exist on the board
try
{
src = new Position(move[0], move[1] - '0');
dst = new Position(move[2], move[3] - '0');
}
catch (std::invalid_argument invalid_index)
{
return 5;
}
if (src == dst)
return 7;
Piece* toMove = _board[*src];
Player* currentPlayer = _board.getPlayer(_curr);
Player* opponentPlayer = _board.getPlayer(!_curr);
// Checking if the source position is null or has a piece that belongs to the current player.
if (toMove == nullptr || _curr != toMove->isWhite())
return 2;
// Checking if the destination has piece, which belongs to the current player.
if (_board[dst->translate()] != nullptr && !(toMove->isEnemy(*_board[dst->translate()])))
return 3;
// First, if the king is the piece to be moved - It cannot move to a location that will cause Check on itself.
if (tolower(toMove->getType()) == 'k')
{
// The king cannot cause Check on the other king, since it would put him in attack range from the opponent's king.
if (!toMove->checkMove(*dst))
return 6;
// Attempting to move the king. If move causes check, reverse the move.
Piece* tmp = _board.extractPiece(*dst);
_board.move(*src, *dst);
bool checkResult = currentPlayer->getKing()->checkCheck(*dst);
if (!checkResult)
{
currentPlayer->setThreatened(false);
}
else
{
_board.move(*dst, *src);
_board.changePiece(tmp, *dst);
return 6;
}
}
else
{
if (!(toMove->checkMove(*dst)))
return 6;
// The move is legal, now checking if the piece to move causes Check on the opponent's king
_board.move(*src, *dst);
if (!(opponentPlayer->getThreatened()) &&
opponentPlayer->getKing()->checkCheck(opponentPlayer->getKing()->getPos()))
{
opponentPlayer->setThreatened(true);
toggleCurrPlayer(); // The function will return 1, meaning the turn was legal.
return 1;
}
}
// If the code reached this point, the move is legal and does not cause Check.
toggleCurrPlayer();
return 0;
}
void gameManager::toggleCurrPlayer()
{
_curr = !_curr;
}
void gameManager::printState()
{
_board.printState();
}