Class AbstractGame<S extends State, T>
java.lang.Object
game.console.AbstractGame<S,T>
- Type Parameters:
S
- represents the states of the gameT
- represents the moves that can be applied to the states
- Direct Known Subclasses:
Game
,TwoPhaseMoveGame
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 Summary
Fields -
Constructor Summary
ConstructorsConstructorDescriptionAbstractGame
(S state, Function<String, T> parser) Creates aGame
instance to conduct a two-player game on the console. -
Method Summary
Modifier and TypeMethodDescriptionprotected abstract void
makeMoveIfPossible
(T move) Applies the move specified to the state of the game if the move is a legal one.protected void
Prints a prompt on the console to read the next move to be made.protected void
Prints the state of the game on the console.protected void
Prints the status of the game on the console.readMove()
Reads the next move to be made from the console.void
start()
Starts the game.
-
Field Details
-
console
-
state
-
parser
-
-
Constructor Details
-
AbstractGame
-
-
Method Details
-
start
public void start()Starts the game. -
makeMoveIfPossible
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 theprintState()
method.- Parameters:
move
- the move to be made
-
readMove
-
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.
-