give the snake more thinging time

This commit is contained in:
Max Känner 2024-10-03 05:37:19 +02:00
parent a1bdd4cb1b
commit 3d58e5331b

View File

@ -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<Duration>,
calculation_time: Arc<Mutex<Duration>>,
token_mapping: Arc<BTreeMap<String, SnakeToken>>,
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()
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 * 3 / 4 - you.latency.parse().unwrap_or(game.timeout * 3 / 4),
) / 3,
),
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 deadline = start + game_info.calculation_time.get();
let mut tree = Node::default();