require 'string.rb'

module Consts
  AMBUSH_FL  = 1
  COAST_FL   = 2
  DANGER_FL  = 4
  BASE_FL    = 8
  MY_PACK_FL = 16
  ROBOT_FL   = 32
  DEST_FL    = 64
  DROP_FL    = 128
  WATER_ID   = 254
  BLOCK_ID   = 255
  TARGET_ID  = 0
end

include Consts

def log(*x)
  puts *x
end

def ambush_pos(p)
  $sp.check_info(p,AMBUSH_FL);
end
def cost_pos(p)
  $sp.check_info(p,COAST_FL);
end
def danger_pos(p)
  $sp.check_info(p,DANGER_FL);
end
def base_pos(p)
  $sp.check_info(p,BASE_FL);
end
def my_pack_pos(p)
  $sp.check_info(p,MY_PACK_FL);
end
def robot_pos(p)
  $sp.check_info(p,ROBOT_FL);
end
def drop_pos(p)
  $sp.check_info(p,DROP_FL);
end
def water_pos(p)
  $sp.check_info(p,WATER_FL);
end
def block_pos(p)
  $sp.check_info(p,BLOCK_FL);
end
def target_pos(p)
  $sp.check_info(p,TARGET_FL);
end


def package(id)
  $cur_packages[id]
end

def to_pos(x,y)
  x+y*$width
end

def from_pos(pos)
  [pos%$width,pos/$width]
end

def pos_x(pos)
  pos % $w
end

def pos_y(pos)
  pos / $w
end

def near(pos)
  yield pos-1
  yield pos+1
  yield pos-$w
  yield pos+$w
end

def near_or(pos)
  (yield pos-1) || 
    (yield pos+1) ||
    (yield pos-$w) ||
    (yield pos+$w)
end

def near_and(pos)
  (yield pos-1) && 
    (yield pos+1) &&
    (yield pos-$w) &&
    (yield pos+$w)
end

def near_info(pos)
  r= $sp
  r.info(pos-1) |
    r.info(pos+1) |
    r.info(pos-$w) |
    r.info(pos+$w) 
end

def pos_to_s(pos)
  "(#{pos_x(pos)},#{pos_y(pos)})"
end

$destinations = {}

class Package
  attr_reader   :id, :weight, :dest

  def initialize(id,xdest,ydest,weight)
    @dest = to_pos(xdest,ydest)
    $destinations[@dest] = true
    @id, @weight = id,weight
  end

  # Return true if the package is arrived
  def drop(pos)
    if pos == @dest
      true
    else
      $world.set_info(@pos,Consts::MY_PACK)
      false
    end
  end
  
  def xdest
    pos_x(@dest)
  end

  def ydest
    pos_y(@dest)
  end
end



