-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.cpp
87 lines (71 loc) · 2.7 KB
/
game.cpp
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
#include "game.h"
Game::Game(ChessBoard* chessboard, QObject *parent) : QObject(parent), chessboard(chessboard), isPawnPromotion(false)
{
whiteTimer.setHMS(0, 5, 0);
blackTimer.setHMS(0, 5, 0);
chessboard->initialBoard();
currentPlayer = ChessPiece::White;
QObject::connect(&whiteTimerUpdateTimer, &QTimer::timeout, this, &Game::updateWhiteTimer);
QObject::connect(&blackTimerUpdateTimer, &QTimer::timeout, this, &Game::updateBlackTimer);
QObject::connect(chessboard, &ChessBoard::pawnPromotionSignal, this, &Game::pawnPromotionHandler);
}
// Add slots to update the timers
void Game::updateWhiteTimer()
{
if (currentPlayer == ChessPiece::Color::White && whiteTimer > QTime(0, 0)) {
whiteTimer = whiteTimer.addSecs(-1);
emit whiteTimerUpdated(whiteTimer);
}
}
void Game::updateBlackTimer()
{
if (currentPlayer == ChessPiece::Color::Black && blackTimer > QTime(0, 0)) {
blackTimer = blackTimer.addSecs(-1);
emit blackTimerUpdated(blackTimer);
}
}
void Game::pawnPromotionHandler(int fromRow, int toRow, int fromCol, int toCol)
{
emit pawnPromotionGUI(fromRow, toRow, fromCol, toCol);
isPawnPromotion = true;
qDebug() << "mf reacher this";
}
void Game::makeMove(int fromRow, int fromCol, int toRow, int toCol)
{
ChessPiece pieceToMove = chessboard->getPiece(fromRow, fromCol);
ChessPiece targetPiece = chessboard->getPiece(toRow, toCol);
if(!pieceToMove.isEmpty() && pieceToMove.getColor() == currentPlayer){
// Check if the move is valid
if(chessboard->VALIDMOVE(pieceToMove.getType(), fromRow, fromCol, toRow, toCol)){
chessboard->movePiece(fromRow, fromCol, toRow, toCol);
// Switches the turn
if(pieceToMove.getColor() != targetPiece.getColor()){
if(!isPawnPromotion)
currentPlayer = (currentPlayer == ChessPiece::Color::White) ? ChessPiece::Color::Black : ChessPiece::Color::White;
// Starts the timer only when the first move is made
blackTimerUpdateTimer.start(1000);
whiteTimerUpdateTimer.start(1000);
if(currentPlayer == ChessPiece::Color::White){
qDebug() << "white timer: " << whiteTimer;
blackTimerUpdateTimer.start(1000);
}else{
qDebug() << "black timer: " << blackTimer;
whiteTimerUpdateTimer.start(1000);
}
}
}
}
isPawnPromotion = false;
}
ChessPiece::Color Game::getCurrentPlayer() const
{
return currentPlayer;
}
QTime Game::getWhiteTimer() const
{
return whiteTimer;
}
QTime Game::getBlackTimer() const
{
return blackTimer;
}