Skip to content

Commit

Permalink
Extract possible collisions to Utils (#31)
Browse files Browse the repository at this point in the history
  • Loading branch information
fdocr authored Oct 3, 2023
1 parent 4a43355 commit e5a8860
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 14 deletions.
15 changes: 1 addition & 14 deletions src/strategy/cautious_carol.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 24 additions & 0 deletions src/strategy/utils/possible_collisions.cr
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit e5a8860

Please sign in to comment.