From e5b81a3ff9bca2c7c55b94b7b256d04111936c9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Max=20K=C3=A4nner?= Date: Mon, 30 Sep 2024 18:34:47 +0200 Subject: [PATCH] return None if no valid move was found --- battlesnake/src/logic.rs | 9 ++++----- battlesnake/src/main.rs | 6 +++--- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/battlesnake/src/logic.rs b/battlesnake/src/logic.rs index b28a137..9f0ee07 100644 --- a/battlesnake/src/logic.rs +++ b/battlesnake/src/logic.rs @@ -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 // Valid moves are "up", "down", "left", or "right" // 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 { let moves = enum_iterator::all() .filter(|&direction| !you.is_direction_death(direction, game, board)) .collect::>(); @@ -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 let chosen = safe_moves .choose(&mut rand::thread_rng()) - .or_else(|| moves.choose(&mut rand::thread_rng())) - .unwrap_or(&Direction::Up); + .or_else(|| moves.choose(&mut rand::thread_rng()))?; info!("MOVE {}: {:?}", turn, chosen); - Move { + Some(Move { r#move: *chosen, shout: None, - } + }) } diff --git a/battlesnake/src/main.rs b/battlesnake/src/main.rs index b64dbbc..a4b8187 100644 --- a/battlesnake/src/main.rs +++ b/battlesnake/src/main.rs @@ -201,15 +201,15 @@ fn handle_start(start_req: Json) -> Status { } #[post("/move", format = "json", data = "")] -fn handle_move(move_req: Json) -> Json { +fn handle_move(move_req: Json) -> Option> { let response = logic::get_move( &move_req.game, move_req.turn, &move_req.board, &move_req.you, - ); + )?; - Json(response) + Some(Json(response)) } #[post("/end", format = "json", data = "")]