spawn blocking task for simulations
All checks were successful
Build / build (push) Successful in 2m2s

This commit is contained in:
Max Känner 2025-01-22 01:17:11 +01:00
parent c26da8869c
commit 32883b2a1b

View File

@ -82,14 +82,10 @@ async fn get_move(request: Json<Request>) -> response::Json<Response> {
} }
info!("valid actions: {:?}", actions); info!("valid actions: {:?}", actions);
let mut action_data = [(0, 0); 4]; tokio::task::spawn_blocking(move || {
let mut total_simulations = 0;
let base_turns = board.turn(); let base_turns = board.turn();
while start.elapsed() < Duration::from_millis(250) { let end_condition: &dyn Fn(&Board) -> Option<u32> = match &*request.game.ruleset.name {
let mut board = board.clone(); "solo" => &|board: &Board| {
let action = *actions.choose(&mut thread_rng()).unwrap_or(&Direction::Up);
board.next_turn(&[(id, action)]);
let turns = board.simulate_random(|board| {
if board.num_snakes() == 0 if board.num_snakes() == 0
|| board.turn() > base_turns + u32::from(request.you.length) * 3 || board.turn() > base_turns + u32::from(request.you.length) * 3
{ {
@ -97,7 +93,24 @@ async fn get_move(request: Json<Request>) -> response::Json<Response> {
} else { } else {
None None
} }
}); },
_ => &|board: &Board| {
if !board.alive(id) || board.turn() > base_turns + u32::from(request.you.length) * 3
{
Some(board.turn())
} else {
None
}
},
};
let mut action_data = [(0, 0); 4];
let mut total_simulations = 0;
while start.elapsed() < Duration::from_millis(250) {
let mut board = board.clone();
let action = *actions.choose(&mut thread_rng()).unwrap_or(&Direction::Up);
board.next_turn(&[(id, action)]);
let turns = board.simulate_random(end_condition);
let action_data = &mut action_data[usize::from(action)]; let action_data = &mut action_data[usize::from(action)];
action_data.0 += turns - base_turns; action_data.0 += turns - base_turns;
action_data.1 += 1; action_data.1 += 1;
@ -122,6 +135,7 @@ async fn get_move(request: Json<Request>) -> response::Json<Response> {
direction: action.unwrap_or(Direction::Up), direction: action.unwrap_or(Direction::Up),
shout: None, shout: None,
}) })
}).await.unwrap()
} }
async fn end(request: Json<Request>) { async fn end(request: Json<Request>) {