1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
local NFRUITS = 10
local NWORMS = 20
local M = settings.get("monitor.worms", 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),
colour=2^math.random(0,14),
food=0, timer=0} 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)
if worm.timer > 0 then worm.timer = worm.timer -1 return end
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
worm.timer = 7
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
|