module Berlin::AI::Map::Internal::ClassMethods

Public Instance Methods

parse(data) click to toggle source
# 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