Class: Toy::UnitCollection

Inherits:
Object
  • Object
show all
Defined in:
lib/toy/unit_collection.rb

Defined Under Namespace

Modules: Error

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(direction = Toy::Direction) ⇒ UnitCollection

Returns a new instance of UnitCollection.



7
8
9
10
# File 'lib/toy/unit_collection.rb', line 7

def initialize(direction=Toy::Direction)
  @all = []
  @direction = direction
end

Instance Attribute Details

#allObject (readonly)

Returns the value of attribute all.



5
6
7
# File 'lib/toy/unit_collection.rb', line 5

def all
  @all
end

Instance Method Details

#add(unit) ⇒ Object



12
13
14
15
16
# File 'lib/toy/unit_collection.rb', line 12

def add(unit)
  raise Toy::UnitCollection::Error::UnitError unless unit.is_a?(Unit)
  
  @all << unit
end

#find_by_coordinates(x, y) ⇒ Object



18
19
20
# File 'lib/toy/unit_collection.rb', line 18

def find_by_coordinates(x, y)
  @all.find { |unit| unit.x == x && unit.y == y }
end

#find_by_direction_of(x, y, direction) ⇒ Object



42
43
44
45
46
# File 'lib/toy/unit_collection.rb', line 42

def find_by_direction_of(x, y, direction)
  raise Toy::UnitCollection::Error::DirectionError unless Toy::Direction::DIRECTION.include?(direction)

  send("find_#{direction}_of", x, y)
end

#find_by_object(object) ⇒ Object



22
23
24
# File 'lib/toy/unit_collection.rb', line 22

def find_by_object(object)
  @all.find { |unit| unit.object == object }
end

#find_east_of(x, y) ⇒ Object



30
31
32
# File 'lib/toy/unit_collection.rb', line 30

def find_east_of(x, y)
  @all.find { |unit| unit.x == x.succ && unit.y == y }
end

#find_north_of(x, y) ⇒ Object



26
27
28
# File 'lib/toy/unit_collection.rb', line 26

def find_north_of(x, y)
  @all.find { |unit| unit.x == x && unit.y == y.succ }
end

#find_south_of(x, y) ⇒ Object



34
35
36
# File 'lib/toy/unit_collection.rb', line 34

def find_south_of(x, y)
  @all.find { |unit| unit.x == x && unit.y == y.pred }
end

#find_west_of(x, y) ⇒ Object



38
39
40
# File 'lib/toy/unit_collection.rb', line 38

def find_west_of(x, y)
  @all.find { |unit| unit.x == x.pred && unit.y == y }
end