----- UTILITY FUNCTIONS -----

-- matrix rotation of point (x0,y0) through angle a with pivot (cx,cy)
function rotate_point(x0, y0, cx, cy, a)
  	return {x = cx + (x0-cx) * math.cos(a) - (y0-cy) * math.sin(a), y = cy + (x0-cx) * math.sin(a) + (y0-cy) * math.cos(a)}
end

-- pythagorean theorem
function dist(x1, y1, x2, y2)
	return math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1))
end

-- make sure a value is a Number
function mknumber(v)
    v = tonumber(v)
    if v ~= nil then return v else return 0 end
end

-- do nothing
function pass()
end

-- make sure # of seconds has two digits
function zero_pad(num)
    if num <= 9 then return "0"..num else return num end
end

-- count the total number of ships a team has
function count_ships(team)
    local total = 0
    local items = g2.search("planet OR fleet team:"..team)
    for i,item in ipairs(items) do
        if item.has_planet == true then
            total = total + item.ships_value
        else
            total = total + item.fleet_ships
        end
    end
    return total      
end

-- find a game object described by "query" using a evaluation function "eval" which may take extra parameters "params"
function find(query,eval,params)
    local res = g2.search(query)
    local best = nil; local value = nil
    for _i,item in pairs(res) do
        _value = eval(item,params)
        if _value ~= nil and (value == nil or _value > value) then
            best = item
            value = _value
        end
    end
    return best
end


