Compare commits

..

2 Commits

2 changed files with 22 additions and 9 deletions

View File

@ -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<SnakeToken, BTreeMap<Direction, ActionStatistic>>,
childs: BTreeMap<BTreeMap<SnakeToken, Direction>, Node>,
childs: BTreeMap<BTreeMap<SnakeToken, (Direction, usize)>, 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)?;

View File

@ -1,6 +1,6 @@
#![allow(clippy::needless_pass_by_value)]
use battlesnake::{logic, Action, GameState};
use battlesnake::{logic, Action, Direction, GameState};
use log::{error, info};
use rocket::{
fairing::AdHoc, get, http::Status, launch, post, routes, serde::json::Json, tokio::task,
@ -26,7 +26,7 @@ fn handle_start(start_req: Json<GameState>) -> Status {
}
#[post("/move", format = "json", data = "<move_req>")]
async fn handle_move(move_req: Json<GameState>) -> Option<Json<Action>> {
async fn handle_move(move_req: Json<GameState>) -> Json<Action> {
let start = Instant::now();
let response = task::spawn_blocking(move || {
logic::get_move(
@ -40,9 +40,13 @@ async fn handle_move(move_req: Json<GameState>) -> Option<Json<Action>> {
.await
.inspect_err(|e| error!("failed to join compute thread: {e}"))
.ok()
.flatten()?;
.flatten()
.unwrap_or(Action {
r#move: Direction::Up,
shout: Some("I am so dead".to_owned()),
});
Some(Json(response))
Json(response)
}
#[post("/end", format = "json", data = "<end_req>")]