class SnakeGame::BaitManager

Class for managing and updating baits (snake food)

Attributes

baits[RW]

Public Class Methods

new() click to toggle source
# File lib/bait_manager.rb, line 12
def initialize
  @baits = []
  @images = ImageDatabase.new
end

Public Instance Methods

add_bait(position) click to toggle source
# File lib/bait_manager.rb, line 26
def add_bait(position)
  @baits << (Bait.new position, @images.bait)
end
calculate_random_movement() click to toggle source
# File lib/bait_manager.rb, line 62
def calculate_random_movement
  random = rand
  return Position.new(STEP, 0) if random > 0.75 # go right
  return Position.new(-STEP, 0) if random > 0.5 # go left
  return Position.new(0, STEP) if random > 0.25 # go down
  Position.new(0, -STEP) # go up
end
draw() click to toggle source
# File lib/bait_manager.rb, line 70
def draw
  @baits.each(&:draw)
end
free?(position, snake) click to toggle source
# File lib/bait_manager.rb, line 51
def free?(position, snake)
  free = true
  snake.snake_parts.each do |part|
    free = false if part.position == position
  end
  @baits.each do |bait|
    free = false if bait.position == position
  end
  free
end
random_free_position(snake) click to toggle source
# File lib/bait_manager.rb, line 30
def random_free_position(snake)
  loop do
    position = Position.new (rand * WIDTH).round(-1) % WIDTH,
                            (rand * HEIGHT).round(-1) % HEIGHT
    return position if free? position, snake
  end
end
update(snake) click to toggle source
# File lib/bait_manager.rb, line 17
def update(snake)
  if @baits.count.zero?
    position = random_free_position snake
    add_bait position
  else
    update_baits snake
  end
end
update_baits(snake) click to toggle source
# File lib/bait_manager.rb, line 38
def update_baits(snake)
  @baits.each do |bait|
    next if rand < EVASION
    loop do
      new_position = bait.position + calculate_random_movement
      if free? new_position, snake
        bait.position = new_position
        break
      end
    end
  end
end