Repository navigation
Expand file tree
/
Copy pathgreedy_cpu.cpp
More file actions
68 lines (55 loc) · 1.98 KB
/
Copy pathgreedy_cpu.cpp
File metadata and controls
68 lines (55 loc) · 1.98 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
#include "greedy_cpu.hpp"
#include <algorithm>
greedy_cpu::greedy_cpu(game_board* b) {
board = b;
}
std::vector<game_move> greedy_cpu::get_all_valid_moves() {
std::vector<game_move> moves;
for(int r = 0; r < board->get_rows(); r++) {
for(int c = 0; c < board->get_cols(); c++) {
if(board->is_valid_move(r, c, cell_type::forward_slash))
moves.push_back({r, c, cell_type::forward_slash});
if(board->is_valid_move(r, c, cell_type::back_slash))
moves.push_back({r, c, cell_type::back_slash});
}
}
return moves;
}
int greedy_cpu::calculate_move_score(game_move m) {
int score = 0;
int r1, c1, r2, c2;
if(m.type == cell_type::forward_slash) {
r1 = m.row + 1; c1 = m.col;
r2 = m.row; c2 = m.col + 1;
} else {
r1 = m.row; c1 = m.col;
r2 = m.row + 1; c2 = m.col + 1;
}
// Heuristic 1: If this move completes a required constraint, do it!
int lim1 = board->get_constraint(r1, c1);
int deg1 = board->get_degree(r1, c1);
if(lim1 != -1 && deg1 + 1 == lim1) score += 100;
int lim2 = board->get_constraint(r2, c2);
int deg2 = board->get_degree(r2, c2);
if(lim2 != -1 && deg2 + 1 == lim2) score += 100;
// Heuristic 2: Prefer touching nodes that have constraints
if(lim1 != -1) score += 20;
if(lim2 != -1) score += 20;
// Heuristic 3: Prefer busy areas
score += (deg1 + deg2) * 5;
return score;
}
game_move greedy_cpu::decide_move() {
auto valid_moves = get_all_valid_moves();
if(valid_moves.empty()) return {-1, -1, cell_type::empty};
std::vector<ranked_move> ranked;
for(const auto& m : valid_moves) {
ranked.push_back({m, calculate_move_score(m)});
}
// Sort descending by score
std::sort(ranked.begin(), ranked.end(),
[](const ranked_move& a, const ranked_move& b) {
return a.score > b.score;
});
return ranked[0].move;
}