From e5a88601ce98a7734f3fd6c84450b956646bb010 Mon Sep 17 00:00:00 2001 From: Fernando Valverde Date: Mon, 2 Oct 2023 19:46:20 -0600 Subject: [PATCH] Extract possible collisions to Utils (#31) --- src/strategy/cautious_carol.cr | 15 +------------- src/strategy/utils/possible_collisions.cr | 24 +++++++++++++++++++++++ 2 files changed, 25 insertions(+), 14 deletions(-) create mode 100644 src/strategy/utils/possible_collisions.cr diff --git a/src/strategy/cautious_carol.cr b/src/strategy/cautious_carol.cr index 3b674f3..38aa068 100644 --- a/src/strategy/cautious_carol.cr +++ b/src/strategy/cautious_carol.cr @@ -10,20 +10,7 @@ class Strategy::CautiousCarol < Strategy::Base return RandomValid.new(@context).move if valid_moves[:moves].empty? # Check for head-to-head collision possibilities - dangerous_moves = [] of BattleSnake::Point - @context.enemies.each do |snake| - next if (snake.head <=> @context.you.head) > 2 - next if snake.body.size < @context.you.body.size - - # Check if we share valid moves (meeting point for collision) - @context.valid_moves(snake.head)[:neighbors].values.each do |point| - meeting_point = valid_moves[:neighbors].values.find do |p| - (point <=> p).zero? - end - next if meeting_point.nil? - dangerous_moves << point - end - end + dangerous_moves = Utils.possible_collisions(@context) # Calculate chase closest food direction closest_food = ChaseClosestFood.new(@context).move diff --git a/src/strategy/utils/possible_collisions.cr b/src/strategy/utils/possible_collisions.cr new file mode 100644 index 0000000..ab00377 --- /dev/null +++ b/src/strategy/utils/possible_collisions.cr @@ -0,0 +1,24 @@ +# Implementation that returns all moves that could cause a collision with +# another snake which would result in death. +def Strategy::Utils.possible_collisions(context : BattleSnake::Context) + valid_moves = context.valid_moves(context.you.head) + dangerous_moves = [] of BattleSnake::Point + + context.enemies.each do |snake| + # Snake is too far away to collide + next if (snake.head <=> context.you.head) > 2 + # We're larger than the snake (not dangerous) + next if snake.body.size < context.you.body.size + + # Check if we share valid moves (meeting point for collision) + context.valid_moves(snake.head)[:neighbors].values.each do |point| + meeting_point = valid_moves[:neighbors].values.find do |p| + (point <=> p).zero? + end + next if meeting_point.nil? + dangerous_moves << point + end + end + + dangerous_moves +end \ No newline at end of file