diff --git a/battlesnake/src/logic.rs b/battlesnake/src/logic.rs index 58d047a..4eacf17 100644 --- a/battlesnake/src/logic.rs +++ b/battlesnake/src/logic.rs @@ -12,7 +12,6 @@ use core::f64; use std::{ - cell::Cell, collections::{BTreeMap, HashMap}, sync::{Arc, LazyLock, Mutex}, time::{Duration, Instant}, @@ -42,9 +41,9 @@ pub fn info() -> Value { }) } -#[derive(Debug, PartialEq, Eq, Clone)] +#[derive(Debug, Clone)] struct GameInfo { - calculation_time: Cell, + calculation_time: Arc>, token_mapping: Arc>, my_token: SnakeToken, } @@ -64,7 +63,9 @@ pub fn start(game: &Game, _turn: i32, board: &Board, you: &Battlesnake) { game_infos.insert( (game.id.clone(), you.id.clone()), GameInfo { - calculation_time: Cell::new(Duration::from_millis(50)), + calculation_time: Arc::new(Mutex::new(Duration::from_millis( + u64::from(game.timeout) / 2, + ))), token_mapping, my_token, }, @@ -94,7 +95,9 @@ pub fn get_move(game: &Game, turn: i32, board: &Board, you: &Battlesnake) -> Opt let token_mapping = Arc::new(SnakeToken::from_board(board)); let my_token = token_mapping[&you.id]; GameInfo { - calculation_time: Cell::new(Duration::from_millis(50)), + calculation_time: Arc::new(Mutex::new(Duration::from_millis( + u64::from(game.timeout) / 2, + ))), token_mapping, my_token, } @@ -117,15 +120,25 @@ pub fn get_move(game: &Game, turn: i32, board: &Board, you: &Battlesnake) -> Opt } // do some latency compensation - game_info.calculation_time.set( - game_info.calculation_time.get() - + Duration::from_millis( - u64::from( - game.timeout * 3 / 4 - you.latency.parse().unwrap_or(game.timeout * 3 / 4), - ) / 3, - ), - ); - let deadline = start + game_info.calculation_time.get(); + let deadline = start + + game_info.calculation_time.lock().map_or_else( + |_| Duration::from_millis(u64::from(game.timeout) / 2), + |mut guard| { + let new_duration = *guard + + Duration::from_millis( + u64::from(game.timeout) * 7 / 8 + - you + .latency + .parse() + .unwrap_or(u64::from(game.timeout) * 7 / 8), + ); + *guard = new_duration.clamp( + Duration::from_millis(1), + Duration::from_millis(u64::from(game.timeout) * 7 / 8), + ); + *guard + }, + ); let mut tree = Node::default();