From ed534cf41f762e5d614ad46e6de7b615da8adc6c Mon Sep 17 00:00:00 2001 From: rebecca Date: Sun, 1 Mar 2026 10:00:37 +0000 Subject: worms --- worms.lua | 45 +++++++++++++++++++++++++++++++++++++-------- 1 file changed, 37 insertions(+), 8 deletions(-) (limited to 'worms.lua') diff --git a/worms.lua b/worms.lua index af0b53e..5e3c11c 100644 --- a/worms.lua +++ b/worms.lua @@ -5,23 +5,52 @@ local NWORMS = 20 local M = peripheral.find"monitor" local W,H = M.getSize() +local function new_fruit() return {math.random(W), math.random(H)} end + local fruits = {} -for i=1,NFRUITS do - fruits[i] = {math.random(W),math.random(H)} -end +for i=1,NFRUITS do fruits[i] = new_fruit() end +local worm = {x=5,y=5} -local function draw() - M.setBackgroundColor(colors.black) - M.clear() - for i,f in ipairs(fruits) do +-- lsup +local function metricd(dx,dy) return math.max(math.abs(dx),math.abs(dy)) end +local function metric(x0,y0,x1,y1) return metricd(x0-x1,y0-y1) end + +local function draw_fruits() for i,f in ipairs(fruits) do M.setCursorPos(f[1],f[2]) M.setBackgroundColor(colors.red) M.write" " +end end + +local function tick_worm(worm) + local x,y = worm.x, worm.y + for i,f in ipairs(fruits) do f.dist = metric(x,y, f[1],f[2]) end + table.sort(fruits, function(f,g) return f.dist < g.dist end) + local target = fruits[1] + if target.dist == 0 then + table.remove(fruits, 1) + table.insert(fruits, new_fruit()) + worm.food = worm.food + 1 + else + local dx,dy = 0,0 + local tx,ty = target[1]-x,target[2]-y + if tx<0 then dx=-1 elseif tx>0 then dx=1 end + if ty<0 then dy=-1 elseif ty>0 then dy=1 end + worm.x = x+dx worm.y = y+dy end end +local function draw_worm(worm) + M.setBackgroundColor(colors.black) + M.setForegroundColor(colors.green) + M.setCursorPos(worm.x,worm.y) + M.write("@") +end + while true do - draw() + tick_worm(worm) + M.setBackgroundColor(colors.black) M.clear() + draw_fruits() + draw_worm(worm) os.sleep(0) end -- cgit v1.2.3