-
Notifications
You must be signed in to change notification settings - Fork 0
/
gameboard.cpp
138 lines (114 loc) · 2.9 KB
/
gameboard.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include <QtDebug>
#include <cassert>
#include "gameboard.h"
/**** Board methods *******/
GameBoard::GameBoard(const GameBoard &other):
rowNum(other.getRowNumber()),
colNum(other.getColNumber()),
freeBoxes(other.freeBoxes),
last_to_play(other.lastToPlay()),
next_to_play(other.nextToPlay())
{
game_board = new Player*[rowNum];
for(int i = 0; i < rowNum; i++)
{
game_board[i] = new Player[colNum];
for(int j = 0; j < colNum; j++)
{
game_board[i][j] = other.getValue(i, j);
}
}
}
bool GameBoard::hasWinner()
{
bool flag;
//Checks the rows
for(int i = 0; i < rowNum; i++)
{
const Player a0 = game_board[i][0];
flag = true;
for(int j = 1; j < colNum; j++)
{
if(a0 != game_board[i][j] || game_board[i][j] == Player::None)
{
flag = false;
break;
}
}
if(flag)
return true;
}
//check the cols
for(int j = 0; j < colNum; j++)
{
const Player a0 = game_board[0][j];
flag = true;
for(int i = 1; i < rowNum; i++)
{
if(a0 != game_board[i][j] || game_board[i][j] == Player::None)
{
flag = false;
break;
}
}
if(flag)
return true;
}
//and the diagonals
flag = true;
for(int i = 1; i < rowNum; i++)
{
const Player a0 = game_board[0][0];
if(a0 != game_board[i][i] || game_board[i][i] == Player::None)
{
flag = false;
break;
}
}
if(flag)
return true;
flag = true;
for(int i = 1; i < rowNum; i++)
{
const Player b0 = game_board[0][rowNum-1];
if(b0 != game_board[i][rowNum - 1 - i] || game_board[i][rowNum - 1 - i] == Player::None)
{
flag = false;
break;
}
}
return flag;
}
void GameBoard::setSquare(int row, int col, const Player ¤t_player)
{
assert(isEmpty(row, col) && "Trying to set a used squared");
game_board[row][col] = current_player;
last_to_play = current_player;
next_to_play = (current_player == Player::Human) ? Player::Machine : Player::Human;
freeBoxes--;
};
void GameBoard::clearSquare(int row, int col)
{
assert(!isEmpty(row, col) && "Trying to clear a free square");
game_board[row][col] = Player::None;
last_to_play = Player::None;
next_to_play = Player::None;
freeBoxes++;
}
/*If the game is over it writes the scores on the argument and returns true,
otherwise it returns false*/
int GameBoard::score(int &score)
{
int winningScore = (last_to_play == Player::Human) ? -1 : 1;
if(hasWinner())
{
score = winningScore;
return true;
}
else if(!hasPlace())
{
score = 0;
return true;
}
return false;
}