--------------------------------------------------------------
-- Checks whether the tile given by its position is in the map
--------------------------------------------------------------
function tileIsInMap(tileX, tileY)
   return (tileX >= 0 and tileY >= 0
         and tileX < boombastic.numTilesX
         and tileY < boombastic.numTilesY)
end


-------------------------------------------------------------------
-- Checks whether the tile at the given position should be blocking
-- (i.e. a rock, a bomb, a wall, ...).
-- It is used by the tank and the rocket for collision detection
-------------------------------------------------------------------
function tileIsBlocking(tileX, tileY)

   -- Is the position beyond the bounds of the map?
   if (not tileIsInMap(tileX, tileY)) then
      return true
   end
   
   -- Is the position a blocking tile of the map?
   if (boombastic.map:tileIsBlock(tileX, tileY)) then
      return true
   end
   
   -- Is the position a rock?
   if (boombastic.rocks:tileIsRock(tileX, tileY)) then
      return true
   end
   
   -- Is the position a bomb?
   if (boombastic.bombs:tileIsBomb(tileX, tileY)) then
      return true
   end
   
   return false
end


-------------------------------------------
-- Gets the list of tanks at the given tile
-------------------------------------------
function getTanksAtTile(tileX, tileY)
   local tanks = {}
   
   for k, tank in ipairs(boombastic.tanks) do
      local tankTileX, tankTileY = convertPixelsToTile(tank.x, tank.y)
      if (tank:isAlive() and tankTileX == tileX and tankTileY == tileY) then
         table.insert(tanks, tank)
      end
   end
   
   return tanks
end


----------------------------------------------
-- Converts pixels into the position of a tile
----------------------------------------------
function convertPixelsToTile(x, y)
   local tileX = math.floor(x / boombastic.tileSize)
   local tileY = math.floor(y / boombastic.tileSize)
   return tileX, tileY
end


----------------------------------------------
-- Converts the position of a tile into pixels
----------------------------------------------
function convertTileToPixels(tileX, tileY)
   local x = math.floor((tileX + 0.5) * boombastic.tileSize)
   local y = math.floor((tileY + 0.5) * boombastic.tileSize)
   return x, y
end
