Skip to Content
Think Java, 2nd Edition
book

Think Java, 2nd Edition

by Allen B. Downey, Chris Mayfield
November 2019
Beginner
326 pages
6h 44m
English
O'Reilly Media, Inc.
Book available
Content preview from Think Java, 2nd Edition

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:

  1. If the ant is on a white cell, it turns to the right, makes the cell black, and moves forward.

  2. 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:

public class Langton {
    private GridCanvas grid;
    private int xpos;
    private int ypos;
    private int head; // 0=North, 1=East, 2=South, 3=West

    public Langton(int rows, int cols) {
        grid = new GridCanvas(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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Head First Java, 2nd Edition

Head First Java, 2nd Edition

Kathy Sierra, Bert Bates
Java in a Nutshell, 8th Edition

Java in a Nutshell, 8th Edition

Benjamin J. Evans, Jason Clark, David Flanagan
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan
The Well-Grounded Java Developer, Second Edition

The Well-Grounded Java Developer, Second Edition

Benjamin Evans, Martijn Verburg, Jason Clark

Publisher Resources

ISBN: 9781492072492Errata PageSupplemental Content