Class AbstractGame<S extends State, T>

java.lang.Object
game.console.AbstractGame<S,T>
Type Parameters:
S - represents the states of the game
T - represents the moves that can be applied to the states
Direct Known Subclasses:
Game, TwoPhaseMoveGame

public abstract class AbstractGame<S extends State, T> extends Object
Conducts a two-player game on the console. It uses a Function to convert a line read from the console to a move. If the line contains invalid input, the functional method of the Function should throw an IllegalArgumentException.

For example, to convert two space-separated integers to a Position object wrapping a row and a column index, the following Function object can be used:

var parser = new Function<String, Position>() {
    @Override
    public Position apply(String s) {
        s = s.trim();
        if (!s.matches("\\d+\\s+\\d+")) {
            throw new IllegalArgumentException();
        }
        var scanner = new Scanner(s);
        return new Position(scanner.nextInt(), scanner.nextInt());
    }
};
  • Field Details

    • console

      protected final Console console
    • state

      protected final S extends State state
    • parser

      protected final Function<String,T> parser
  • Constructor Details

    • AbstractGame

      public AbstractGame(S state, Function<String,T> parser)
      Creates a Game instance to conduct a two-player game on the console.
      Parameters:
      state - the state from which the game is started
      parser - a function that converts a line read from the console to a move
  • Method Details

    • start

      public void start()
      Starts the game.
    • makeMoveIfPossible

      protected abstract void makeMoveIfPossible(T move)
      Applies the move specified to the state of the game if the move is a legal one. In case of a legal move, it should also print the updated state on the console with the printState() method.
      Parameters:
      move - the move to be made
    • readMove

      protected Optional<T> readMove()
      Reads the next move to be made from the console.
      Returns:
      the next move to be made, or an empty Optional if an end of stream has been reached
    • printPrompt

      protected void printPrompt()
      Prints a prompt on the console to read the next move to be made.
    • printState

      protected void printState()
      Prints the state of the game on the console.
    • printStatus

      protected void printStatus()
      Prints the status of the game on the console.