local NFRUITS = 10 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] = new_fruit() end local function new_worm() return {x=math.random(W),y=math.random(H),food=0,colour=2^math.random(0,14)} end local worms = {} for i=1,NWORMS do worms[i] = new_worm() end -- 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.setTextColor(worm.colour) M.setCursorPos(worm.x,worm.y) M.write("@") end while true do for _,w in ipairs(worms) do tick_worm(w) end M.setBackgroundColor(colors.black) M.clear() draw_fruits() for _,w in ipairs(worms) do draw_worm(w) end os.sleep(0) end