summaryrefslogtreecommitdiff
path: root/worms.lua
diff options
context:
space:
mode:
Diffstat (limited to 'worms.lua')
-rw-r--r--worms.lua45
1 files changed, 37 insertions, 8 deletions
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