Addepar requests that internship applicants program an ant AI in Java. This was my first experience programming an AI, so I stuck with classic techniques like state machines and A* pathfinding to be sure I ended up with something functional. In this article, I’ll be documenting the challenge, my strategy, and possible improvements. I’ll also include a sneak-peek of my newest game project.
Overall, the AI functions pretty well – you can clearly see the ants are following a strategy. The limitations on what an ant can know about it’s environment made for a fun programming challenge.
If I had time to improve the AI, I’d probably look at optimizing how the ants balance known food sources versus discovery – This could be done by building a test harness that ran a couple days worth of tests and recorded the results depending on the “discovery constant.” This would allow a host of other optimizations by allowing me to test answering other questions like “Does sitting on the anthill for a certain number of ticks improve knowledge and in turn food acquisition?” This testing harness would probably provide the most bang-for-my-buck coding wise.
In the future, I’d like to try a bottom up approach to developing and see if that improves my ability to write more loosely coupled classes. I’m not terribly happy with the code organization. Looking into extending Java’s built-in data structures would probably improve code readability as well. Without further adieu, here is the code:
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451 import ants.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
public class MyAnt implements Ant{
private Brain MyBrain = new Brain();
public Action getAction(Surroundings surroundings){
// Always load up my brain with new information.
// Knowledge is Power!
Surroundings s = surroundings;
MyBrain.loadCurrent(s.getCurrentTile().getAmountOfFood());
MyBrain.loadSurroundings(s.getTile(Direction.NORTH), s.getTile(Direction.EAST), s.getTile(Direction.WEST), s.getTile(Direction.SOUTH));
return MyBrain.getAction();
}
public byte[] send(){
// Sends a byte[] of a list of integers in the following order
// x, y, food, frontier? ... and so on
try {
return MyBrain.dataOutput();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public void receive(byte[] data){
// Recieves a byte[] of a list of Integers in x, y, food, frontier? ... and so on order
// and sends it to the brain for processing.
try {
MyBrain.dataInput(data);
} catch (IOException e) {
e.printStackTrace();
}
}
// How a relative coordinate is stored in my HashMap
class Cell {
public Integer food;
public Integer x;
public Integer y;
public Integer f, g, h;
public Cell parent;
public Cell(Integer x, Integer y, Integer food) {
this.food = food;
this.x = x;
this.y = y;
this.f = 0;
this.g = 0;
this.h = 0;
this.parent = null;
}
public int hashCode() {
String s = x + ",,," + y;
return s.hashCode();
}
public String key() {
String k = x + "," + y;
return k;
}
}
class Map {
String antHill;
HashSet food;
HashSet frontier;
HashMap mapIndex;
Integer x,y;
public Map() {
this.x = 0;
this.y = 0;
this.antHill = xyToS(0, 0);
this.mapIndex = new HashMap();
this.mapIndex.put(antHill, new Cell(0, 0, 0));
this.food = new HashSet();
this.frontier = new HashSet();
}
// Gives a key for the current coordinates, offset by supplied xOff and yOff
// Offset of 0,0 would give the current coordinate's key
private String xyToS(Integer xOff, Integer yOff) {
return ((x+xOff) + "," + (y+yOff));
}
// Updates or creates a cell in our Ant's HashMap
private void updateSurrounding(String key, Tile t, Integer xx, Integer yy) {
if (mapIndex.get(key) != null) {
// Update the HashMap's cell
Cell c = mapIndex.remove(key);
c.food = t.getAmountOfFood();
if (c.food <= 0)
food.remove(key);
mapIndex.put(key, c);
} else {
// Create a new cell for the hashmap
if (t.isTravelable()) {
Cell c = new Cell(xx, yy, t.getAmountOfFood());
mapIndex.put(key, c);
frontier.add(key);
if (c.food > 0)
food.add(key);
}
}
}
// Takes as input all NEWS tiles and then adds them to your ant's internal map
public void setSurroundings(Tile N, Tile E, Tile W, Tile S) {
// NEWS Updates
updateSurrounding(xyToS(0, 1), N, x, y+1);
updateSurrounding(xyToS(1, 0), E, x+1, y);
updateSurrounding(xyToS(-1, 0), W, x-1, y);
updateSurrounding(xyToS(0, -1), S, x, y-1);
}
// Takes as input the current cell's food count and updates the ant's map
public void setCurrent(Integer food) {
Cell c = getCurrent();
if (food <= 0)
this.food.remove(c);
c.food = food;
}
// Returns true if we are standing on food
public Boolean foodHere() {
return mapIndex.get(xyToS(0, 0)).food > 0;
}
// Returns true if we are standing on the anthill
public Boolean homeHere() {
return antHill.equals(xyToS(0, 0));
}
// Gets the nearest cell from a HashSet of cells
private Cell closestTarget(HashSet m) {
Cell best = null;
Integer distance = Integer.MAX_VALUE;
if (!m.isEmpty()) {
Cell cur = getCurrent();
for (String key : m) {
if (estimateDistance(cur, mapIndex.get(key)) < distance) {
best = mapIndex.get(key);
distance = estimateDistance(cur, best);
}
}
}
return best;
}
// Returns the cell our ant should move towards.
// Goes to the closest food source, unless an undiscovered cell is less than half
// the distance.
public Cell getBestTarget() {
// Find closest food and frontier cells
Cell bestFoodCell = closestTarget(food);
Cell bestFrontierCell = closestTarget(frontier);
if (estimateDistance(getCurrent(), bestFrontierCell)*2 <= estimateDistance(getCurrent(), bestFoodCell))
return bestFrontierCell;
else
return bestFoodCell;
}
// Returns the current Cell we are standing on
public Cell getCurrent() {
return mapIndex.get(xyToS(0, 0));
}
// Returns the anthill cell
public Cell getHome() {
return mapIndex.get(antHill);
}
// Based on a neighboring coordinate destination, this returns which direction we need
// to move to get there.
public Direction move(String key) {
String[] k = key.split(",");
Integer kx = Integer.parseInt(k[0]);
Integer ky = Integer.parseInt(k[1]);
frontier.remove(key);
if (y+1 == ky) {
this.y += 1;
return Direction.NORTH;
}
else if (x+1 == kx) {
this.x += 1;
return Direction.EAST;
}
else if (x-1 == kx) {
this.x -= 1;
return Direction.WEST;
}
else {
this.y -= 1;
return Direction.SOUTH;
}
}
// Returns an ArrayList of all known neighboring cells
public ArrayList getNeighbors(String key) {
String[] k = key.split(",");
Integer x = Integer.parseInt(k[0]);
Integer y = Integer.parseInt(k[1]);
ArrayList ret = new ArrayList();
if (mapIndex.get(x+","+(y+1)) != null)
ret.add(mapIndex.get(x+","+(y+1)));
if (mapIndex.get((x+1)+","+y) != null)
ret.add(mapIndex.get((x+1)+","+y));
if (mapIndex.get((x-1)+","+y) != null)
ret.add(mapIndex.get((x-1)+","+y));
if (mapIndex.get(x+","+(y-1)) != null)
ret.add(mapIndex.get(x+","+(y-1)));
return ret;
}
public Integer estimateDistance(Cell cell1, Cell cell2) {
if (cell1 == null || cell2 == null)
return Integer.MAX_VALUE;
return Math.abs(cell1.x - cell2.x) + Math.abs(cell1.y - cell2.y);
}
// Updates a cell's food if it's less than what is already in our map
private void updateCell(String key, Integer food) {
Cell c = mapIndex.get(key);
c.food = Math.min(food, c.food);
mapIndex.put(key, c);
}
// Merge list of Integers into our ant's map
// List: x, y, food, frontier? ... and so on
public void mergeQuads(ArrayList quads) {
Iterator itr = quads.iterator();
while(itr.hasNext()) {
Integer x = itr.next();
Integer y = itr.next();
Integer food = itr.next();
Boolean frontier = (1 == itr.next());
String k = x+","+y;
// If we already have the cell, update it.
// Otherwise add a new cell and put it in the appropriate frontier or food list
if(mapIndex.containsKey(k)) {
updateCell(k, food);
if (food <= 0)
this.food.remove(k);
} else {
mapIndex.put(k, new Cell(x, y, food));
if (food > 0)
this.food.add(k);
if (frontier)
this.frontier.add(k);
}
}
}
}
enum STATE { Exploring, GoingHome }
class Brain {
Map map;
STATE state;
LinkedList route;
public Brain() {
map = new Map();
state = STATE.Exploring;
route = new LinkedList();
}
// Takes a byte[] that's composed of an ArrayList and
// inputs it into our ant's brain.
// Integer Format: x, y, food, frontier? ... and so on
public void dataInput(byte[] in) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(in);
DataInputStream inp = new DataInputStream(bais);
ArrayList quads = new ArrayList();
while (inp.available() > 0) {
Integer element = Integer.parseInt(inp.readUTF());
quads.add(element);
}
map.mergeQuads(quads);
}
// Outputs an ArrayList as a byte[] to send
// to another ant.
// Format: x, y, food, frontier? ... and so on
public byte[] dataOutput() throws IOException {
ArrayList quads = new ArrayList();
for (Cell c : map.mapIndex.values()) {
quads.add(c.x);
quads.add(c.y);
quads.add(c.food);
if(map.frontier.contains(c.key()))
quads.add(1);
else
quads.add(0);
}
// write to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos);
for (Integer element : quads) {
out.writeUTF(element.toString());
}
byte[] bytes = baos.toByteArray();
return bytes;
}
// Load the current tile's data into our brain
public void loadCurrent(Integer food) {
map.setCurrent(food);
}
// Load our neighboring tile's data into our brain
public void loadSurroundings(Tile N, Tile E, Tile W, Tile S) {
// load into map
map.setSurroundings(N, E, W, S);
}
// Main Strategy Center
// 2 States - Exploration and GoingHome
// If an ant is GoingHome, it means the ant has collected food to drop off.
// After dropping off, the ant's state is set to Exploring.
// When exploring, the ant moves towards known food sources or undiscovered areas
// (going towards food if its less than twice as far as the nearest undiscovered area).
// If it finds food on the way, it picks it up and head's home otherwise it gets to its destination,
// picking up food if it's still there or else it finds a new best destination.
//
// Routes are created with the A* algorithm
public Action getAction() {
if (state == STATE.GoingHome) {
if (route.isEmpty() && !map.homeHere())
route = aStar(map.getCurrent(), map.getHome());
// 1. Drop off food if we're home
// 2. Otherwise continue heading home
if (map.homeHere()) {
state = STATE.Exploring;
return Action.DROP_OFF;
} else {
// Follow route home
return Action.move(map.move(route.removeLast()));
}
}
else if (state == STATE.Exploring)
{
// 1. Pickup food if possible
// 2. Explore with food target taking precedence over exploring
if (map.foodHere() && !map.homeHere()) {
// Pick up, set state to picking up (save prev val)
route.clear();
state = STATE.GoingHome;
return Action.GATHER;
} else {
// frontier/food explore
if (route.isEmpty())
route = aStar(map.getCurrent(), map.getBestTarget());
return Action.move(map.move(route.removeLast()));
}
}
return Action.move(Direction.SOUTH);
}
// Returns a LinkedList with the key of the next tile to move to
// at the end of the list.
public LinkedList aStar(Cell start, Cell goal) {
Set open = new HashSet();
Set closed = new HashSet();
start.g = 0;
start.h = estimateDistance(start, goal);
start.f = start.h;
open.add(start);
while (true) {
Cell current = null;
if (open.size() == 0) {
throw new RuntimeException("no route");
}
for (Cell cell : open) {
if (current == null || cell.f < cell.f) {
current = cell;
}
}
if (current == goal) {
break;
}
open.remove(current);
closed.add(current);
for (Cell neighbor : map.getNeighbors(current.key())) {
if (neighbor != null) {
int nextG = current.g + 1; // flat neighbor cost of 1
if (nextG < neighbor.g) {
open.remove(neighbor);
closed.remove(neighbor);
}
if (!open.contains(neighbor) && !closed.contains(neighbor)) {
neighbor.g = nextG;
neighbor.h = estimateDistance(neighbor, goal);
neighbor.f = neighbor.g + neighbor.h;
neighbor.parent = current;
open.add(neighbor);
}
}
}
}
// Finding my way back
LinkedList route = new LinkedList();
Cell current = goal;
while (current.parent != null) {
route.add(current.key());
Cell t = current.parent;
current.parent = null;
current = t;
}
return route;
}
public Integer estimateDistance(Cell cell1, Cell cell2) {
if (cell1 == null || cell2 == null)
return Integer.MAX_VALUE;
return Math.abs(cell1.x - cell2.x) + Math.abs(cell1.y - cell2.y);
}
}
}
Future posts will include my experiences with Microsoft’s Kinect for Windows SDK, programming Koans for learning languages, and my newest project titled Blob-Bomb.
Key Features: