-- Mini Terraria for CC:Tweaked

local w,h = term.getSize()

local world = {}
local px = math.floor(w/2)
local py = 5

local inv = {
 dirt = 0,
 stone = 0,
 ore = 0
}

for y=1,h do
 world[y] = {}

 for x=1,w*4 do
  if y < 8 then
   world[y][x] = " "
  elseif y == 8 then
   world[y][x] = "="
  elseif y < 13 then
   world[y][x] = "#"
  else
   if math.random(1,10) == 1 then
    world[y][x] = "*"
   else
    world[y][x] = "O"
   end
  end
 end
end

local camX = 1

local function draw()
 term.clear()

 camX = math.max(1, math.floor(px - w/2))

 for sy=1,h-2 do
  for sx=1,w do
   local wx = sx + camX - 1

   if world[sy] and world[sy][wx] then
    term.setCursorPos(sx,sy)
    write(world[sy][wx])
   end
  end
 end

 local screenX = px - camX + 1

 term.setCursorPos(screenX,py)
 write("@")

 term.setCursorPos(1,h-1)
 write("D:"..inv.dirt..
       " S:"..inv.stone..
       " O:"..inv.ore)

 term.setCursorPos(1,h)
 write("WASD Move Arrows Mine Q Quit")
end

local function mine(dx,dy)
 local x = px + dx
 local y = py + dy

 if not world[y] then return end
 if not world[y][x] then return end

 local b = world[y][x]

 if b == "#" or b == "=" then
  inv.dirt = inv.dirt + 1
  world[y][x] = " "
 end

 if b == "O" then
  inv.stone = inv.stone + 1
  world[y][x] = " "
 end

 if b == "*" then
  inv.ore = inv.ore + 1
  world[y][x] = " "
 end
end

while true do
 draw()

 local e,key = os.pullEvent("key")

 if key == keys.q then
  break
 end

 if key == keys.a then
  px = math.max(1, px - 1)
 end

 if key == keys.d then
  px = px + 1
 end

 if key == keys.w then
  py = math.max(1, py - 1)
 end

 if key == keys.s then
  py = math.min(h-2, py + 1)
 end

 if key == keys.left then
  mine(-1,0)
 end

 if key == keys.right then
  mine(1,0)
 end

 if key == keys.up then
  mine(0,-1)
 end

 if key == keys.down then
  mine(0,1)
 end
end

term.clear()
term.setCursorPos(1,1)
print("Game Over")
print("Ore Collected: "..inv.ore)