summaryrefslogtreecommitdiff
path: root/src/strategy.rs
diff options
context:
space:
mode:
authorJustin Worthe <justin@worthe-it.co.za>2019-05-22 20:38:47 +0200
committerJustin Worthe <justin@worthe-it.co.za>2019-05-22 20:38:47 +0200
commite9a514409565c17a4a86e8c6402be8d7a4f399ae (patch)
tree839dc6e223014ef519fe4d2d020aea996b562e44 /src/strategy.rs
parent63da94f7f1b25eddeb9ffd379f37c1a32e750fdb (diff)
Added a strategy cache for reusing previous round data
Diffstat (limited to 'src/strategy.rs')
-rw-r--r--src/strategy.rs39
1 files changed, 30 insertions, 9 deletions
diff --git a/src/strategy.rs b/src/strategy.rs
index 8d2eea5..39bbe66 100644
--- a/src/strategy.rs
+++ b/src/strategy.rs
@@ -11,13 +11,30 @@ use rand;
use rand::prelude::*;
use arrayvec::ArrayVec;
-pub fn choose_move(state: &GameBoard, start_time: &PreciseTime, max_time: Duration) -> Command {
- let mut root_node = Node {
- state: state.clone(),
- score_sum: ScoreSum::new(),
- player_score_sums: [HashMap::new(), HashMap::new()],
- unexplored: mcts_move_combo(state),
- children: HashMap::new(),
+pub fn choose_move(state: &GameBoard, previous_root: Option<Node>, start_time: &PreciseTime, max_time: Duration) -> (Command, Node) {
+ let mut root_node = match previous_root {
+ None => Node {
+ state: state.clone(),
+ score_sum: ScoreSum::new(),
+ player_score_sums: [HashMap::new(), HashMap::new()],
+ unexplored: mcts_move_combo(state),
+ children: HashMap::new(),
+ },
+ Some(mut node) => {
+ node.children.drain()
+ .map(|(_k, n)| n)
+ .find(|n| n.state == *state)
+ .unwrap_or_else(|| {
+ eprintln!("Previous round did not appear in the cache");
+ Node {
+ state: state.clone(),
+ score_sum: ScoreSum::new(),
+ player_score_sums: [HashMap::new(), HashMap::new()],
+ unexplored: mcts_move_combo(state),
+ children: HashMap::new(),
+ }
+ })
+ }
};
while start_time.to(PreciseTime::now()) < max_time {
@@ -34,10 +51,14 @@ pub fn choose_move(state: &GameBoard, start_time: &PreciseTime, max_time: Durati
);
}
- best_player_move(&root_node)
+ let chosen_command = best_player_move(&root_node);
+
+ root_node.children.retain(|[c1, _], _| *c1 == chosen_command);
+
+ (chosen_command, root_node)
}
-struct Node {
+pub struct Node {
state: GameBoard,
score_sum: ScoreSum,
player_score_sums: [HashMap<Command, ScoreSum>; 2],