-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathant.lua
88 lines (68 loc) · 2.21 KB
/
ant.lua
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
88
local function f()
local ant = {}
ant.food_eaten = 0
ant.numLastFoodEaten = 200 -- which turn the last food item was eaten
ant.turn = 0
ant.direction = "east"
-- directions in the clockwise order
ant.directions = {
-- dir prev next
east = {"north", "south"},
south = {"east", "west"},
west = {"south", "north"},
north = {"west", "east"}}
-- Where to move depending to directions
ant.directions_position_changes = {
east = {x = 1, y = 0},
south = {x = 0, y = 1},
west = {x = -1, y = 0},
north = {x = 0, y = -1}
}
-- Spawn ant at (x, y) on the food field
function ant:spawn(x, y, food)
ant.x = x
ant.y = y
ant.food = food
end
-- Returns true if there is food exactly in front of ant looking direction
function ant:isLookingAtFood()
local x = ant.x + ant.directions_position_changes[ant.direction].x
local y = ant.y + ant.directions_position_changes[ant.direction].y
return ant.food:contains(x, y) and true or false
end
-- Move and forward
function ant:move()
ant.turn = ant.turn + 1
ant.x = ant.x + ant.directions_position_changes[ant.direction].x
ant.y = ant.y + ant.directions_position_changes[ant.direction].y
if ant.x < 1 then
ant.x = ant.x + CONFIG.FIELD_SIZE
end
if ant.y < 1 then
ant.y = ant.y + CONFIG.FIELD_SIZE
end
if ant.x > CONFIG.FIELD_SIZE then
ant.x = ant.x - CONFIG.FIELD_SIZE
end
if ant.y > CONFIG.FIELD_SIZE then
ant.y = ant.y - CONFIG.FIELD_SIZE
end
if ant.food:contains(ant.x, ant.y) then
ant.food_eaten = ant.food_eaten + 1
ant.food:remove(ant.x, ant.y)
ant.numLastFoodEaten = ant.turn
end
end
-- Rotate and to the left
function ant:turnLeft()
ant.turn = ant.turn + 1
ant.direction = ant.directions[ant.direction][1]
end
-- Rotate ant to the right
function ant:turnRight()
ant.turn = ant.turn + 1
ant.direction = ant.directions[ant.direction][2]
end
return ant
end
return f