class Rubots::Game

Constants

CELL_SIZE
COLLISION_DISTANCE
MAP_HEIGHT
MAP_WIDTH

Attributes

laser_beams[R]
robots[R]

Public Class Methods

new(robots) click to toggle source
# File lib/rubots/game.rb, line 8
def initialize(robots)
  @robots = robots.map { |klass| Robot.new(klass, self, *random_location) }
end

Public Instance Methods

laser_fire(beam) click to toggle source
# File lib/rubots/game.rb, line 26
def laser_fire(beam)
  @laser_beams << beam
end
map() click to toggle source
# File lib/rubots/game.rb, line 22
def map
  OpenStruct.new width: MAP_WIDTH, height: MAP_HEIGHT
end
over?() click to toggle source
# File lib/rubots/game.rb, line 30
def over?
  @robots.count <= 1
end
tick() click to toggle source
# File lib/rubots/game.rb, line 12
def tick
  @laser_beams = []
  @robots.each { |robot| robot.process_command }
  @robots.each { |robot| robot.tick            }
  check_collisions
  check_out_of_area
  check_beam_hits
  clean_up_bodies
end
winner() click to toggle source
# File lib/rubots/game.rb, line 34
def winner
  return nil unless over?

  @robots.first || OpenStruct.new(name: "Nobody")
end

Private Instance Methods

check_beam_hits() click to toggle source
# File lib/rubots/game.rb, line 66
def check_beam_hits
  @laser_beams.each do |beam|
    @robots.each { |robot| beam.check_hit robot }
  end
end
check_collisions() click to toggle source
# File lib/rubots/game.rb, line 54
def check_collisions
  @robots.each do |r1|
    @robots.each do |r2|
      next if r1 == r2
      if r1.distance_to(r2) < COLLISION_DISTANCE
        r1.destroy
        puts "#{r1.name} destroyed by collision with #{r2.name}"
      end
    end
  end
end
check_out_of_area() click to toggle source
# File lib/rubots/game.rb, line 72
def check_out_of_area
  @robots.each do |r|
    if r.x > MAP_WIDTH || r.y > MAP_HEIGHT || r.x < 0 || r.y < 0
      r.destroy
      puts "#{r.name} hit the invisible wall and was destroyed"
    end
  end
end
clean_up_bodies() click to toggle source
# File lib/rubots/game.rb, line 81
def clean_up_bodies
  @robots.reject!(&:destroyed?)
end
random_location() click to toggle source
# File lib/rubots/game.rb, line 42
def random_location
  x_cells = MAP_WIDTH  / CELL_SIZE
  y_cells = MAP_HEIGHT / CELL_SIZE
  @taken ||= []
  begin
    pair = [rand(x_cells), rand(y_cells)]
  end while @taken.include?(pair)
  @taken << pair
  pair.map { |coord| coord * CELL_SIZE + CELL_SIZE / 2 }
end