Sprint View

2014 FRQ Q2 - Writing a Class

1 min read

FRQ Question 2

This question involves reasoning about the GridWorld case study. Reference materials are provided in the appendixes.

Write the complete Director class, including the zero-parameter constructor and any necessary instance variables and methods. Assume that the Color class has been imported.

Code Runner Challenge

GridWorld Style

View IPYNB Source
// CODE_RUNNER: GridWorld Style
public class Main {

    // Minimal stubs so the code runs in this environment
    static class Actor {
        private java.awt.Color color = java.awt.Color.RED;

        public java.awt.Color getColor() {
            return color;
        }

        public void setColor(java.awt.Color c) {
            color = c;
        }

        public void turnRight() {
            System.out.println("Actor turned right");
        }
    }

    static class Rock extends Actor {
        public java.util.ArrayList<Actor> getNeighbors() {
            // For demonstration, return a couple of dummy neighbors
            java.util.ArrayList<Actor> neighbors = new java.util.ArrayList<>();
            neighbors.add(new Actor());
            neighbors.add(new Actor());
            return neighbors;
        }
    }

    // Director class
    static class Director extends Rock {

        /** Constructs a Director with an initial color of RED */
        public Director() {
            setColor(java.awt.Color.RED);
        }

        /** Alternates color and turns neighbors right if color is GREEN */
        public void act() {
            if (getColor().equals(java.awt.Color.GREEN)) {
                turnNeighborsRight();
                setColor(java.awt.Color.RED);
            } else {
                setColor(java.awt.Color.GREEN);
            }
        }

        /** Turns all neighboring actors 90 degrees to the right */
        private void turnNeighborsRight() {
            for (Actor a : getNeighbors()) {
                a.turnRight();
            }
        }
    }

    // Main method for testing
    public static void main(String[] args) {
        Director d = new Director();
        System.out.println("Initial color: " + d.getColor());
        d.act();
        System.out.println("After first act: " + d.getColor());
        d.act();
        System.out.println("After second act: " + d.getColor());
    }
}

Main.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Course Timeline