-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflip_tiles.cpp
More file actions
114 lines (103 loc) · 3.66 KB
/
flip_tiles.cpp
File metadata and controls
114 lines (103 loc) · 3.66 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#pragma once
#include "table.hpp"
/**
* @brief When called, it flips the valid tiles in the direction of the move.
*
* @param move: coordinates of the moves
* @param dir: direction
*
* @return nothing
*/
void Table::flipTiles(coor move)
{
coor curr(move), toFlip(move);
bool isFlipped = false;
// valid move guard in case there is a problem with isLegal function
bool isValid = false;
// for each direction
for (auto dir : DIRS)
{
isFlipped = false;
for (int i = 1;; i++)
{
// multiplying by 'i' to move along the directions
curr.row = move.row + dir[0] * i;
curr.col = move.col + dir[1] * i;
// if the square is not on the board, then it is not a legal move
if (!isOnBoard(curr))
break;
// if the square is empty, the goal is not reached
if (getBoard(curr) == EMPTY || getBoard(curr) == LEGAL)
break;
// isFlipped changes to true if there is a tile to flip
// when the player's square is found, there must be at least one tile to flip
if (getBoard(curr) == getOpponent())
isFlipped = true;
// when a square in the same color as players is found
if (getBoard(curr) == getTurn())
{
// if isFlipped is not true, then it is not a legal move
if (!isFlipped)
break;
isValid = true;
// toFlip is assigned the numbers along the legal direction
// to flip the tiles between curr and move, not including curr and move
// [curr]-----[toFlip]-----[move]
toFlip.row = move.row + dir[0];
toFlip.col = move.col + dir[1];
// assigning the squares, when the direction is horizontal
if (dir[0] == 0)
{
// assign till curr.col
while (toFlip.col != curr.col)
{
// incrase the number by the delta
setBoard(toFlip, getTurn());
toFlip.col += dir[1];
}
}
// assigning the squares, when the direction is vertical
else if (dir[1] == 0)
{
// assign till curr.row
while (toFlip.row != curr.row)
{
// incrase the number by the delta
setBoard(toFlip, getTurn());
toFlip.row += dir[0];
}
}
// assigning the squares, when the direction is cross
else
{
// assign till curr.row and curr.col
while (toFlip.row != curr.row && toFlip.col != curr.col)
{
// incrase the numbers by the delta
setBoard(toFlip, getTurn());
toFlip.row += dir[0];
toFlip.col += dir[1];
}
}
break;
}
}
}
try
{
if (isValid)
{
this->moves.push_back(move);
// the chosen square is assigned to current player's color
setBoard(move, getTurn());
}
else
{
throw "flipTiles: Illegal move\n";
}
}
catch (const char *msg)
{
std::cerr << msg;
}
}