forked from ethz-gtc/npc-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.rs
175 lines (157 loc) · 4.76 KB
/
main.rs
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
/*
* SPDX-License-Identifier: Apache-2.0 OR MIT
* © 2020-2022 ETH Zurich and other contributors, see AUTHORS.txt for details
*/
use board::State;
use npc_engine_core::{graphviz, AgentId, MCTSConfiguration, MCTS};
use npc_engine_utils::plot_tree_in_tmp;
use regex::Regex;
use crate::{
board::{Board, Cell, CellArray2D, CellCoord},
domain::TicTacToe,
player::Player,
r#move::Move,
};
mod board;
mod domain;
mod r#move;
mod player;
enum Input {
Coordinate((CellCoord, CellCoord)),
Quit,
Error,
}
fn get_input() -> Input {
let mut input = String::new();
std::io::stdin()
.read_line(&mut input)
.expect("Failed to read line");
match input.trim() {
"q" => Input::Quit,
s => {
let input_re = Regex::new(r"^([0-2])\s([0-2])$").unwrap();
let cap = input_re.captures(s);
let cap = cap.filter(|cap| cap.len() >= 3);
if let Some(cap) = cap {
let x = CellCoord::new(cap[1].parse().unwrap()).unwrap();
let y = CellCoord::new(cap[2].parse().unwrap()).unwrap();
Input::Coordinate((x, y))
} else {
println!("Input error, try again!");
Input::Error
}
}
}
}
fn run_mcts_and_return_move(
board: u32,
agent: AgentId,
config: MCTSConfiguration,
turn_to_plot: Option<u32>,
) -> Move {
let mut mcts = MCTS::<TicTacToe>::new(board, agent, config);
if let Some(turn) = turn_to_plot {
if let Err(e) = plot_tree_in_tmp(&mcts, "tic-tac-toe_graphs", &format!("turn{turn:02}")) {
println!("Cannot write search tree: {e}");
}
}
let task = mcts.run().unwrap();
task.downcast_ref::<Move>().unwrap().clone()
}
fn game_finished(state: State) -> bool {
if state.is_full() {
println!("Draw!");
return true;
}
if let Some(winner) = state.winner() {
match winner {
Player::O => println!("You won!"),
Player::X => println!("Computer won!"),
};
true
} else {
false
}
}
fn main() {
// These parameters control the MCTS algorithm.
const CONFIG: MCTSConfiguration = MCTSConfiguration {
allow_invalid_tasks: false,
visits: 1000,
depth: 9,
exploration: 1.414,
discount_hl: f32::INFINITY,
seed: None,
planning_task_duration: None,
};
// Set the depth of graph output to 6 and enable logging if specified
// in the RUST_LOG environment variable.
graphviz::set_graph_output_depth(6);
env_logger::init();
println!("Welcome to tic-tac-toe. You are player 'O', I'm player 'X'.");
let mut board = 0;
let mut turn = 0;
loop {
// Print the current board.
println!("{}", board.description());
// Get input.
println!("Please enter a coordinate with 'X Y' where X,Y are 0,1,2, or 'q' to quit.");
let (x, y) = match get_input() {
Input::Coordinate(pair) => pair,
Input::Quit => break,
Input::Error => continue,
};
if board.get(x, y) != Cell::Empty {
println!("The cell {x} {y} is already occupied!");
continue;
}
// Set cell.
board.set(x, y, Cell::Player(Player::O));
// Did we win?
if game_finished(board) {
println!("{}", board.description());
break;
}
// Run planner.
println!("Computer is thinking...");
const AI_AGENT: AgentId = AgentId(1);
let ai_move = run_mcts_and_return_move(board, AI_AGENT, CONFIG, Some(turn));
println!("Computer played {ai_move}");
board.set(ai_move.x, ai_move.y, Cell::Player(Player::X));
turn += 1;
// Did computer win?
if game_finished(board) {
println!("{}", board.description());
break;
}
}
}
#[cfg(test)]
mod tests {
use crate::*;
#[test]
fn ai_vs_ai_must_be_a_draw() {
const CONFIG: MCTSConfiguration = MCTSConfiguration {
allow_invalid_tasks: false,
visits: 5000,
depth: 9,
exploration: 1.414,
discount_hl: f32::INFINITY,
planning_task_duration: None,
seed: None,
};
for _ in 0..10 {
let mut board = 0;
loop {
for agent in [AgentId(0), AgentId(1)] {
let task = run_mcts_and_return_move(board, agent, CONFIG, None);
board.set(task.x, task.y, Cell::Player(Player::from_agent(agent)));
assert_eq!(board.winner(), None);
if board.is_full() {
return;
}
}
}
}
}
}