-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathboard_model.cpp
More file actions
70 lines (54 loc) · 1.77 KB
/
board_model.cpp
File metadata and controls
70 lines (54 loc) · 1.77 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
#include "board_model.hpp"
namespace FrogToad {
// --- Public API ---
void BoardModel::reset() {
board = StartingBoard;
isGameSolved = false;
}
bool BoardModel::isSolved() const {
return isGameSolved;
}
BoardModel::Cell BoardModel::cellAt(int i) const {
return isIndexValid(i) ? board[i] : Cell::Empty;
}
char BoardModel::toChar(Cell c) {
switch (c) {
case Cell::Empty: return '.';
case Cell::Frog: return 'F';
case Cell::Toad: return 'T';
default: return 'X'; // Invalid! There are only three states to the enum.
}
}
bool BoardModel::tryMove(int i) {
if (!isIndexValid(i) || isCellEmpty(i)) return false;
Cell c{ board[i] };
int slideMove{ i + moveDirection(c) };
int jumpMove{ i + 2 * moveDirection(c) };
if (isIndexValid(slideMove) && !isCellEmpty(slideMove) && isIndexValid(jumpMove) && isCellEmpty(jumpMove)) {
board[jumpMove] = c;
}
else if (isIndexValid(slideMove) && isCellEmpty(slideMove)) {
board[slideMove] = c;
}
else {
return false;
}
board[i] = Cell::Empty;
evaluateBoard();
return true;
}
// --- Private Static Constexpr Helpers ---
constexpr bool BoardModel::isIndexValid(int i) {
return i >= 0 && i < BoardSize;
}
constexpr int BoardModel::moveDirection(Cell c) {
return (c == Cell::Frog) ? +1 : -1;
}
// --- Private Instance Helpers ---
bool BoardModel::isCellEmpty(int i) const {
return board[i] == Cell::Empty;
}
void BoardModel::evaluateBoard() {
isGameSolved = (board == GoalBoard);
}
} // namespace FrogToad