local w,h=term.getSize()
local px,py=math.floor(w/2),8
local world={}
local inv={dirt=0,stone=0,ore=0}

for y=1,h do
 world[y]={}
 for x=1,w do
  if y<10 then world[y][x]="air"
  elseif y==10 then world[y][x]="grass"
  elseif y<15 then world[y][x]="dirt"
  else
   world[y][x]=math.random(1,12)==1 and "ore" or "stone"
  end
 end
end

local function blockChar(b)
 if b=="air" then return " " end
 if b=="grass" then return "=" end
 if b=="dirt" then return "#" end
 if b=="stone" then return "O" end
 if b=="ore" then return "*" end
 return "?"
end

local function blockColor(b)
 if b=="grass" then return colors.green end
 if b=="dirt" then return colors.brown end
 if b=="stone" then return colors.gray end
 if b=="ore" then return colors.yellow end
 return colors.black
end

local function draw()
 term.setBackgroundColor(colors.black)
 term.clear()
 for y=1,h-2 do
  for x=1,w do
   local b=world[y][x]
   term.setCursorPos(x,y)
   term.setTextColor(blockColor(b))
   write(blockChar(b))
  end
 end

 term.setCursorPos(px,py)
 term.setTextColor(colors.cyan)
 write("@")

 term.setCursorPos(1,h-1)
 term.setTextColor(colors.white)
 write("WASD move | Arrows mine | Q quit")

 term.setCursorPos(1,h)
 write("Dirt:"..inv.dirt.." Stone:"..inv.stone.." Ore:"..inv.ore)
end

local function mine(dx,dy)
 local x,y=px+dx,py+dy
 if x<1 or x>w or y<1 or y>h-2 then return end
 local b=world[y][x]
 if b~="air" then
  if b=="grass" then inv.dirt=inv.dirt+1
  elseif b=="dirt" then inv.dirt=inv.dirt+1
  elseif b=="stone" then inv.stone=inv.stone+1
  elseif b=="ore" then inv.ore=inv.ore+1
  end
  world[y][x]="air"
 end
end

local function move(dx,dy)
 local x,y=px+dx,py+dy
 if x<1 or x>w or y<1 or y>h-2 then return end
 if world[y][x]=="air" then
  px,py=x,y
 end
end

while true do
 draw()
 local e,k=os.pullEvent("key")

 if k==keys.q then break end

 if k==keys.w then move(0,-1) end
 if k==keys.s then move(0,1) end
 if k==keys.a then move(-1,0) end
 if k==keys.d then move(1,0) end

 if k==keys.up then mine(0,-1) end
 if k==keys.down then mine(0,1) end
 if k==keys.left then mine(-1,0) end
 if k==keys.right then mine(1,0) end
end

term.clear()
term.setCursorPos(1,1)
print("Thanks for playing!")