home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
PC World 1998 October
/
PCWorld_1998-10_cd.bin
/
software
/
prehled
/
inprise
/
JSAMPLES.Z
/
PlayerId.java
< prev
next >
Wrap
Text File
|
1998-05-08
|
15KB
|
431 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.
*/
package borland.samples.apps.chess.server;
import java.io.*;
import java.util.*;
import java.lang.*;
import borland.samples.apps.chess.client.PersistString;
class PlayerId
{
public static Hashtable usersByUser = new Hashtable();
public static Hashtable usersById = new Hashtable();
private final static File partialGames = new File("Suspended"); //directory for holding suspended games
private final static File userlist = new File("users.txt"); //file that holds user list
private static int nextId = 4096; //highest userid, for constructing new users id's
private static boolean userListIsDirty = false;
String id = null; //unique string representation of a hex number. Key to usersById
String user = null; //unique key to usersByUser
String password;
String name;
String email;
String location;
String extra; //whatever
Vector message; //array of undelivered messages
int rating; //elo rating
int gamesPlayed; //number of games played
long lastNoteTime;
Vector partialGame; //list of users suspended game filenames
public PlayerId(String user,String password){
int idNum = PlayerId.nextId++;
id = "000" + Integer.toHexString(idNum);
if (id.length() > 4)
id = id.substring(id.length() - 4);
this.user = user;
this.password = password;
message = new Vector();
name = " ";
email = " ";
location = " ";
extra = " ";
rating = 1200;
partialGame = new Vector(1);
gamesPlayed = 0;
lastNoteTime = 0;
}
public void isDirty() {
userListIsDirty = true;
}
public void update(String password,String email,String name,String location,String extra) {
this.password = password;
this.name = name;
this.email = email;
this.location = location;
this.extra = extra;
PlayerId.userListIsDirty = true;
}
public PlayerId() {
partialGame = new Vector(5);
message = new Vector();
}
public boolean addPlayer() {
if (id != null && user != null) {
PlayerId.usersByUser.put(user,this);
PlayerId.usersById.put(id,this);
PlayerId.userListIsDirty = true;
return true;
}
return false;
}
void addNote(String msg) {
long now = System.currentTimeMillis();
if (now - lastNoteTime > 180000) {
message.addElement(new Date(now).toString());
lastNoteTime = now;
}
message.addElement(msg);
isDirty();
}
void read(String data) {
try {
String [] temp = PersistString.parse(data);
id = temp[0];
user = temp[1];
password = temp[2];
name = temp[3];
email = temp[4];
location = temp[5];
extra = temp[6];
rating = Integer.parseInt(temp[7]);
gamesPlayed = Integer.parseInt(temp[8]);
for (int i= 9;i<temp.length;i++)
message.addElement(temp[i]);
//System.out.println ("user=" + user + " name=" + name + " rating=" + rating);
PlayerId.userListIsDirty = true; // this method is used to update data
}
catch (Exception e) {System.out.println("PlayerId.read " + e);
System.out.println("record: " + data);
}
}
public String output() {
String [] temp = new String [9+ message.size()];
temp[0] = id;
temp[1] = user ;
temp[2] = password ;
temp[3] = name ;
temp[4] = email;
temp[5] = location ;
temp[6] = extra ;
temp[7] = String.valueOf(rating);
temp[8] = String.valueOf( gamesPlayed) ;
for (int i = 0; i < message.size(); i++)
temp[i+9] = (String) message.elementAt(i);
return PersistString.concat(temp);
}
public void addGame(String filename) {
partialGame.addElement(filename);
}
public static void readUserFile() {
int numUsers = 0;
try {
// partialGames = new File("Suspended");
//userlist = new File("users.txt");
if (userlist.exists()) {
FileInputStream fs = new FileInputStream(userlist);
DataInputStream ds = new DataInputStream(fs);
InputStreamReader isr = new InputStreamReader(ds);
BufferedReader br = new BufferedReader(isr);
PlayerId temp;
String inputData;
while (true) {
inputData = br.readLine();
if (inputData == null || inputData.length() < 10)
break;
else
//System.out.println(inputData);
temp = new PlayerId() ;
temp.read(inputData);
numUsers++;
if (temp.addPlayer()) {
try {
int intId = Integer.parseInt(temp.id,16);
if (intId >= nextId)
nextId = intId + 1;
}
catch (NumberFormatException e) { System.out.println (temp.id + "is not a hex number"); }
}
else
System.out.println(temp.id + " " + temp.user + ": junk data in user file");
}
fs.close();
}
else
System.out.println("User database " + userlist.getAbsolutePath() + " not found ");
System.out.println("Read " + numUsers + " userId records from " + userlist.getAbsolutePath());
constructSuspendLists();
PlayerId.userListIsDirty = false;
}
catch (Exception e) {System.out.println("Exception after reading " + numUsers + " " + e);}
}
private static void constructSuspendLists() {
PgnFilter filter = new PgnFilter(13);
if (filter == null)
System.out.println("file filter object is null??");
if (partialGames == null)
System.out.println("game directory object is null??");
else if (!partialGames.exists())
partialGames.mkdir();
String [] dirlist = partialGames.list(filter);
if (dirlist != null)
for (int i=0; i<dirlist.length;++i) {
PlayerId white = (PlayerId)usersById.get(dirlist[i].substring(0,4));
PlayerId black = (PlayerId)usersById.get(dirlist[i].substring(4,8));
if (white != null && black != null) {
System.out.println("added game " + dirlist[i] + " to " + white.user + " & " + black.user + "'s suspended list");
white.addGame(dirlist[i]);
black.addGame(dirlist[i]);
}
else
System.out.println("could not find id " + dirlist[i].substring(0,8));
}
else
System.out.println("Suspended game directory is empty");
}
//game is over. if it was a suspended game, delete it
public static void recordResult(Game g,String result) {
PlayerId white = (PlayerId) PlayerId.usersByUser.get(g.white) ;
PlayerId black = (PlayerId) PlayerId.usersByUser.get(g.black) ;
if (g.filename != null) {
black.partialGame.removeElement(g.filename);
white.partialGame.removeElement(g.filename);
File file = new File("Suspended",g.filename);
if (file.delete())
System.out.println("deleted " + g.filename);
else
System.out.println("delete " + g.filename + " failed ");
}
PlayerId winner = white;
PlayerId loser = black;
int loserdelta;
int winnerdelta;
if (result.startsWith("Abort"))
return;
if (result.startsWith("1/2-1/2")) {
if (winner.gamesPlayed < 20)
winner.rating = ((winner.rating * winner.gamesPlayed) +
loser.rating ) / (winner.gamesPlayed + 1) ;
else
winner.rating = winner.rating - elo(winner.rating - loser.rating);
if (winner.gamesPlayed < 20)
loser.rating = ((loser.rating * loser.gamesPlayed) +
winner.rating ) / (loser.gamesPlayed + 1) ;
else
loser.rating = loser.rating + elo(winner.rating - loser.rating);
}
else {
if (result.startsWith("0-1")) {
winner = black;
loser = white;
}
winnerdelta = loser.rating + 400;
loserdelta = winner.rating - 400;
if (winner.gamesPlayed < 20)
winner.rating = ((winner.rating * winner.gamesPlayed) +
winnerdelta ) / (winner.gamesPlayed + 1) ;
else
winner.rating = winner.rating + 16 - elo(winner.rating - loser.rating);
if (loser.gamesPlayed < 20)
loser.rating = ((loser.rating * loser.gamesPlayed) +
loserdelta ) / (loser.gamesPlayed + 1) ;
else
loser.rating = loser.rating - 16 + elo(winner.rating - loser.rating);
}
winner.gamesPlayed++;
loser.gamesPlayed++;
PlayerId.userListIsDirty = true;
}
static int elo(int ratingdiff) {
int distribution[] = {0,12,34,56,8,101,126,151,177,206,239,273,315,366,446,471,714};
int sign = 1;
if (ratingdiff < 0) {
sign = -1;
ratingdiff = -ratingdiff;
}
int oldsub = -1;
int i = 8;
int maxsub = 16;
int minsub = 0;
while (oldsub != i) {
oldsub = i;
i = (maxsub + minsub) /2;
if (ratingdiff > distribution[i])
minsub = i;
else
maxsub = i;
}
return oldsub * sign;
}
//Game is being suspended. Delete old version (if any) and
//write game to disk
public static void suspendGame(Game g) {
String tomove = "1";
if (g.whitetomove)
tomove = "0" ;
String suffix = tomove + String.valueOf(g.offerFlag) + String.valueOf(g.movenum); //1 digit
String gameName;
PlayerId black = null;
PlayerId white = null;
if (g.filename != null ) {
if (g.blackId == null || g.whiteId == null)
System.out.println("weird Game object " + g.filename + g.white + g.black);
if (g.filename.substring(8).equals(suffix + ".pgn"))
return;
}
white = (PlayerId) PlayerId.usersByUser.get(g.white) ;
black = (PlayerId) PlayerId.usersByUser.get(g.black) ;
gameName = white.id + black.id + suffix + ".pgn";
try {
File file = new File("Suspended",gameName);
System.out.println("Saving " + gameName);
if (file == null)
System.out.println("could not open file");
FileOutputStream fs = new FileOutputStream(file);
PrintWriter ps = new PrintWriter(fs);
ps.print(g.getMoves());
ps.flush();
ps.close();
System.out.println("Wrote file");
if (g.filename != null) {
black.partialGame.removeElement(g.filename);
white.partialGame.removeElement(g.filename);
file = new File("Suspended",g.filename);
if (file.delete())
System.out.println("deleted " + g.filename);
else
System.out.println("delete " + g.filename + " failed ");
}
black.partialGame.addElement(gameName);
white.partialGame.addElement(gameName);
g.filename = gameName;
g.blackId = black.id;
g.whiteId = white.id;
}
catch (Exception e ) {
System.out.println("err in SuspendGame " + e);
}
}
//Create a game object for the suspended game file
public Game getGame(String filename) {
Game g = null;
try {
File gamefile = new File("Suspended",filename);
FileInputStream fs = new FileInputStream(gamefile) ;
DataInputStream ds = new DataInputStream(fs);
InputStreamReader isr = new InputStreamReader(ds);
BufferedReader br = new BufferedReader(isr);
String moves = br.readLine();
fs.close();
String whiteId = filename.substring(0,4);
String blackId = filename.substring(4,8);
String tomove = filename.substring(8,9);
int movenum = Integer.parseInt(filename.substring(10,filename.indexOf('.',9)));
PlayerId white = (PlayerId) PlayerId.usersById.get(whiteId);
PlayerId black = (PlayerId) PlayerId.usersById.get(blackId);
g = new Game(white.user,black.user);
g.offerFlag = Integer.parseInt(filename.substring(9,10));
g.movenum = movenum;
int index;
if (tomove.equals("0"))
g.whitetomove = true;
else {
g.whitetomove = false;
index = moves.lastIndexOf('.') ;
String temp = moves.substring(index-5,index);
System.out.println("temp=" + temp);
int index1 = temp.lastIndexOf(' ');
g.whitesLastMove = moves.substring(index - 4 + index1);
System.out.println("indexes="+index + "," + index1+ g.whitesLastMove);
}
g.setInfo();
index = moves.indexOf("Whitetime");
int endindex = moves.indexOf("]",index);
g.whiteTime = moves.substring(index+10,endindex);
index = moves.indexOf("Blacktime");
endindex = moves.indexOf("]",index);
g.blackTime = moves.substring(index+10,endindex);
index = moves.indexOf("Movetime");
endindex = moves.indexOf("]",index);
g.moveTime = moves.substring(index+9,endindex);
g.moves = moves.substring(endindex+1);
g.whiteId = whiteId;
g.blackId = blackId;
g.filename = filename;
}
catch (Exception e) {System.out.println("PlayerId.getGame " + e);}
return g;
}
static public void writeUserList() {
if (!PlayerId.userListIsDirty)
return;
FileOutputStream fo = null;
PrintWriter ps = null;
//System.out.println("Trying to write out updated user List") ;
try {
fo = new FileOutputStream(PlayerId.userlist);
ps = new PrintWriter(fo);
}
catch (Exception e) {System.out.println("Things look bad for the home team");}
PlayerId p = null;
if (ps != null) {
for (Enumeration e = PlayerId.usersById.elements(); e.hasMoreElements();) {
p = (PlayerId) e.nextElement();
//System.out.println("Writing " + p.user );
ps.println(p.output());
}
System.out.println("Updated the user List");
ps.flush();
ps.close();
PlayerId.userListIsDirty = false;
}
}
} //end of class
class PgnFilter implements FilenameFilter {
int minFileNameLength = 2;
public PgnFilter(int length) {
minFileNameLength = length;
}
public boolean accept(File dir,String name) {
if ( name != null && name.endsWith(".pgn") && name.length() > minFileNameLength)
return true;
else {
System.out.println("Threw out " + name );
return false;
}
}
}