summaryrefslogtreecommitdiff
path: root/nav.lua
blob: 62b84572ffbe801945d5564eb7ec9a1a6bacbf99 (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
-- orientation: east 1 x+, south 2 z+, west 3 x-, north 4 z-

local function turnTo(o1, o2)
	if o1 == o2 then
		return nil
	end

	if math.abs(o2 - o1) == 2 then
		turtle.turnLeft()
		turtle.turnLeft()
	elseif o2 - o1 == 1 or o2 - o1 == -3 then
		turtle.turnRight()
	else 
		turtle.turnLeft()
	end
end

local function moveX(x1, x2, o1)
	if x1 == x2 then
		return o1
	end

	local amount = x2 - x1
	local o2 = amount > 0 and 1 or 3
	turnTo(o1, o2)

	for ii = 1, math.abs(amount) do
		turtle.forward()
	end

	return o2
end

local function moveZ(z1, z2, o1)
	if z1 == z2 then
		return o1
	end

	local amount = z2 - z1
	local o2 = amount > 0 and 2 or 4
	turnTo(o1, o2)

	for ii = 1, math.abs(amount) do
		turtle.forward()
	end

	return o2
end

local function moveY(y1, y2)
	if y1 == y2 then
		return nil
	end

	local amount = y2 - y1
	for ii = 1, math.abs(amount) do
		if y2 > y1 then
			turtle.up()
		else
			turtle.down()
		end
	end
end

local function travel(x1, y1, z1, o1, x2, y2, z2, o2, safe_y, unsafe)
	unsafe = unsafe or false
	local dx = x2 - x1
	local dz = z2 - z1
	local move_safe = (not unsafe) and (dx ~= 0 or dz ~= 0)

	if move_safe then
		moveY(y1, safe_y)
	else
		moveY(y1, y2)
	end

	local newO = moveX(x1, x2, o1)
	newO = moveZ(z1, z2, newO)

	if move_safe then
		moveY(safe_y, y2)
	end

	turnTo(newO, o2)
end

return { turnTo = turnTo, moveX = moveX, moveZ = moveZ, moveY = moveY, travel = travel }