 class MapUnit2DForUserTank extends MapUnit2DForTank
   defend: (missile, destroy_area) ->
     return 0 if missile.parent is @model
-    @max_depend_point
+    @max_depend_point - 1
 
 class MapUnit2DForEnemyTank extends MapUnit2DForTank
   defend: (missile, destroy_area) ->

  defend: (missile, destroy_area) -> 0

class MapUnit2DForBrick extends MapUnit2D
  current_frames: () -> [{x: 0, y: 240}]
  defend: (missile, destroy_area) ->
    # cut self into pieces

  delete_map_unit: (map_unit) ->
    @map_units = _.without(@map_units, map_unit)

  init_vertexes: () ->
    vertexes = []
    [x1, x2] = [0, @default_width]
    while x2 <= @max_x
      column_vertexes = []
      [y1, y2] = [0, @default_height]
      while y2 <= @max_y
        column_vertexes.push(new MapArea2DVertex(x1, y1, x2, y2))
        [y1, y2] = [y1 + @default_height/4, y2 + @default_height/4]
      vertexes.push(column_vertexes)
      [x1, x2] = [x1 + @default_width/4, x2 + @default_width/4]
    for x in _.range(0, @vertexes_columns)
      for y in _.range(0, @vertexes_rows)
        for sib in [{x: x, y: y - 1}, {x: x + 1, y: y}, {x: x, y: y + 1}, {x: x - 1, y: y}]
          vertexes[x][y].init_vxy(x, y)
          if 0 <= sib.x < @vertexes_columns and 0 <= sib.y < @vertexes_rows
            vertexes[x][y].add_sibling(vertexes[sib.x][sib.y])
    vertexes

  vertexes_at: (area) ->
    candidate_points = [
      {x: area.x1, y: area.y1},
      {x: area.x2 - 1, y: area.y1},
      {x: area.x2 - 1, y: area.y2 - 1}
      {x: area.x1, y: area.y2 - 1},
    ]
    vertexes = []
    for point in candidate_points
      vertexes.push @vertexes[parseInt(point.x / @default_width)][parseInt(point.y / @default_height)]
    _.uniq(vertexes)

  weight: (tank, vertex1, vertex2) ->
    sub_area = _.first(vertex1.sub(vertex2))
    terrain_units = _.select(@units_at(sub_area), (unit) -> unit.model instanceof Terrain)
    return 1 if _.isEmpty(terrain_units)
    _.first(terrain_units).weight(tank) * @default_width * @default_height / (sub_area.width() * sub_area.height())

class MapUnit2D
  layer: 10

