GameState is #4 from the from the 2007 AP Computer Science A Free Response problems.

https://secure-media.collegeboard.org/secure/ap/pdf/computer-science-a/ap-2007-computer-science-a-free-response-questions.pdf

Part (a) RandomPlayer class

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

See Class writing order for a technique to respond to AP CS FR that request an entire class.

See Inheritance and polymorphism for details including how to write subclasses.

Part (b) play method

public void play()
{
    System.out.println(state); // automatically runs toString
    
    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");
}

For more on working with Math.random() see Generating numbers with Math.random().

2007 AP CS Exam Free Response Solutions

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on GameState