package dcj.examples.message;
import java.rmi.*;
/**
* Source code from "Java Distributed Computing", by Jim Farley.
*
* Class: RMIChessPlayerImpl
* Example: 6-21
* Description: Server implementation of the RMI-based chess player agent.
*/
public class RMIChessPlayerImpl
implements RMIChessPlayer, Remote {
// Game-over indicator
protected boolean gameOver = false;
// Data structures for maintaining chess board state
// .
// .
// .
public static final int CHECK = 0;
public static final int CHECKMATE = 1;
public static final int NO_CHECK = 2;
public RMIChessPlayerImpl() {
// Initialize chess board
}
public boolean acceptMove(RMIChessMove m) throws RemoteException {
// Check validity of requested move.
// If valid, apply to chess board and return true.
// If invalid, return false.
// .
// .
// .
return true;
}
public RMIChessMove nextMove() throws RemoteException {
// Generate our next move based on the current
// state of the game board, and put it into the
// ChessMove passed in. If no move in this round,
// return false.
// .
// .
// .
return null;
}
public void moveAccepted(RMIChessMove m) throws RemoteException {
// Our move was accepted as valid, apply it to the
// game board...
// .
// .
// .
}
public boolean gameOver() throws RemoteException {
return gameOver;
}
public void conceded() throws RemoteException {
// We've won!
gameOver = true;
}
public static void main(String argv[]) {
String playerName = argv[0];
// Create the chess player for our side of the game
RMIChessPlayerImpl me = new RMIChessPlayerImpl();
// If we've been given the location of an opponent as
// command-line arguments, try to start a game with them...
if (argv.length > 2) {
String oppName = argv[1];
String oppHost = argv[2];
RMIChessPlayer opponent = null;
try {
opponent = (RMIChessPlayer)Naming.lookup("rmi://" + oppHost
+ "/" + oppName);
}
catch (Exception ex) {
System.out.println("Error looking up opponent " + oppName
+ " at host " + oppHost);
System.exit(1);
}
RMIChessMove myMove = null;
RMIChessMove theirMove = null;
try {
while (!me.gameOver()) {
if ((theirMove = opponent.nextMove()) != null) {
while (!me.acceptMove(theirMove) &&
(theirMove = opponent.nextMove()) != null) {
// Don't have to do anything, the while
// loop conditions do all the work.
}
}
if ((myMove = me.nextMove()) != null) {
while (!opponent.acceptMove(myMove) &&
(myMove = me.nextMove()) != null) {}
}
}
}
catch (RemoteException re) {
System.out.println("RMI error during game play.");
System.exit(1);
}
}
else {
// No arguments telling us where our opponent is, so
// we register the local player and wait for them to come
// to us.
// Bind the player to their name in the registry
try {
Naming.rebind(playerName, me);
// Now wait for another player to engage us in a game.
while (!me.gameOver()) {}
}
catch (Exception e) {
System.out.println("Error registering local player.");
System.exit(1);
}
}
}
} |