-
Notifications
You must be signed in to change notification settings - Fork 0
Java interface
SlaynAndKorpil edited this page Aug 23, 2019
·
2 revisions
An example implementation of the I/O interface in the framework via java:
package test.test;
import chess.framework.FileOperationError.FileNotFoundError;
import chess.framework.FileOperationError.FileOperationError;
import chess.framework.Input.Input;
import chess.framework.*;
import chess.framework.javaInterfacing.JChessIO;
import chess.framework.javaInterfacing.Reactions.*;
import static chess.framework.javaInterfacing.JInput.*;
public class TestImpl extends JChessIO {
public TestImpl() {
super();
// adding reactions to events; order like with a stack (adding to top,
// working from top to bottom, ie. last added gets handled first)
addReaction(new ReactToAll(event -> System.out.println("catch all: " + event.toString())));
addReaction(new ShowEndedReaction(event -> {
String result = event.result().toString();
System.out.println("game ended with " + result);
}));
addReaction(new ShowDrawOfferReaction(event -> System.out.println("Your opponent offered a draw. Do you want to accept it?")));
addReaction(new RemoveDrawOfferReaction(x -> System.out.println("remove draw offer: " + x.toString())));
// giving input (e.g. moving from d2 to d4)
giveInput(MoveParams(new Square('d', 2), new Square('d', 4)));
// or offering a draw to your opponent
giveInput(DrawOffer);
// square a2
Square sq = new Square('a', 2);
//... and the piece on that square
Piece p = getChessBoard().apply(sq);
// testing for piece types
if (p instanceof Pawn) System.out.println(sq + " is a pawn");
else System.out.println(sq + "is a " + p);
// getting color from that piece
Color c = p.color();
// Saving...
try {
save("C:\\Users\\user\\Documents\\javaTestSave.save");
System.out.println("Successfully saved game.");
}
catch (FileNotFoundError fnfe) {
System.err.println(fnfe.getMessage());
}
// ... and loading boards.
try {
load("C:\\Users\\user\\Documents\\javaTestSave.save");
System.out.println("Successfully loaded.");
}
catch (FileOperationError e) {
System.err.println(e.getMessage());
}
}
// defining rendering of the board
public void update() {
System.out.println(getChessBoard().toString());
}
// to open input receiver to others
public void giveInput(Input<?> input) {
super.giveInput(input);
}
}