-
Notifications
You must be signed in to change notification settings - Fork 0
/
mnk.cpp
116 lines (101 loc) · 2.51 KB
/
mnk.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
#include "common.hpp"
#include "mnk.hpp"
#include <iostream>
mnk::State::State(int width_, int height_, int in_a_row_) {
width = width_;
height = height_;
in_a_row = in_a_row_;
board = std::vector<std::vector<common::Player>>(width,
std::vector<common::Player>(height, common::kNeither));
}
void mnk::State::Print() {
std::cout << '\n';
for (int y = height - 1; y >= 0; --y) {
for (int x = 0; x < width; ++x) {
if (board[x][y] == common::kPlayer1) {
std::cout << 'X';
} else if (board[x][y] == common::kPlayer2) {
std::cout << 'O';
} else {
std::cout << '_';
}
if (x < width - 1) {
std::cout << '|';
} else {
std::cout << '\n';
}
}
}
}
void mnk::State::FlipPlayer() {
common::Player temp = last_player;
last_player = current_player;
current_player = temp;
}
bool mnk::State::ValidMove(Move move) {
return move.x >= 0 && move.x < width &&
move.y >=0 && move.y < height;
}
bool mnk::State::LegalMove(Move move) {
return ValidMove(move) && board[move.x][move.y] == common::kNeither;
}
std::vector<mnk::Move> mnk::State::LegalMoves() {
std::vector<Move> legal_moves;
legal_moves.reserve(width * height);
for (int x = 0; x < width; ++x) {
for (int y = 0; y < height; ++y) {
if (board[x][y] == common::kNeither) {
legal_moves.emplace_back(x, y);
}
}
}
return legal_moves;
}
void mnk::State::PlayMove(Move move) {
board[move.x][move.y] = current_player;
move_history.push_back(move);
FlipPlayer();
}
void mnk::State::PlayRandomMove() {
while (true) {
Move move(rand() % width, rand() % height);
if (LegalMove(move)) {
PlayMove(move);
break;
}
}
}
void mnk::State::UndoMove() {
Move last_move = move_history.back();
board[last_move.x][last_move.y] = common::kNeither;
move_history.pop_back();
FlipPlayer();
winner = common::kNeither;
}
bool mnk::State::GameOver() {
if (winner != common::kNeither ||
move_history.size() == width * height) {
return true;
}
if (move_history.size() == 0) {
return false;
}
Move last_move = move_history.back();
auto CountRay = [&](int delta_x, int delta_y) {
int count = 0;
for (int x = last_move.x, y = last_move.y;
ValidMove(Move(x, y)) && board[x][y] == last_player;
x += delta_x, y += delta_y) {
++count;
}
return count;
};
if (CountRay(1, 0) + CountRay(-1, 0) > in_a_row ||
CountRay(0, 1) + CountRay(0, -1) > in_a_row ||
CountRay(1, 1) + CountRay(-1, -1) > in_a_row ||
CountRay(1, -1) + CountRay(-1, 1) > in_a_row) {
winner = last_player;
return true;
}
return false;
}