summaryrefslogtreecommitdiff
path: root/worms.lua
blob: af4160a854ca7c82187019073af5ead10500d4c5 (plain)
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
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 worm = {x=5,y=5,food=0}

-- 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(colors.green)
	M.setCursorPos(worm.x,worm.y)
	M.write("@")
end

while true do
	tick_worm(worm)
	M.setBackgroundColor(colors.black)  M.clear()
	draw_fruits()
	draw_worm(worm)
	os.sleep(0)
end