Chapter 16. Reusing Classes
In Chapter 15, we developed classes to implement Conway’s Game of Life. We can reuse the Cell and GridCanvas classes to implement other simulations. One of the most interesting zero-player games is Langton’s Ant, which models an “ant” that walks around a grid. The ant follows only two simple rules:
If the ant is on a white cell, it turns to the right, makes the cell black, and moves forward.
If the ant is on a black cell, it turns to the left, makes the cell white, and moves forward.
Because the rules are simple, you might expect the ant to do something simple, like make a square or repeat a simple pattern. But starting on a grid with all white cells, the ant makes more than 10,000 steps in a seemingly random pattern before it settles into a repeating loop of 104 steps. You can read more about it at: Wikipedia’s “Langton’s Ant” entry.
In this chapter, we present a solution to Langton’s Ant and use it to demonstrate more advanced object-oriented techniques.
Langton’s Ant
We begin by defining a Langton class that has a grid and information about the ant. The constructor takes the grid dimensions as parameters:
publicclassLangton{privateGridCanvasgrid;privateintxpos;privateintypos;privateinthead;// 0=North, 1=East, 2=South, 3=WestpublicLangton(introws,intcols){grid=newGridCanvas(rows,cols,10);xpos=rows/2;ypos=cols/2;head=0;}}
grid is a GridCanvas object, which represents the state of the cells. xpos and ypos are the ...