Class: Alchemist::Geography

Inherits:
Object show all
Defined in:
lib/alchemist-server/geography.rb

Defined Under Namespace

Classes: Loc

Instance Method Summary collapse

Constructor Details

#initialize(locations = {}) ⇒ Geography

Returns a new instance of Geography.



3
4
5
6
7
8
# File 'lib/alchemist-server/geography.rb', line 3

def initialize(locations = {})
  @locations = case locations
               when Hamster::Hash then locations
               else Hamster.hash locations
               end
end

Instance Method Details

#at(x, y) ⇒ Object



10
11
12
# File 'lib/alchemist-server/geography.rb', line 10

def at(x,y)
  locations[Loc[x,y]]
end

#dimensionsObject



53
54
55
56
57
58
# File 'lib/alchemist-server/geography.rb', line 53

def dimensions
  points = locations.keys
  xs,ys = points.map(&:x), points.map(&:y)

  [[xs.min, ys.min],[xs.max,ys.max]]
end

#put(x, y, c) ⇒ Object



18
19
20
21
22
23
24
25
26
# File 'lib/alchemist-server/geography.rb', line 18

def put(x,y,c)
  loc = Loc[x,y]

  if locations.key? loc
    raise "#{locations[loc]} is already at #{x},#{y}"
  end

  Geography.new locations.put(loc, c[0..1])
end

#string_around(x, y, range) ⇒ Object



28
29
30
31
32
33
# File 'lib/alchemist-server/geography.rb', line 28

def string_around(x,y,range)
  string_within x - range,
                y - range,
                x + range,
                y + range
end

#string_within(min_x, min_y, max_x, max_y) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/alchemist-server/geography.rb', line 40

def string_within(min_x, min_y, max_x, max_y)
  if min_x && min_y && max_x && max_y
    (min_y..max_y).map do |y|
      (min_x..max_x).map do |x|
        at(x, y) || ' '
      end.join('')
    end.join("\n")
  else
    ''
  end
end

#take(x, y) ⇒ Object



14
15
16
# File 'lib/alchemist-server/geography.rb', line 14

def take(x,y)
  Geography.new locations.delete(Loc[x,y])
end

#to_sObject



35
36
37
38
# File 'lib/alchemist-server/geography.rb', line 35

def to_s
  (min_x, min_y), (max_x, max_y) = dimensions
  string_within min_x, min_y, max_x, max_y
end