Module: Berlin::AI::Map::Internal::ClassMethods

Defined in:
lib/ai/map_internal.rb

Instance Method Summary collapse

Instance Method Details

#parse(data) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/ai/map_internal.rb', line 6

def parse(data)
  map = Map.new

  # Map details
  map.directed = data['directed']
  map.player_id = data['player_id']

  # Node types
  types = data['types'].each.with_object({}) do |type, types|
    types[type['name']] = type
  end
  
  # Let's parse data['nodes'] and register all nodes we can find.
  # We'll keep track of them in @nodes so we can find them later.
  # At this step (Map creation...), we still don't know who possess
  # the node and how many soldiers there is. We'll get back to that later.
  # map['nodes'] => [{:id => STRING}, ...]
  data['nodes'].each do |node|
    node_data = node.merge(types[node['type']]).merge('map' => map)
    map.nodes_hash[node['id']] = Berlin::AI::Node.parse(node_data)
  end

  # Same thing here, with paths.
  # map['paths'] => [{:from => INTEGER, :to => INTEGER}, ...]
  data['paths'].each do |path|
    map.nodes_hash[path['from']].link_to(map.nodes_hash[path['to']])

    # Don't forget! If the map is not directed, we must create the reverse link!
    map.nodes_hash[path['to']].link_to(map.nodes_hash[path['from']]) unless map.directed?
  end

  # and... return the newly created map
  map
end