Commits

Vincent Fiack committed be57faf

tutorial 1: avoid collisions

Comments (0)

Files changed (1)

src/main/java/fr/vfiack/ants/AntsBot.java

 package fr.vfiack.ants;
 
+import java.util.HashSet;
+import java.util.Set;
+
 import org.aichallenge.Aim;
 import org.aichallenge.Ants;
 import org.aichallenge.Bot;
 import org.aichallenge.Tile;
 
 public class AntsBot extends Bot {
+	/*
+	The doMoveDirection function takes an ant location (a Tile object) 
+	and a direction (an Aim object of N, E, S or W) and tries to perform the move. 
+	This function is located outside the doTurn function, so we need to pass in our 
+	reserved tiles HashSet. We are using some predefined functions from the starter bot 
+	to help us:
 
-    /**
-     * For every ant check every direction in fixed order (N, E, S, W) and move it if the tile is
-     * passable.
-     */
-    @Override
-    public void doTurn() {
-        Ants ants = getAnts();
-        
-        for (Tile myAnt : ants.getMyAnts()) {
-            for (Aim direction : Aim.values()) {
-                if (ants.getIlk(myAnt, direction).isPassable()) {
-                    ants.issueOrder(myAnt, direction);
-                    break;
-                }
-            }
-        }
-    }
-}
+    ants.getTile(Tile, Aim) takes a location (Tile object) and a direction (Aim object) 
+    and returns the destination location (Tile object) for us. 
+    It takes care of the map wrapping around so we don't have to worry about it.
+
+    ants.getIlk(Tile) takes a location (Tile object) and returns the Ilk 
+    (a fancy word for type or kind). We then call the isUnoccupied() function of the 
+    Ilk object to see if it is free to move to.
+
+    Ilk.isUnoccupied takes a location and let's us know if we can move there. 
+    This is better than the previous Ilk.isPassable because it will not allow us 
+    to step on food or other ants.
+
+	The reservedTiles HashSet is used to track what moves we have issued. 
+	In the if statement we have !reservedTiles.contains(newLoc) 
+	which will check the HashSet for us and help prevent collisions. 	
+	*/
+	public boolean doMoveDirection(Set<Tile> reservedTiles, Tile antLoc, Aim direction) {
+		Ants ants = getAnts();
+		// Track all moves, prevent collisions
+		Tile newLoc = ants.getTile(antLoc, direction);
+		if (ants.getIlk(newLoc).isUnoccupied() && !reservedTiles.contains(newLoc)) {
+			ants.issueOrder(antLoc, direction);
+			reservedTiles.add(newLoc);
+			return true;
+		} else {
+			return false;
+		}
+	}
+
+	@Override
+	public void doTurn() {
+		Set<Tile> reservedTiles = new HashSet<Tile>();
+		Ants ants = getAnts();
+		for (Tile myAnt : ants.getMyAnts()) {
+			for (Aim direction : Aim.values()) {
+				if (doMoveDirection(reservedTiles, myAnt, direction)) {
+					break;
+				}
+			}
+		}
+	}
+}