return None if no valid move was found

This commit is contained in:
Max Känner 2024-09-30 18:34:47 +02:00
parent b7ea419d21
commit e5b81a3ff9
2 changed files with 7 additions and 8 deletions

View File

@ -138,7 +138,7 @@ pub fn end(_game: &Game, _turn: i32, _board: &Board, _you: &Battlesnake) {
// move is called on every turn and returns your next move // move is called on every turn and returns your next move
// Valid moves are "up", "down", "left", or "right" // Valid moves are "up", "down", "left", or "right"
// See https://docs.battlesnake.com/api/example-move for available data // See https://docs.battlesnake.com/api/example-move for available data
pub fn get_move(game: &Game, turn: i32, board: &Board, you: &Battlesnake) -> Move { pub fn get_move(game: &Game, turn: i32, board: &Board, you: &Battlesnake) -> Option<Move> {
let moves = enum_iterator::all() let moves = enum_iterator::all()
.filter(|&direction| !you.is_direction_death(direction, game, board)) .filter(|&direction| !you.is_direction_death(direction, game, board))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@ -151,12 +151,11 @@ pub fn get_move(game: &Game, turn: i32, board: &Board, you: &Battlesnake) -> Mov
// Choose a random move from the safe ones // Choose a random move from the safe ones
let chosen = safe_moves let chosen = safe_moves
.choose(&mut rand::thread_rng()) .choose(&mut rand::thread_rng())
.or_else(|| moves.choose(&mut rand::thread_rng())) .or_else(|| moves.choose(&mut rand::thread_rng()))?;
.unwrap_or(&Direction::Up);
info!("MOVE {}: {:?}", turn, chosen); info!("MOVE {}: {:?}", turn, chosen);
Move { Some(Move {
r#move: *chosen, r#move: *chosen,
shout: None, shout: None,
} })
} }

View File

@ -201,15 +201,15 @@ fn handle_start(start_req: Json<GameState>) -> Status {
} }
#[post("/move", format = "json", data = "<move_req>")] #[post("/move", format = "json", data = "<move_req>")]
fn handle_move(move_req: Json<GameState>) -> Json<Move> { fn handle_move(move_req: Json<GameState>) -> Option<Json<Move>> {
let response = logic::get_move( let response = logic::get_move(
&move_req.game, &move_req.game,
move_req.turn, move_req.turn,
&move_req.board, &move_req.board,
&move_req.you, &move_req.you,
); )?;
Json(response) Some(Json(response))
} }
#[post("/end", format = "json", data = "<end_req>")] #[post("/end", format = "json", data = "<end_req>")]