From 4e44ac548cf8a8a0b3c76befa30561657b27c5d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Max=20K=C3=A4nner?= Date: Sun, 6 Oct 2024 22:28:08 +0200 Subject: [PATCH] make nodes depend on snake length --- battlesnake/src/logic.rs | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/battlesnake/src/logic.rs b/battlesnake/src/logic.rs index 324f79c..89a73e0 100644 --- a/battlesnake/src/logic.rs +++ b/battlesnake/src/logic.rs @@ -19,7 +19,7 @@ use std::{ use log::{error, info, warn}; use ordered_float::OrderedFloat; -use rand::thread_rng; +use rand::{prelude::*, thread_rng}; use serde_json::{json, Value}; use crate::{ @@ -172,7 +172,8 @@ pub fn get_move( let chosen = actions .iter() .max_by_key(|(_, stat)| OrderedFloat(stat.won as f64 / stat.played as f64)) - .map(|(direction, _)| *direction)?; + .map(|(direction, _)| *direction) + .or_else(|| possible_actions.iter().choose(&mut thread_rng()).copied())?; info!( "DIRECTION {turn}: {chosen:?} after {}ms ({})", @@ -205,7 +206,7 @@ struct DeadlineError; struct Node { statistic: Statistics, child_statistics: BTreeMap>, - childs: BTreeMap, Node>, + childs: BTreeMap, Node>, } impl Node { @@ -258,9 +259,13 @@ impl Node { .collect(); board.simulate_actions(&actions, &mut thread_rng()); + let map_actions = actions + .iter() + .map(|(&snake, &action)| (snake, (action, board.snake_length(snake).unwrap_or(0)))) + .collect(); let winner = self .childs - .entry(actions.clone()) + .entry(map_actions) .or_default() .monte_carlo_step(board, deadline)?; @@ -352,9 +357,13 @@ impl Node { return Err(DeadlineError); } board.simulate_actions(&actions, &mut thread_rng()); + let map_actions = actions + .iter() + .map(|(&snake, &action)| (snake, (action, board.snake_length(snake).unwrap_or(0)))) + .collect(); let lengths = self .childs - .entry(actions.clone()) + .entry(map_actions) .or_default() .monte_carlo_step_solo(board, deadline)?;