From 290b793b94bfdb85b6b365bf25df8f99fd042be4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Max=20K=C3=A4nner?= Date: Mon, 2 Sep 2024 18:17:20 +0200 Subject: [PATCH] move into unsafe directions as backup --- battlesnake/src/logic.rs | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/battlesnake/src/logic.rs b/battlesnake/src/logic.rs index 3465945..eb9c50e 100644 --- a/battlesnake/src/logic.rs +++ b/battlesnake/src/logic.rs @@ -58,6 +58,30 @@ impl Battlesnake { true } + + #[must_use] + pub fn is_direction_death(&self, direction: Direction, game: &Game, board: &Board) -> bool { + let target = self.head.move_to(direction); + + // check if target is out of bounds + if !((0..board.width).contains(&target.x) && (0..board.height).contains(&target.y)) { + return true; + } + + // check if target is inside a snake + if board + .snakes + .iter() + .filter(|snake| { + !(game.ruleset.settings.squad.allow_body_collisions && self.squad == snake.squad) + }) + .flat_map(|snake| snake.body.iter()) + .any(|&coord| target == coord) + { + return true; + } + false + } } // info is called when you create your Battlesnake on play.battlesnake.com @@ -89,13 +113,19 @@ pub fn end(_game: &Game, _turn: i32, _board: &Board, _you: &Battlesnake) { // 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 { - let safe_moves = enum_iterator::all() + let moves = enum_iterator::all() + .filter(|&direction| !you.is_direction_death(direction, game, board)) + .collect::>(); + let safe_moves = moves + .iter() + .copied() .filter(|&direction| you.is_direction_safe(direction, game, board)) .collect::>(); // 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); info!("MOVE {}: {:?}", turn, chosen);