home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
PC World 1998 October
/
PCWorld_1998-10_cd.bin
/
software
/
prehled
/
inprise
/
JSAMPLES.Z
/
ChessViewer.java
< prev
next >
Wrap
Text File
|
1998-05-08
|
66KB
|
1,830 lines
/*
* Copyright (c) 1997-1998 Borland International, Inc. All Rights Reserved.
*
* This SOURCE CODE FILE, which has been provided by Borland as part
* of a Borland product for use ONLY by licensed users of the product,
* includes CONFIDENTIAL and PROPRIETARY information of Borland.
*
* USE OF THIS SOFTWARE IS GOVERNED BY THE TERMS AND CONDITIONS
* OF THE LICENSE STATEMENT AND LIMITED WARRANTY FURNISHED WITH
* THE PRODUCT.
*
* IN PARTICULAR, YOU WILL INDEMNIFY AND HOLD BORLAND, ITS RELATED
* COMPANIES AND ITS SUPPLIERS, HARMLESS FROM AND AGAINST ANY CLAIMS
* OR LIABILITIES ARISING OUT OF THE USE, REPRODUCTION, OR DISTRIBUTION
* OF YOUR PROGRAMS, INCLUDING ANY CLAIMS OR LIABILITIES ARISING OUT OF
* OR RESULTING FROM THE USE, MODIFICATION, OR DISTRIBUTION OF PROGRAMS
* OR FILES CREATED FROM, BASED ON, AND/OR DERIVED FROM THIS SOURCE
* CODE FILE.
*/
//
//
// ChessViewer.java
// applet to view a chess pgn file
//
//
package borland.samples.apps.chess.client;
import java.awt.* ;
import java.awt.event.*;
import java.net.*;
import java.applet.*;
import java.io.*;
import java.util.*;
import java.beans.*;
import borland.samples.apps.chess.client.board.*;
import borland.jbcl.control.*;
import borland.jbcl.layout.*;
import borland.jbcl.view.*;
import borland.jbcl.model.*;
import borland.jbcl.util.Alignment;
import borland.jbcl.util.VetoException;
import borland.jbcl.util.ImageLoader;
import java.lang.*;
import welcome.Application1;
public class ChessViewer extends com.sun.java.swing.JApplet implements ModalParent, Runnable
{
boolean threadFlag = true;
ResourceBundle res = ResourceBundle.getBundle("borland.samples.apps.chess.client.Res");
ColumnView[] columns = new ColumnView[4];
Button[] navBtn = new Button[8];
Thread clock; //This thread does the chessclock
ClientSender sender; //This thread sends data to server
ClientListener ourServer; //the thread that listens to the sever
boolean imageLoadError = false;
public boolean isApplet = true;
boolean loggedon = false;
boolean doNothing = false;
boolean hasListeners = false;
boolean showLibraryGame = true;
String filename ;
String myName = "";
String opponentName; //null when not a live game
String challenger; //opponent's name before the challenge is accepted
int listuse ; //used as enum PlayerList,LIBRARYLIST,MOVELIST,KIBITZ
Vector listContents;
Vector libraryListContents;
Vector pieceGif;
String subroutine = "Init";
String msg = " ";
int movecount=0; //index of selected item in playerList
int count = 0; // size of List playerList
int importCount = 0;
boolean moveToken = true;
Hashtable libraryHash = new Hashtable();
boolean blackOnTop = true;
int[] moveSubscript = new int[8];
static final int PLAYERLIST = 1;
static final int LIBRARYLIST = 2;
static final int MOVELIST = 0;
static final int KIBITZ = 3;
// static final String PLAYERLIST_LABEL = res.getString("Players");
// static final String LIBRARYLIST_LABEL = res.getString("Library");
// static final String res.getString("Moves") = res.getString("Moves");
boolean okay=true;
int color = ChessRules.Black; //the color that made the last move
int yourColor = ChessRules.Black;
long[] playerTime = new long[2];
int gameTimeValue;
long lMoveTime;
ChessRules game;
String imageNames ="/images/cmpieces.gif;/images/owlpieces.gif"; //Image parameter default data
String host = "localhost"; //HOST parameter default data
//URL selectedImage;
long opponentsTimeWhenStopped = 0; //other players time when the applet was suspended
boolean timerWasStopped = false; //Was the chessclock thread killed because the applet was suspended?
long timeStopped = 0; //the SystemTime when the applet was suspended.
LogonDialog pDialog;
Frame f = null;
GridView gridControl1; //more work to setup than a GridControl, but 500k less to deploy and since we
//we do not use a dataset and we are an applet seemed like a good idea
SplitPanel splitPanel ;
Button button0;
Button button1;
Button button2;
Button button3;
Button button4;
Button button5;
Button button6;
Button button7;
Label topName;
Label bottomName;
TextField chatText;
Panel statusPanel;
BorderLayout appletBorderLayout;
BorderLayout statusPanelBorderLayout;
Panel statusButtons;
GridLayout statusButtonsGridLayout;
Button sbLogon;
Button sbChoose;
Button optionsButton;
Label statusLine;
TextArea infoText;
Panel p;
GridLayout pGridLayout;
BorderLayout pBorderLayout;
Panel w;
BorderLayout wBorderLayout;
Panel b;
BorderLayout bBorderLayout;
EastPanel ep;
Panel altButtons;
GridLayout altButtonsGridLayout;
TabsetPanel listPanel;
List libraryList;
List playerList;
Chessboard theboard;
Label topTime;
Label bottomTime;
Panel timePanel;
Panel bottomInfo;
BorderLayout bottomInfoBorderLayout;
Panel topInfo;
BorderLayout topInfoBorderLayout;
Panel statusLinePanel;
BorderLayout statusLinePanelBorderLayout;
TextField moveTime;
TextField gameTime;
BorderLayout epLayout;
Label gameTimeLabel;
Label minutesLabel;
Label moveTimeLabel;
public ChessViewer() {
//System.out.println ("ChessViewer xtor d");
listContents = new Vector();
libraryListContents = new Vector();
game = new ChessRules();
}
static public void main(String[] args) {
ChessViewer app = new ChessViewer();
app.isApplet = false;
app.getParameters(args);
if (args.length == 1 && args[0].equals("?")) {
String [][] info = app.getParameterInfo();
if (info != null)
for (int i=0;i<info.length;i++)
System.out.println(info[i][0] + "=(" + info[i][0]+ ") " + info[i][2]);
}
DecoratedFrame frame = new DecoratedFrame();
//frame.setLayout(new BorderLayout());
frame.add(app,BorderLayout.CENTER);
frame.setTitle(app.res.getString("ChessViewer"));
frame.setBounds(0,-500,40,30);
frame.setVisible(false);
frame.setVisible(true); //needs to happen before Chessboard.setImage() so image observer is real?
app.init();
frame.pack();
// Center the frame
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getPreferredSize();
if (frameSize.height > screenSize.height)
frameSize.height = screenSize.height;
if (frameSize.width > screenSize.width)
frameSize.width = screenSize.width;
frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
frame.setVisible(true);
if (app.pDialog != null)
app.pDialog.name.requestFocus();
}
String getParameter(String parmName, String args[]) {
if (args == null) {
return getParameter(parmName);
}
int i;
String strArg = parmName + '=';
String strValue = null;
for (i = 0; i < args.length; i++) {
int index = args[i].indexOf('=') + 1;
if (strArg.equalsIgnoreCase(args[i].substring(0, index))) {
strValue= args[i].substring(strArg.length());
if (strValue.startsWith("\"")) {
strValue = strValue.substring(1);
if (strValue.endsWith("\""))
strValue = strValue.substring(0, strValue.length() - 1);
}
}
}
return strValue;
}
void getParameters(String args[]) {
String param;
param = getParameter(res.getString("IMAGENAME"), args);
if (param != null)
imageNames = param;
param = getParameter("HOST", args);
if (param != null)
host = param;
param = getParameter(res.getString("GAMEPARAMNAME"),args);
if (param != null)
filename = param;
}
public String [] [] getParameterInfo() {
String[][] info = {
{ res.getString("IMAGENAME"), "String", res.getString("SEMICOLON_DELIMITED") },
{ res.getString("GAMEPARAMNAME"), "String", res.getString("PGN_FILE_TO_LOAD_VERY")},
{ "HOST", "String", res.getString("THE_HOSTNAME_OF_THE") },
};
return info;
}
public String getAppletInfo() {
return res.getString("Name:_ChessViewer") +
res.getString("Author:_Greg") +
res.getString("Created_with_Borland") +
res.getString("Description:_A_Chess");
}
public void init() {
try {
pieceGif = new Vector();
int i ;
if (isApplet) {
getParameters(null);
host = getCodeBase().getHost(); //Override the host parameter since we are an
//applet and this is only server we are
//capable of talking to
}
//parse imageNames into Vector pieceGif
int index = -1;
while (true) {
int nextIndex = imageNames.indexOf(';',index+1);
if (nextIndex == -1)
nextIndex = imageNames.length();
String imageName = imageNames.substring(index+1,nextIndex);
System.out.println("imageName = " + imageName);
URL imageURL;
try {
if (!isApplet)
if (imageName.startsWith("file://"))
imageURL = new URL(imageName);
else
imageURL = new URL("http",host,imageName);
else
imageURL = new URL(getDocumentBase(),imageName);
pieceGif.addElement(imageURL);
}
catch (Exception e) {
System.out.println( e + host +" " + imageName);
}
index = nextIndex;
if (index >= imageNames.length() -1)
break;
}
int j;
f = ChessViewer.getFrame(this);
if (f == null)
System.out.println("Where is the frame?");
else
System.out.println("frame title is " + f.getTitle());
jbInit();
}
catch (Exception e ) {
System.out.println("chessViewer.init " + e);
e.printStackTrace();
}
game.setPieceValues(0,1,theboard.getPiecePosition());
game.setPieceColors(0,1,theboard.getColorPosition());
subroutine = "parsePGNFile";
URL PGNurl = null;
listuse = KIBITZ;
String message;
InputStream is = null;
try {
if (filename != null) {
if (isApplet)
PGNurl = new URL(getDocumentBase(),filename);
else
PGNurl = new URL("http",host,filename);
is = PGNurl.openStream();
if (is != null){
infoText.setText("");
Reader reader = new InputStreamReader(is);
BufferedReader bufferedReader = new BufferedReader(reader);
game.parsePGNFile (bufferedReader);
listuse = KIBITZ;
subroutine = "parsePGNFile done";
}
else {
topName.setText(res.getString("COULD_NOT_OPEN") + filename);
}
}
else
System.out.println("no file specified");
topName.setText(game.getPlayerB());
bottomName.setText(game.getPlayerW());
System.out.println("init start thread");
clock = new Thread(this);
//clock.setPriority(Thread.NORM_PRIORITY + 1); //to help the images load
clock.start();
clock = null; //don't want the opportunity to kill loading the board image.
System.out.println("init call fillMoveList");
fillMoveList();
color = ChessRules.Black;
System.out.println("init call dispalypos" );
logonEnable(false);
displayPos();
System.out.println("init back from call dispalypos" );
if (filename == null)
startsocket();
}
catch( IOException x) {
message = x.toString() ;
if (PGNurl != null)
message = message + " "+ PGNurl.toString();
else
message = res.getString("QUESTION_MARKS") + message;
if (bottomName != null)
bottomName.setText(message);
}
catch(Exception e) {
System.out.println( "init " + e);
e.printStackTrace();
message = e.toString();
if (topName != null)
topName.setText(subroutine + count );
if (bottomName != null)
bottomName.setText(message);
}
try {
if (is != null)
is.close();
}
catch(Exception e) {}
}
private void jbInit() throws Exception {
gridControl1 = (GridView) Beans.instantiate(getClass().getClassLoader(),borland.jbcl.view.GridView.class.getName());
splitPanel = (SplitPanel) Beans.instantiate(getClass().getClassLoader(),borland.jbcl.control.SplitPanel.class.getName());
button0 = (Button) Beans.instantiate(getClass().getClassLoader(),java.awt.Button.class.getName());
button1 = (Button) Beans.instantiate(getClass().getClassLoader(),java.awt.Button.class.getName());
button2 = (Button) Beans.instantiate(getClass().getClassLoader(),java.awt.Button.class.getName());
button3 = (Button) Beans.instantiate(getClass().getClassLoader(),java.awt.Button.class.getName());
button4 = (Button) Beans.instantiate(getClass().getClassLoader(),java.awt.Button.class.getName());
button5 = (Button) Beans.instantiate(getClass().getClassLoader(),java.awt.Button.class.getName());
button6 = (Button) Beans.instantiate(getClass().getClassLoader(),java.awt.Button.class.getName());
button7 = (Button) Beans.instantiate(getClass().getClassLoader(),java.awt.Button.class.getName());
topName = (Label)Beans.instantiate(getClass().getClassLoader(),Label.class.getName());
bottomName = (Label)Beans.instantiate(getClass().getClassLoader(),Label.class.getName());
chatText = (TextField) Beans.instantiate(getClass().getClassLoader(),TextField.class.getName());
statusPanel = (Panel) Beans.instantiate(getClass().getClassLoader(),Panel.class.getName());
appletBorderLayout = (BorderLayout) Beans.instantiate(getClass().getClassLoader(),BorderLayout.class.getName());
statusPanelBorderLayout = (BorderLayout) Beans.instantiate(getClass().getClassLoader(),BorderLayout.class.getName());
statusButtons = (Panel) Beans.instantiate(getClass().getClassLoader(),Panel.class.getName());
statusButtonsGridLayout = (GridLayout)Beans.instantiate(getClass().getClassLoader(),GridLayout.class.getName());
sbLogon = (Button) Beans.instantiate(getClass().getClassLoader(),Button.class.getName());
sbChoose = (Button) Beans.instantiate(getClass().getClassLoader(),Button.class.getName());
optionsButton = (Button) Beans.instantiate(getClass().getClassLoader(),Button.class.getName());
statusLine = (Label)Beans.instantiate(getClass().getClassLoader(),Label.class.getName());
infoText = (TextArea) Beans.instantiate(getClass().getClassLoader(),TextArea.class.getName());
p = (Panel) Beans.instantiate(getClass().getClassLoader(),Panel.class.getName());
pGridLayout = (GridLayout)Beans.instantiate(getClass().getClassLoader(),GridLayout.class.getName());
pBorderLayout = (BorderLayout) Beans.instantiate(getClass().getClassLoader(),BorderLayout.class.getName());
w = (Panel) Beans.instantiate(getClass().getClassLoader(),Panel.class.getName());
wBorderLayout = (BorderLayout) Beans.instantiate(getClass().getClassLoader(),BorderLayout.class.getName());
b = (Panel) Beans.instantiate(getClass().getClassLoader(),Panel.class.getName());
bBorderLayout = (BorderLayout) Beans.instantiate(getClass().getClassLoader(),BorderLayout.class.getName());
ep = (EastPanel)(Panel) Beans.instantiate(getClass().getClassLoader(),EastPanel.class.getName());
altButtons = (Panel) Beans.instantiate(getClass().getClassLoader(),Panel.class.getName());
altButtonsGridLayout = (GridLayout)Beans.instantiate(getClass().getClassLoader(),GridLayout.class.getName());
listPanel = (TabsetPanel) Beans.instantiate(getClass().getClassLoader(),TabsetPanel.class.getName());
libraryList = (List)Beans.instantiate(getClass().getClassLoader(),List.class.getName());
playerList = (List)Beans.instantiate(getClass().getClassLoader(),List.class.getName());
theboard = (Chessboard) Beans.instantiate(getClass().getClassLoader(),Chessboard.class.getName());
topTime = (Label)Beans.instantiate(getClass().getClassLoader(),Label.class.getName());
bottomTime = (Label)Beans.instantiate(getClass().getClassLoader(),Label.class.getName());
timePanel = (Panel) Beans.instantiate(getClass().getClassLoader(),Panel.class.getName());
bottomInfo = (Panel) Beans.instantiate(getClass().getClassLoader(),Panel.class.getName());
bottomInfoBorderLayout = (BorderLayout) Beans.instantiate(getClass().getClassLoader(),BorderLayout.class.getName());
topInfo = (Panel) Beans.instantiate(getClass().getClassLoader(),Panel.class.getName());
topInfoBorderLayout = (BorderLayout) Beans.instantiate(getClass().getClassLoader(),BorderLayout.class.getName());
statusLinePanel= (Panel) Beans.instantiate(getClass().getClassLoader(),Panel.class.getName());
statusLinePanelBorderLayout = (BorderLayout) Beans.instantiate(getClass().getClassLoader(),BorderLayout.class.getName());
moveTime = (TextField) Beans.instantiate(getClass().getClassLoader(),TextField.class.getName());
gameTime = (TextField) Beans.instantiate(getClass().getClassLoader(),TextField.class.getName());
epLayout = (BorderLayout) Beans.instantiate(getClass().getClassLoader(),BorderLayout.class.getName());
gameTimeLabel = (Label)Beans.instantiate(getClass().getClassLoader(),Label.class.getName());
minutesLabel = (Label)Beans.instantiate(getClass().getClassLoader(),Label.class.getName());
moveTimeLabel = (Label)Beans.instantiate(getClass().getClassLoader(),Label.class.getName());
w.setLayout(wBorderLayout);
b.setLayout(bBorderLayout);
w.add(b,BorderLayout.SOUTH);
pGridLayout.setRows(1);
pGridLayout.setColumns(4);
p.setLayout(pGridLayout);
b.add(p,BorderLayout.CENTER);
theboard.setImage(borland.jbcl.util.ImageLoader.loadFromResource("images/cmpieces.gif",this,game.getClass()));
button0.setLabel(res.getString("BEGINNING_OF_GAME"));
navBtn[0] = button0;
p.add(button0);
navBtn[1] = button1;
button1.setLabel(res.getString("BACK_ONE_MOVE"));
p.add(button1);
navBtn[3] = button3;
button3.setLabel(res.getString("FORWARD_ONE_MOVE"));
p.add(button3);
navBtn[2] = button2;
button2.setLabel(res.getString("END_OF_GAME"));
p.add(button2);
b.add(altButtons,BorderLayout.SOUTH);
altButtonsGridLayout.setRows(1);
altButtonsGridLayout.setColumns(4);
altButtons.setLayout(altButtonsGridLayout);
navBtn[4] = button4;
button4.setLabel("Branch 1");
altButtons.add(button4);
navBtn[5] = button5;
button5.setLabel("Branch 2");
altButtons.add(button5);
navBtn[6] = button6;
button6.setLabel("Branch 3");
altButtons.add(button6);
navBtn[7] = button7;
button7.setLabel("Branch 4");
altButtons.add(button7);
BoardButtonActionAdapter boardButtonActionAdapter = new BoardButtonActionAdapter(this);
for (int i=0;i<8;i++)
navBtn[i].addActionListener(boardButtonActionAdapter);
PlayerListAdapter playerListAdapter = new PlayerListAdapter(this);
playerList.addActionListener(playerListAdapter);
playerList.addItemListener(playerListAdapter);
LibraryListAdapter libaryListAdapter = new LibraryListAdapter(this);
libraryList.addActionListener(libaryListAdapter);
libraryList.addItemListener(libaryListAdapter);
infoText.setRows(6);
infoText.setColumns(25);
infoText.setEditable(false);
statusPanel.setLayout(statusPanelBorderLayout);
statusLine.setText(res.getString("LOGONHINT"));
chatText.setText(res.getString("CHATHINT"));
OtherActionAdapter otherActionAdapter = new OtherActionAdapter(this);
chatText.addActionListener(otherActionAdapter);
ep.setLayout(epLayout);
ep.add(chatText,BorderLayout.NORTH);
statusButtonsGridLayout.setRows(1);
statusButtonsGridLayout.setColumns(4);
statusButtons.setLayout(statusButtonsGridLayout);
gameTimeLabel.setText(res.getString("GAMEIN"));
timePanel.add (gameTimeLabel);
gameTimeLabel.setAlignment(Label.RIGHT);
gameTime.setText(res.getString("DEFAULT_GAME_TIME"));
timePanel.add (gameTime);
minutesLabel.setText(res.getString("MINUTES") );
timePanel.add (minutesLabel);
moveTime.setText(res.getString("DEFAULT_MOVE_TIME"));
timePanel.add (moveTime);
moveTimeLabel.setText(res.getString("MOVETIME"));
int[] columnSizes = new int[4];
columnSizes[0] = 40;
columnSizes[1] = 50;
columnSizes[2] = 50;
columnSizes[3] = 100;
columns[0] = new ColumnView();
columns[1] = new ColumnView();
columns[2] = new ColumnView();
columns[3] = new ColumnView();
columns[0].setWidth(columnSizes[0]);
columns[1].setWidth(columnSizes[1]);
columns[2].setWidth(columnSizes[2]);
columns[3].setWidth(columnSizes[3]);
columns[0].setItemPainter(new TextItemPainter());
columns[3].setItemEditor(new ExpandingTextItemEditor());
columns[0].setCaption(res.getString("Move"));
columns[1].setCaption(res.getString("White"));
columns[2].setCaption(res.getString("Black"));
columns[3].setCaption("");
gridControl1.setColumnViews(columns);
gridControl1.setRowHeaderVisible(false);
SizeVector columnSizeVector = new VariableSizeVector(columnSizes);
gridControl1.setColumnSizes(columnSizeVector);
gridControl1.setRowSizes(new FixedSizeVector(20));
GC_ColumnHeaderManager columnManager = new GC_ColumnHeaderManager(columns);
gridControl1.getColumnHeaderView().setViewManager(columnManager);
gridControl1.getColumnHeaderView().setModel(columnManager);
gridControl1.setSelection(new SingleMatrixSelection(gridControl1.getSubfocus()));
gridControl1.addSubfocusListener(new ChessViewer_gridControl1_SubfocusAdapter(this));
this.setSize(new Dimension(687, 497));
gridControl1.setModel(game);
gridControl1.setViewManager(new BasicViewManager(
new FocusableItemPainter(
new SelectableTextItemPainter(Alignment.LEFT | Alignment.MIDDLE)),
new TextItemEditor(Alignment.LEFT | Alignment.MIDDLE)));
timePanel.add (moveTimeLabel);
sbChoose.setLabel(res.getString("COPY_PASTE"));
statusButtons.add(sbChoose);
statusButtons.add(optionsButton);
sbLogon.setLabel(res.getString("LOGOFF") );
statusButtons.add(sbLogon);
sbChoose.addActionListener(otherActionAdapter);
sbLogon.addActionListener(otherActionAdapter);
statusPanel.add(statusButtons,BorderLayout.CENTER);
statusPanel.add(timePanel,BorderLayout.NORTH);
optionsButton.addActionListener(otherActionAdapter);
optionsButton.setLabel(res.getString("OPTIONS_"));
statusLinePanel.setLayout(statusLinePanelBorderLayout);
statusLinePanel.add(statusLine,BorderLayout.CENTER);
statusPanel.add(statusLinePanel,BorderLayout.SOUTH);
ep.add(statusPanel,BorderLayout.SOUTH);
getContentPane().setLayout(appletBorderLayout);
getContentPane().add(w,BorderLayout.WEST);
getContentPane().add(ep,BorderLayout.EAST);
ep.add(splitPanel, BorderLayout.CENTER);
// ep.add(gridControl1, BorderLayout.CENTER);
splitPanel.add(infoText, new PaneConstraints("infoText","infoText",PaneConstraints.ROOT,1.0f));
splitPanel.add(listPanel, new PaneConstraints("listPanel","infoText",PaneConstraints.BOTTOM,0.6f));
// splitPanel.add(gridControl1, new PaneConstraints("listPanel","infoText",PaneConstraints.BOTTOM,0.6f));
listPanel.add(gridControl1, res.getString("Moves"));
listPanel.add(playerList, res.getString("Players"));
listPanel.add(libraryList, res.getString("Library"));
listPanel.setSelectedTab(res.getString("Players"));
listPanel.setTabsOnTop(false);
listPanel.setMargins(new Insets(0, 0, 0, 0));
listPanel.addSubfocusListener(new ChessViewer_listPanel_SubfocusAdapter(this));
Font boldFont = new Font(getFont().getName(),Font.BOLD,getFont().getSize());
bottomName = new Label();
bottomName.setText(game.getPlayerW());
bottomName.setFont(boldFont);
topName.setText(game.getPlayerB());
topName.setFont(boldFont);
topInfo.setLayout(topInfoBorderLayout);
topTime.setFont(boldFont);
bottomInfo.setLayout(bottomInfoBorderLayout);
bottomTime.setFont(boldFont);
bottomInfo.add(bottomName,BorderLayout.CENTER);
bottomInfo.add(bottomTime, BorderLayout.EAST);
w.add(theboard, BorderLayout.CENTER);
topInfo.add(topName, BorderLayout.CENTER);
topInfo.add(topTime, BorderLayout.EAST);
w.add(topInfo, BorderLayout.NORTH);
b.add(bottomInfo, BorderLayout.NORTH);
bottomTime.setText(res.getString("ZEROTIME"));
topTime.setText(res.getString("ZEROTIME"));
theboard.addActionListener(new ChessboardAdapt(this));
//so it comes up pretty in the designer; set to something real in run(); if it can't find the image set in run it will keep using this one
if (isApplet)
return;
theboard.setImage(ImageLoader.loadFromResource("images/cmpieces.gif",this,game.getClass()));
}
public void fillMoveList() {
try {
game.generatePositions();
System.out.println("FillMoveList returned from generatePositions");
count = game.getArraySize();
subroutine= "fillMoveList";
moveSubscript[0] = 0;
moveSubscript[1] = 0;
moveSubscript[2] = count;
moveSubscript[3] = 0;
int movenumber;
for (int i=1;i<=count;i++) {
movenumber = game.getMoveNumber(i,0);
if (movenumber == 0)
movenumber = game.getMoveNumber(i,1);
String lineitem = " " + movenumber +". "+game.getMoveText(i,0)+" "+game.getMoveText(i,1);
}
System.out.println("Added " + count + " lines");
subroutine= "fillMoveList-end";
}
catch (Exception e) {
System.out.println("fillmovelist " + e);
e.printStackTrace();
}
}
void logonEnable(boolean state) {
loggedon = state;
chatText.setEnabled(state);
if (loggedon) {
sbLogon.setEnabled(true); // Once on, only toggle the meaning
sbLogon.setLabel(res.getString("LOGOFF"));
}
else {
if (listuse == ChessViewer.MOVELIST)
gameOver();
else
if (listuse == ChessViewer.PLAYERLIST ||
listuse == ChessViewer.LIBRARYLIST ) {
setListButtons (ChessViewer.LIBRARYLIST);
getLibraryList();
}
moveToken = true;
sbLogon.setLabel(res.getString("LOGON"));
}
}
public void setListListener(PlayerListListener ll){
ourServer.listListener = ll;
}
public void removeListListener(){
ourServer.listListener = null;
}
public void startsocket() {
int port = 100;
System.out.println("startsocket");
try {
statusLine.setText(res.getString("Connecting_"));
Socket kkSocket = new Socket(host,port);
PrintWriter os = new PrintWriter(kkSocket.getOutputStream());
//DataInputStream is = new DataInputStream(kkSocket.getInputStream());
BufferedReader is = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
String fromServer;
os.println("Hello");
os.flush();
if ((fromServer = is.readLine()) != null) {
System.out.println("CV" +String.valueOf(port) + "Received: " + fromServer);
port = new Integer(fromServer).intValue();
}
os.close();
is.close();
kkSocket.close();
//kkSocket = new Socket("ghamer", port);
kkSocket = new Socket(host,port);
ourServer = new ClientListener(this,kkSocket);
ourServer.start();
sender = new ClientSender(kkSocket);
sender.start();
pDialog = new LogonDialog(this);
pDialog.setVisible(true);
}
catch (UnknownHostException e) {
statusLine.setText(res.getString("CONNECTION_ERROR") + e);
System.err.println(res.getString("UNKNOWN_HOST") + e);
}
catch (Exception e) {
statusLine.setText(res.getString("CONNECTION_ERROR") + e);
System.err.println("startsocket " + e);
e.printStackTrace();
}
}
public void setModal(boolean value) {
doNothing = value;
//System.out.println("SM Chessboard enable = " + !value);
theboard.setEnabled(!doNothing);
}
public void setGameButtons() {
int i;
if (listuse == MOVELIST) {
navBtn[0].setLabel(res.getString("OFFER_ABORT"));
navBtn[1].setLabel(res.getString("OFFER_DRAW"));
navBtn[2].setLabel(res.getString("RESIGN"));
navBtn[3].setLabel(res.getString("SUSPEND"));
navBtn[0].setEnabled(true);
navBtn[1].setEnabled(true);
navBtn[2].setEnabled(true);
navBtn[3].setEnabled(true);
for (i=4;i<8;i++)
navBtn[i].setVisible(false);
}
//System.out.println("movecount="+movecount+ " count=" + count);
if (opponentName != null && listuse != KIBITZ)
return;
navBtn[0].setEnabled(movecount>0);
moveSubscript[1] = game.getPreviousSubscript(movecount,color);
navBtn[1].setEnabled(movecount != 0);
navBtn[2].setEnabled(movecount<count);
String message = game.getComment(movecount,color);
int nxtclr = 0;
if (color==0)
nxtclr = 1;
int initcolor = nxtclr;
int j;
loops:
for (i=movecount+color;i<count;i++) { //format the move comment
for (j=initcolor;j<2;j++) {
if (game.getMoveNumber(i,j) != 0)
break loops;
message = message + game.getComment(i,j);
}
initcolor = 0;
}
//infoText.setText(message); turn on someday when dont need diagnostics
j = 3;
boolean moremoves = false;
for (i=movecount+color;i<=count;i++){ //map the navigation buttons
if (game.getPreviousSubscript(i,nxtclr) == movecount ||
(j==3 && game.getMoveNumber(i,nxtclr) != 0)){
navBtn[j].setLabel(game.getMoveText(i,nxtclr));
navBtn[j].setVisible(true);
moremoves = true;
moveSubscript[j] = i;
j++;
if (j > 7)
break;
}
}
if (moremoves)
navBtn[3].setEnabled(true); //enable the play button
else {
navBtn[3].setLabel(res.getString(">"));
navBtn[3].setEnabled(false);
j++; //never want to hide the play button
}
for (i=j;i<8;i++) //hide the unmapped navigation buttons
navBtn[i].setVisible(false);
}
public void tokenMove(String tokenmsg){
int index = tokenmsg.indexOf(' ');
int prevsub = Integer.parseInt(tokenmsg.substring(0,index));
MoveTuple tuple = new MoveTuple(tokenmsg.substring(index+1));
if (tuple.pieceColor == 0)
color = 1;
else
color = 0;
movecount = prevsub;
// theboard.setPosition(game.getPieceValues(prevsub,color),
// game.getPieceColors(prevsub,color));
game.setMove(prevsub,color);
game.moveInfo(tuple,yourColor,false,false);
updateMoveList();
System.out.println("tokenMove calling displayPos");
// displayPos();
}
void moveInfo() {
//System.out.println("moveInfo opponentName=" + opponentName);
if (listuse == PLAYERLIST || listuse == LIBRARYLIST) {
listuse = KIBITZ;
listPanel.setSelectedTab(res.getString("Moves"));
}
MoveTuple tuple = theboard.getTuple();
if (game.moveInfo(tuple,yourColor,opponentName != null,!moveToken && hasListeners)) {
if (!moveToken && hasListeners) {
sendMsg("TokenMove",String.valueOf(movecount) + " " + tuple.toString());
return;
}
else {
updateMoveList(); //will trigger a subfocusChanged which calls displayPos
}
//displayPos();
}
else {
//System.out.println("ChessViewer.moveInfo reason " + game.getReason());
theboard.setPosition(game.getPieceValues(movecount,color),
game.getPieceColors(movecount,color));
statusLine.setText(game.getReason());
}
//displayPos();
int gameResult = game.isGameOver();
if (gameResult > 0 && opponentName != null) {
String msgType = "Resigned";
String rslt = res.getString("01_Checkmate");
if (gameResult == 1) {
if (color == ChessRules.Black)
rslt = res.getString("10_Checkmate");
}
else {
rslt = res.getString("12_1_2_Stalemate");
msgType = "AcceptDraw";
}
sendMsg(msgType,rslt);
statusLine.setText(rslt); //written when resign msg comes back from server
gameOver(rslt);
}
}
// Update movecount & color to point to the new move
// If playing someone, punch the clock and send them the move
void updateMoveList() {
movecount = game.getLastMoveNumber();
color = game.getWhoMovedLast();
//System.out.println("lastmoveSub = " + movecount + ",color = " + color);
String moveString;
String variation = " ";
gridControl1.setSubfocus(movecount-1,color + 1);
if (count == movecount) {
moveString = Integer.toString(game.getMoveNumber(movecount,color))+
". "+game.getMoveText(movecount,0)+" "+game.getMoveText(movecount,1);
moveSubscript[2] = movecount ;
}
else {
int prevsub = game.getPreviousSubscript(movecount,color);
if (count != prevsub)
variation = " @" + prevsub + ' ';
moveString = Integer.toString(game.getMoveNumber(movecount,color))+". "+
game.getMoveText(movecount,0)+" "+game.getMoveText(movecount,1);
moveSubscript[2] = ++count ;
//count++; //count = newcount;
}
if (clock != null) {
synchronized (clock) {
clock.notify(); //punch the clock
}
}
playerTime[color] = playerTime[color] + lMoveTime ;
if (/*opponentName != null &&*/ hasListeners && sender != null) {
//System.out.println("Send kibitzers/opponents the move");
sendMsg("Move",String.valueOf(playerTime[color]) + variation + moveString);
}
}
void sendMsg(String msgid,String[] parm) {
String msg = PersistString.concat(parm);
sendMsg(msgid,msg);
}
void sendMsg(String msgid,String msg) {
try {
System.out.println("Sending " + msgid + " " + msg );
ServerMessage smsg = new ServerMessage(0,msgid,msg);
if (sender == null )
System.out.println("sendMsg - sender is null??");
else {
synchronized (sender) {
sender.msgque.addElement(smsg);
sender.notify();
}
if (msgid.equals("Bye") || msgid.equals("Dead")) {
System.out.println("sendMsg setting sender to null");
sender = null;
}
}
}
catch (Exception e ) {System.out.println("sendMsg " + e); }
}
public void logonButton() {
if (loggedon == true) {
statusLine.setText(res.getString("LOGGED_OFF"));
logonEnable(false);
libraryList.removeAll();
libraryListContents.removeAllElements();
sendMsg("Bye","");
}
else {
if (pDialog == null)
startsocket();
else
pDialog.okButton.requestFocus();
}
}
void chooseGame() {
String [] gameName = libraryList.getSelectedItems();
String msg = null;
if (gameName == null) {
ImportDlg dlg = new ImportDlg(this,getMoves());
dlg.setVisible(true);
}
else {
for (int i=0;i<gameName.length;i++) {
if (libraryHash.containsKey(gameName[i]));
else
if (msg == null)
msg = gameName[i] + "?";
else
msg = msg + gameName[i] + "?";
}
if (msg != null)
sendMsg("GetLibraryGame",msg);
if (gameName.length == 1)
showLibraryGame = true;
else
showLibraryGame = false;
if (gameName.length == 1 && msg == null)
getGame(gameName[0]);
}
}
void chooseButton(){
hasListeners = false;
if (listuse == PLAYERLIST) {
String choice = playerList.getSelectedItem();
int index = playerList.getSelectedIndex();
if (index == -1) {
ImportDlg dlg = new ImportDlg(this,getMoves());
dlg.setVisible(true);
}
else {
String type = "?";
type = (String) listContents.elementAt(index);
if (type.equals("G"))
sendMsg("Resume",String.valueOf(index));
else
if (type.equals("P"))
challenge(choice);
else
watch(choice);
}
}
else {
if (listuse == LIBRARYLIST)
chooseGame();
else
if (listuse == KIBITZ) {
ImportDlg dlg = new ImportDlg(this,getMoves());
dlg.setVisible(true);
}
else {
sbChoose.setEnabled(false);
System.out.println("Choose button was enabled when it shouldn't be");
}
}
}
String getMoves() {
//StringBuffer moves = new StringBuffer("[White \"" + game.getPlayerW() + "\"]" + "[Black \"" + game.getPlayerB() + "\"]\n");
StringBuffer moves = new StringBuffer(game.getTags());
//int max = moveList.getItemCount();
int max = game.getRowCount();
int count = 0;
String movePair;
for (int i= 1;i <= max; i++) {
//movePair = moveList.getItem(i);
movePair = " " + game.getMoveNumber(i,0) + ". " + game.getMoveText(i,0) + " " + game.getMoveText(i,1);
count = count + movePair.length() + 1;
if (count > 64) {
moves.append("\n" + movePair);
count = movePair.length() ;
}
else
moves.append(movePair);
}
return moves.toString();
}
void getInfo(String linedata){
sbChoose.setEnabled(true);
String user = linedata.substring(0,linedata.lastIndexOf(' '));
if (user.equals(myName))
sbChoose.setLabel(res.getString("UPDATE"));
else {
sendMsg("Info",user);
sbChoose.setLabel(res.getString("CHALLENGE"));
}
}
void challenge(String linedata) {
//strip off rating
challenger = linedata.substring(0,linedata.lastIndexOf(' '));
if (challenger.equals(myName))
sendMsg("Information",challenger);
else {
try {
String[] parm = new String[3];
parm[0] = gameTime.getText();
System.out.println("Challenge " + challenger + " " + parm[0]) ;
gameTimeValue = Integer.parseInt(parm[0]);
parm[1] = moveTime.getText();
lMoveTime = Long.parseLong(parm[1]) * 1000;
parm[2] = challenger;
//String l = gt +" " + mt +" " + challenger;
playerTime[0] = gameTimeValue * 60000;
playerTime[1] = playerTime[0];
sendMsg("Challenge",PersistString.concat(parm));
}
catch (NumberFormatException e){
statusLine.setText(res.getString("TIME_CONTROL_FIELDS"));
}
}
}
void importGame(String gamePGN) {
System.out.println("imported game = " + gamePGN);
if (gamePGN == null || gamePGN.length() < 20)
statusLine.setText(res.getString("PASTE_AND_THEN") );
else {
importCount++;
String name = res.getString("IMPORTEDGAME") + importCount;
libraryHash.put(name,gamePGN);
getGame(name);
}
}
void boardOptionsDialog() {
try {
URL[] imageName = new URL[pieceGif.size()];
URL currentImage = theboard.getImageURL();
//System.out.println("image array size = " + imageName.length);
for (int i= 0;i< pieceGif.size();i++) {
imageName[i] = (URL)pieceGif.elementAt(i);
//System.out.println("image " + i + "=" + imageName[i].toString());
if (currentImage.sameFile(imageName[i]) && i > 0){
imageName[i] = imageName[0];
imageName[0] = currentImage;
}
}
//System.out.println("ready to call BoardOptions xtor");
BoardOptions dlg;
dlg = new BoardOptions(this,f,imageName,theboard);
System.out.println("back from xtor");
Point y = listPanel.getLocation();
//Point x = ep.location();
dlg.setLocation(0,y.y);
dlg.pack();
dlg.setVisible(true);
System.out.println("back from show");
}
catch (Exception e) {System.out.println("BoardOptionsDialog " + e); e.printStackTrace(); }
}
public void otherAction(ActionEvent evt) {
if (doNothing) //fake modal dialog on the loose
return ;
if (evt.getSource().equals(optionsButton))
boardOptionsDialog();
else if (evt.getSource().equals(sbLogon))
logonButton();
else if (evt.getSource().equals(chatText)) {
sendMsg("Chat",myName + ":" + chatText.getText()) ;
chatText.setText("");
}
else if (evt.getSource().equals(sbChoose))
chooseButton();
}
void boardButtonAction(ActionEvent evt) {
if (doNothing) //fake modal dialog on the loose
return ;
if (listuse == MOVELIST)
gameButtons(evt);
else
navigationButtons(evt);
}
void getLibraryList() {
listuse = LIBRARYLIST;
sbChoose.setLabel(res.getString("COPY_PASTE"));
if (loggedon) {
if (libraryList.getItemCount()==0)
sendMsg("LibraryList","") ;
else
setListButtons(ChessViewer.LIBRARYLIST);
}
else {
if (libraryList.getItemCount()==0) {
libraryListContents.removeAllElements();
for (Enumeration e = libraryHash.keys();e.hasMoreElements();) {
String gameName = (String) e.nextElement() ;
libraryList.addItem(gameName);
libraryListContents.addElement("L");
}
}
setListButtons(ChessViewer.LIBRARYLIST);
}
}
void gameButtons(ActionEvent evt) {
if (evt.getSource().equals(navBtn[0])) {
navBtn[0].setEnabled(false);
sendMsg("OfferAbort","") ;
statusLine.setText(res.getString("ABORT_OFFERED_TO") + opponentName);
}
else
if (evt.getSource().equals(navBtn[1])) {
navBtn[1].setEnabled(false);
if (game.claimDraw()) {
sendMsg("AcceptDraw"," 1/2-1/2 " + game.getReason() ) ;
gameOver("1/2-1/2");
}
else {
sendMsg("OfferDraw","") ;
statusLine.setText(res.getString("DRAW_OFFERED_TO") +opponentName);
}
}
else
if (evt.getSource().equals(navBtn[2])) {
statusLine.setText(res.getString("GAME_OVER"));
String result = "1-0 ";
if (yourColor == ChessRules.White)
result = "0-1 ";
game.setComment(movecount,color,result);
displayPos();
gameOver(result);
sendMsg("Resigned",result + myName + res.getString("RESIGNED")) ;
}
else
if (evt.getSource().equals(navBtn[3])) {
statusLine.setText(res.getString("GAME_SUSPENDED"));
gameOver();
hasListeners = false;
sendMsg("Suspend","") ;
}
}
public void navigationButtons(ActionEvent evt) {
for (int i=0; i< 8;i++) {
if (evt.getSource().equals(navBtn[i])) {
movecount = moveSubscript[i] ;
if (navBtn[i].getLabel() == res.getString("END_OF_GAME")) {
color = game.getMoveNumber(movecount, ChessRules.Black) == 0 ?
ChessRules.White : ChessRules.Black;
}
else if (color==0)
color = 1;
else
if (movecount != 0) //initial position is Move(0,1)
color = 0;
break;
}
}
// Note that calling setSubfocus will also invoke the
// 'callback' associated with clicking the grid cell of
// interest.
int subfocusRow, subfocusCol;
if (movecount > 0) {
// typical case
subfocusRow = movecount-1;
subfocusCol = color + 1;
}
else {
// initial case, before the game begins
movecount = 0; // just to make sure
color = ChessRules.Black;
subfocusRow = 0;
subfocusCol = 0;
}
System.err.println("set subfocus to " +
subfocusRow + "," + subfocusCol );
gridControl1.setSubfocus(subfocusRow, subfocusCol);
//displayPos();
if (listuse == PLAYERLIST || listuse == LIBRARYLIST) {
listuse = KIBITZ;
listPanel.setSelectedTab(res.getString("Moves"));
}
}
public void setNames() {
//System.out.println("PlayerB="+game.getPlayerB()+" PlayerW="+game.getPlayerW()+" myName="+myName);
if (game.getPlayerB().equals(myName)) {
if (blackOnTop)
switchSides();
else {
bottomName.setText(game.getPlayerB());
topName.setText(game.getPlayerW());
bottomTime.setText(formatTime(playerTime[1]));
topTime.setText(formatTime(playerTime[0]));
}
}
else {
if (!blackOnTop)
switchSides();
else {
bottomName.setText(game.getPlayerW());
topName.setText(game.getPlayerB());
bottomTime.setText(formatTime(playerTime[0]));
topTime.setText(formatTime(playerTime[1]));
}
}
}
void newGame(String white,String black) {
game.init();
game.setPlayerW(white);
game.setPlayerB(black);
setNames();
movecount = 0;
color = ChessRules.Black;
count = 0;
setListButtons(MOVELIST);
moveToken = true;
if (opponentName != null) {
hasListeners = true;
gameTime.setEnabled(false);
moveTime.setEnabled(false);
gridControl1.setEnabled(false);
}
else {
//System.out.println("NG chessboard enabled");
theboard.setEnabled(true);
}
displayPos();
gameTime.setText(String.valueOf(gameTimeValue));
moveTime.setText(String.valueOf(lMoveTime/1000));
try {
if (clock != null)
clock.stop();
clock = new Thread(this);
clock.start();
}
catch (Exception e) {
e.printStackTrace();
}
}
void displayPos() {
if (count > 0 && movecount == count && game.getMoveNumber(movecount,color) == 0)
color = 0; //don't step off the end
game.setMove(movecount,color);
//System.out.println("CV displayPos "+ movecount + "," + color);
subroutine = "setPosition";
theboard.setPosition(game.getPieceValues(movecount,color),
game.getPieceColors(movecount,color));
subroutine = "DisplayPosition";
if (listuse == MOVELIST){
if (yourColor == color)
statusLine.setText(res.getString("WAITING_ON_YOUR"));
else
statusLine.setText(res.getString("YOUR_MOVE"));
}
else
if (color == ChessRules.Black)
statusLine.setText(res.getString("WHITE_TO_MOVE"));
else
if (color == ChessRules.White)
statusLine.setText(res.getString("BLACK_TO_MOVE"));
else
statusLine.setText(res.getString("Color_")+String.valueOf(color)+"?");
setGameButtons();
}
//the browser is no longer displaying the applet. Let's be nice
//and end our chessclock thread if it is running
public void stop() {
System.out.println("ChessViewer.stop called");
if (clock != null) {
if (yourColor == 0)
opponentsTimeWhenStopped = playerTime[1];
else
opponentsTimeWhenStopped = playerTime[0];
timerWasStopped = true;
timeStopped = System.currentTimeMillis();
clock.stop();
}
clock = null;
}
//The browser is displaying the applet again. re-start the
//chessclock if it was running when the applet was last stopped.
public void start() {
System.out.println("ChessViewer.start called");
long opponentsTimeUsed;
long timeAway;
if (timerWasStopped) {
try {
int oppColor = 0;
if (yourColor == 0)
oppColor = 1;
opponentsTimeUsed = opponentsTimeWhenStopped - playerTime[oppColor];
timeAway = System.currentTimeMillis() - timeStopped;
if (opponentsTimeUsed == 0) {
if (color == yourColor)
playerTime[oppColor] = playerTime[oppColor] - timeAway;
else
playerTime[yourColor] = playerTime[yourColor] - timeAway;
}
else
playerTime[yourColor] = playerTime[yourColor] - timeAway - lMoveTime + opponentsTimeUsed;
clock = new Thread(this);
clock.start();
}
catch (Exception e) {
e.printStackTrace();
}
}
timerWasStopped = false;
}
//run gets called whenever a thread gets started
public void run() {
try{
if (threadFlag) {
threadFlag = false;
theboard.setImageURL((URL) pieceGif.elementAt(0));
validate();
repaint();
return;
}
//System.out.println("ChessViewer.run clock started");
clock.setPriority(Thread.MIN_PRIORITY);
long time = System.currentTimeMillis();
long nexttime;
int OnMove = ChessRules.White;
if (color == ChessRules.White)
OnMove = ChessRules.Black;
boolean enableSuspend = true;
if (OnMove == yourColor)
enableSuspend = false;
navBtn[3].setEnabled(enableSuspend);
synchronized (clock) {
while (true) {
try {
clock.wait(1000);
}
catch (InterruptedException e) {}
if (!(OnMove == yourColor ^ enableSuspend)) {
enableSuspend = !enableSuspend;
navBtn[3].setEnabled(enableSuspend);
}
nexttime = System.currentTimeMillis();
playerTime[OnMove] = playerTime[OnMove] + time - nexttime ;
time = nexttime;
if (playerTime[OnMove] < 0) {
String rslt = res.getString("BLACK_LOST_ON_TIME");
if (OnMove == ChessRules.White)
rslt = res.getString("WHITE_LOST_ON_TIME");
if (OnMove == yourColor) {
sendMsg("Resigned",rslt);
//statusLine.setText(rslt); status given when msg comes back from server
gameOver(rslt);
}
}
if (OnMove == 1 && blackOnTop || OnMove == 0 && !blackOnTop)
topTime.setText(formatTime(playerTime[OnMove]));
else
bottomTime.setText(formatTime(playerTime[OnMove]));
if (color == ChessRules.White)
OnMove = ChessRules.Black;
else
OnMove = ChessRules.White;
}
}
}
catch (ThreadDeath e) {
System.out.println("ChessViewer.run died");
throw e;
}
}
String formatTime(long milliseconds) {
String time;
if (milliseconds < 0 )
milliseconds = 0;
long seconds = milliseconds / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
seconds = seconds - (60 * minutes);
minutes = minutes - (60 * hours);
String sec;
String min;
if (seconds < 10)
sec = "0" + seconds;
else
sec = String.valueOf(seconds);
if (minutes < 10)
min = "0" + minutes;
else
min = String.valueOf(minutes);
//if (hours != 0 || minutes > 9)
time = String.valueOf(hours) + ":" + min;
//else
// time = min + ":" + sec;
if (hours != 0 )
time = String.valueOf(hours) + ":" + min + ":" + sec;
else
time = min + ":" + sec;
return time;
}
void fillList(String msg) {
//System.out.println("CV processing List");
int index = 0;
int oldindex = 0;
int matchchar = '?';
String newname;
List c = playerList;
Vector v = listContents;
if (listuse == LIBRARYLIST) {
c = libraryList;
v = libraryListContents;
}
c.removeAll();
v.removeAllElements();
if (msg != null) {
while (index != -1) {
index = msg.indexOf(matchchar,oldindex);
if (index != -1) {
v.addElement(msg.substring(oldindex,oldindex+1));
newname = msg.substring(oldindex+1,index);
oldindex = index +1;
c.addItem(newname);
}
}
}
else
c.setVisible(true);
}
//always add to the end of the array (count is the size of the array)
//don't assume the new move comes after the last move
//in kibitz mode the board position can be altered to somewhere in the middle
void addMove(String movemsg) {
//System.out.println("ChessViewer.addMove " + movemsg);
int timeIndex = movemsg.indexOf(' ');
String time = movemsg.substring(0,timeIndex);
long timeremaining = 0;
try {
timeremaining = Long.parseLong(time);
}
catch (NumberFormatException e) {
System.out.println (time + " is not a number");
}
int varindex = movemsg.indexOf('@');
if (opponentName == null)
movecount = count;
int prevsub = movecount;
if (varindex > timeIndex){
timeIndex = movemsg.indexOf(' ',varindex+1);
try {
prevsub = Integer.parseInt(movemsg.substring(varindex+1,timeIndex));
}
catch (NumberFormatException e) {
System.out.println("could not read variation subscript in " + movemsg) ;
}
}
String movetxt = movemsg.substring(timeIndex + 1);
String sMovenum;
int spaceindex = movetxt.indexOf('.');
sMovenum = movetxt.substring(0,spaceindex);
int movenum = Integer.parseInt(sMovenum);
spaceindex++;
int index = movetxt.indexOf('_');
int temp = 0;
if (index > 0)
temp = movetxt.indexOf(' ',index);
//System.out.println("found _ at " + index);
//int clr = Chessboard.WhitePiece;
int clrsub = ChessRules.White;
String moveNotation ;
if (index > 0) { //new line in listbox needed
if (prevsub == movecount)
prevsub++;
movecount++;
}
if (index > 0 && index > temp) { //whites move
playerTime[0] = timeremaining;
if (blackOnTop)
bottomTime.setText(formatTime(timeremaining));
else
topTime.setText(formatTime(timeremaining));
//System.out.println("White move " + movetxt+ index);
clrsub = ChessRules.White;
moveNotation = movetxt.substring(spaceindex+1,movetxt.lastIndexOf(' '));
}
else {
playerTime[1] = timeremaining;
if (blackOnTop)
topTime.setText(formatTime(timeremaining));
else
bottomTime.setText(formatTime(timeremaining));
clrsub = ChessRules.Black;
moveNotation = movetxt.substring(movetxt.lastIndexOf(' '));
}
//System.out.println("move is " + Move[movecount][clrsub].Movetxt +
// "; movenum is " + String.valueOf(movenum) +
// "; color=" + String.valueOf(clrsub));
game.addMove(movecount,clrsub,moveNotation,movenum,prevsub);
gridControl1.setSubfocus(movecount-1,clrsub + 1);
color = clrsub;
if (clock != null)
synchronized (clock) {
clock.notify(); //time to punch the chess clock
}
count = movecount;
//displayPos();
}
void switchSides() {
blackOnTop = theboard.switchOrientation();
if (blackOnTop) {
bottomName.setText(game.getPlayerW());
topName.setText(game.getPlayerB());
topTime.setText(formatTime(playerTime[1]));
bottomTime.setText(formatTime(playerTime[0]));
}
else {
bottomName.setText(game.getPlayerB());
topName.setText(game.getPlayerW());
topTime.setText(formatTime(playerTime[0]));
bottomTime.setText(formatTime(playerTime[1]));
}
}
public void setListButtons(int use) {
listuse = use;
switch (use) {
case MOVELIST:
sbChoose.setEnabled(false);
listPanel.setSelectedTab(res.getString("Moves"));
break;
case PLAYERLIST:
sbChoose.setEnabled(true);
sbChoose.setLabel(res.getString("COPY_PASTE"));
break;
case LIBRARYLIST:
sbChoose.setEnabled(true);
sbChoose.setLabel(res.getString("VIEW"));
System.out.println("show library list");
break;
case KIBITZ:
sbChoose.setEnabled(true);
sbChoose.setLabel(res.getString("COPY_PASTE"));
navBtn[0].setLabel(res.getString("BEGINNING_OF_GAME"));
navBtn[1].setLabel(res.getString("BACK_ONE_MOVE"));
navBtn[3].setLabel(res.getString("FORWARD_ONE_MOVE"));
navBtn[2].setLabel(res.getString("END_OF_GAME"));
setGameButtons();
}
}
void gameOver(String result) {
game.setResult(result);
System.out.println("setResult " + result);
gameOver();
}
void gameOver() {
setListButtons(ChessViewer.KIBITZ);
gameTime.setEnabled(true);
moveTime.setEnabled(true);
gridControl1.setEnabled(true);
opponentName = null;
if (clock != null)
clock.stop();
timerWasStopped = false;
clock = null;
if (yourColor == ChessRules.Black)
moveToken = false;
}
public void watch(String gameName) {
int index = gameName.lastIndexOf(':');
if (index > 0)
sendMsg("Watching",gameName.substring(0,index));
else {
infoText.setText(res.getString("Cannot_find_game"));
System.out.println("Cannot find game " + gameName);
}
}
void getGame(String name) {
String gamePGN = (String) libraryHash.get(name) ;
try {
game.parsePGNFile (new StringReader(gamePGN));
infoText.setText(game.getInfo());
}
catch (Exception e) {}
setNames();
fillMoveList();
movecount = 1;
color = 0;
setListButtons(ChessViewer.KIBITZ) ;
listPanel.setSelectedTab(res.getString("Moves"));
setGameButtons();
hasListeners = false;
displayPos();
//System.out.println("ML chessboard enabled");
theboard.setEnabled(true);
moveToken = true;
}
public void playerListEvent(AWTEvent evt) {
if (doNothing) //fake modal dialog on the loose
return ;
String listContent = "?";
//System.out.println("handling event for list c");
int selectedIndex = playerList.getSelectedIndex();
//System.out.println("listuse = " + listuse);
//System.out.println("listuse = PLAYERLIST");
if (selectedIndex >= 0)
listContent = (String)listContents.elementAt(selectedIndex);
if (listContent.equals("P")) {
if (evt.getID() == Event.ACTION_EVENT)
challenge(playerList.getSelectedItem());
else
if (evt.getID() == Event.LIST_SELECT){
getInfo(playerList.getSelectedItem());
}
else
if (evt.getID() == Event.LIST_DESELECT)
sbChoose.setLabel(res.getString("COPY_PASTE"));
}
else
if (listContent.equals("A")) {
if (evt.getID() == Event.ACTION_EVENT)
watch(playerList.getSelectedItem());
else {
sbChoose.setEnabled(true);
sbChoose.setLabel(res.getString("OBSERVE"));
}
}
else {
if (listContent.equals("G")) {
if (evt.getID() == Event.ACTION_EVENT)
sendMsg("Resume",String.valueOf(selectedIndex));
else {
sbChoose.setEnabled(true);
sbChoose.setLabel(res.getString("RESUME"));
}
}
}
}
void libraryListEvent(AWTEvent evt) {
//System.out.println("Gamelist handle");
if (doNothing) //fake modal dialog on the loose
return ;
if (evt.getID() == Event.ACTION_EVENT)
chooseGame();
else {
int [] selItems = libraryList.getSelectedIndexes();//returns null if multiple selections are not enabled
if (selItems == null) {
selItems = new int[1] ;
selItems[0] = libraryList.getSelectedIndex();
}
if (selItems.length == 0)
sbChoose.setLabel(res.getString("COPY_PASTE"));
else {
if (selItems.length == 1)
sbChoose.setLabel(res.getString("VIEW"));
else
sbChoose.setLabel(res.getString("GET"));
}
}
}
public static Frame getFrame(Component theComponent) {
Component currParent = theComponent;
Frame theFrame = null;
while (currParent != null) {
if (currParent instanceof Frame){
theFrame = (Frame) currParent;
break;
}
currParent = currParent.getParent();
}
return theFrame;
}
void gridControl1_subfocusChanged(borland.jbcl.model.MatrixSubfocusEvent e) {
if (doNothing) {//fake modal dialog on the loose
//System.out.println("do nothing");
return ;
}
if (listuse == MOVELIST || listuse == KIBITZ) {
MatrixLocation test = e.getLocation();
if (test != null) {
if (test.column < 2)
color = 0;
else
color = 1;
if (test.row == 0 && test.column == 0) {
// if the very first grid cell is clicked, then go to
// initial condition (movecount = 0, color = 1)
movecount = 0;
color = 1;
}
else if (test.row >= 0)
movecount = test.row+1;
//System.out.println("Display cell " + test.row +", "+ test.column);
displayPos();
}
}
}
void listPanel_subfocusChanging(borland.jbcl.model.VectorSubfocusEvent e) throws VetoException{
System.out.println("tabset panel subfocus changing " + e.getLocation());
if (listuse == MOVELIST)
if (e.getLocation() != MOVELIST && opponentName != null)
throw new VetoException() ;
else
return;
if (e.getLocation() == PLAYERLIST) {
listuse = PLAYERLIST;
sendMsg("List","") ;
}
else if (e.getLocation() == LIBRARYLIST){
listuse = LIBRARYLIST;
if (libraryListContents.size() == 0)
getLibraryList();
}
else
listuse = KIBITZ;
setListButtons(listuse);
}
} //end of class ChessViewer
class ChessboardAdapt implements ActionListener
{
ChessViewer adaptee;
public void actionPerformed(ActionEvent e) {adaptee.moveInfo();}
ChessboardAdapt(ChessViewer adaptee) {this.adaptee = adaptee;}
}
class OtherActionAdapter implements ActionListener
{
ChessViewer adaptee;
public void actionPerformed(ActionEvent e) {adaptee.otherAction(e);}
OtherActionAdapter(ChessViewer adaptee) {this.adaptee = adaptee;}
}
class BoardButtonActionAdapter implements ActionListener
{
ChessViewer adaptee;
public void actionPerformed(ActionEvent e) {adaptee.boardButtonAction(e);}
BoardButtonActionAdapter(ChessViewer adaptee) {this.adaptee = adaptee;}
}
class PlayerListAdapter implements ActionListener,ItemListener
{
ChessViewer adaptee;
PlayerListAdapter(ChessViewer adaptee) {this.adaptee = adaptee;}
public void actionPerformed(ActionEvent e) {adaptee.playerListEvent(e);}
public void itemStateChanged(ItemEvent e) {adaptee.playerListEvent(e);}
}
class LibraryListAdapter implements ActionListener,ItemListener
{
ChessViewer adaptee;
LibraryListAdapter(ChessViewer adaptee) {this.adaptee = adaptee;}
public void actionPerformed(ActionEvent e) {adaptee.libraryListEvent(e);}
public void itemStateChanged(ItemEvent e) {adaptee.libraryListEvent(e);}
}
class ChessViewer_gridControl1_SubfocusAdapter extends MatrixSubfocusAdapter
{
ChessViewer adaptee;
ChessViewer_gridControl1_SubfocusAdapter(ChessViewer adaptee) {
this.adaptee = adaptee;
}
public void subfocusChanged(borland.jbcl.model.MatrixSubfocusEvent e) {
adaptee.gridControl1_subfocusChanged(e);
}
}
class ChessViewer_listPanel_SubfocusAdapter extends VectorSubfocusAdapter
{
ChessViewer adaptee;
ChessViewer_listPanel_SubfocusAdapter(ChessViewer adaptee) {
this.adaptee = adaptee;
}
public void subfocusChanging(borland.jbcl.model.VectorSubfocusEvent e) throws VetoException {
adaptee.listPanel_subfocusChanging(e);
}
}
//simple class that does double duty as the
//grids columnheader viewmanager and model
class GC_ColumnHeaderManager implements VectorViewManager, VectorModel
{
public GC_ColumnHeaderManager(ColumnView[] columns) {
this.columns = columns;
}
public Object get(int index) {
String caption = columns[index].getCaption();
if (caption == null)
caption = String.valueOf(index);
return caption;
}
public ItemPainter getPainter(int index, Object data, int state) { return painter; }
public ItemEditor getEditor(int index, Object data, int state) { return null; }
public int find(Object data) { return -1; }
public int getCount() { return columns.length; }
public void addModelListener(VectorModelListener listener) { modelListeners.add(listener); }
public void removeModelListener(VectorModelListener listener) { modelListeners.remove(listener); }
private borland.jbcl.util.EventMulticaster modelListeners = new borland.jbcl.util.EventMulticaster();
private ColumnView[] columns;
private ItemPainter painter = new TextItemPainter(Alignment.CENTER | Alignment.MIDDLE, new Insets(0,2,0,2));
}