2007 AP CSA FRQ 4: GameState - Complete Solution

2007 AP CSA FRQ 4: GameState

Topic: Inheritance & Game Simulation

Skills Tested: Subclass creation, polymorphism, game loop implementation, ArrayList with random

Curriculum Alignment: Unit 3 (Class Creation) (2025-2026 AP CSA)

Points: 9 | Time Estimate: ~22 minutes

Part (a)

Write the complete RandomPlayer class that extends Player and selects moves randomly.

Try It First! Attempt to solve this part before viewing the solution.

Solution

public class RandomPlayer extends Player
{
    public RandomPlayer(String name)
    {
        super(name);
    }
    
    public String getNextMove(GameState state)
    {
        ArrayList moves = state.getCurrentMoves();
        
        if (moves.size() == 0)
            return "no move";
        
        int index = (int) (Math.random() * moves.size());
        return moves.get(index);
    }
}

Part (b)

Write the play method that runs the game loop until completion, printing moves and announcing the winner.

Solution

public void play()
{
    System.out.println(state);
    
    while (!state.isGameOver())
    {
        Player player = state.getCurrentPlayer();
        String move = player.getNextMove(state);
        
        System.out.println(player.getName() + " " + move);
        state.makeMove(move);
    }
    
    Player winner = state.getWinner();
    
    if (winner != null)
        System.out.println(winner.getName() + " wins");
    else
        System.out.println("Game ends in a draw");
}

Key Concepts

Use super(name) to call parent constructor
Math.random() returns [0, 1), multiply by size for index
Cast to int truncates to get valid array index
Game loop continues while !isGameOver()

Common Mistakes to Avoid

Forgetting to call super(name) in constructor
Not handling empty moves list (size == 0)
Incorrect random index calculation
Not checking for null winner (draw case)

Official College Board Resources

About the Author: Tanner Crow is a certified AP Computer Science teacher with 11+ years of experience.

Last updated: January 2026

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]