📄 311-314.html
字号:
<HTML>
<HEAD>
<META name=vsisbn content="1571690433"><META name=vstitle content="Black Art of Java Game Programming"><META name=vsauthor content="Joel Fan"><META name=vsimprint content="Sams"><META name=vspublisher content="Macmillan Computer Publishing"><META name=vspubdate content="11/01/96"><META name=vscategory content="Web and Software Development: Programming, Scripting, and Markup Languages: Java"><TITLE>Black Art of Java Game Programming:Implementing a High Score Server on a Network</TITLE>
<!-- HEADER --><STYLE type="text/css"> <!-- A:hover { color : Red; } --></STYLE><META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW"><script><!--function displayWindow(url, width, height) { var Win = window.open(url,"displayWindow",'width=' + width +',height=' + height + ',resizable=1,scrollbars=yes'); if (Win) { Win.focus(); }}//--></script><SCRIPT><!--function popUp(url) { var Win = window.open(url,"displayWindow",'width=400,height=300,resizable=1,scrollbars=yes'); if (Win) { Win.focus(); }}//--></SCRIPT><script language="JavaScript1.2"><!--function checkForQuery(fm) { /* get the query value */ var i = escape(fm.query.value); if (i == "") { alert('Please enter a search word or phrase'); return false; } /* query is blank, dont run the .jsp file */ else return true; /* execute the .jsp file */}//--></script></HEAD><BODY>
<TABLE border=0 cellspacing=0 cellpadding=0>
<tr>
<td width=75 valign=top>
<img src="../1571690433.gif" width=60 height=73 alt="Black Art of Java Game Programming" border="1">
</td>
<td align="left">
<font face="arial, helvetica" size="-1" color="#336633"><b>Black Art of Java Game Programming</b></font>
<br>
<font face="arial, helvetica" size="-1"><i>by Joel Fan</i>
<br>
Sams, Macmillan Computer Publishing
<br>
<b>ISBN:</b> 1571690433<b> Pub Date:</b> 11/01/96</font>
</td>
</tr>
</table>
<P>
<!--ISBN=1571690433//-->
<!--TITLE=Black Art of Java Game Programming//-->
<!--AUTHOR=Joel Fan//-->
<!--AUTHOR=Eric Ries//-->
<!--AUTHOR=Calin Tenitchi//-->
<!--PUBLISHER=Macmillan Computer Publishing//-->
<!--IMPRINT=Sams//-->
<!--CHAPTER=8//-->
<!--PAGES=311-314//-->
<!--UNASSIGNED1//-->
<!--UNASSIGNED2//-->
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="309-311.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="../ch09/315-318.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>
<P><BR></P>
<H4 ALIGN="LEFT"><A NAME="Heading50"></A><FONT COLOR="#000077">Writing Scores Out to a File</FONT></H4>
<P>A list of high scores isn’t too useful if it is lost when the server quits. We therefore need a way to write it out to a file. Luckily, files in Java aren’t too tricky. They are just another kind of Stream. The important thing here will be having a delay between file writes, because we don’t want to tie down the server with constant writing. Also, we don’t want to write anything if there is nothing new to write. It is very, very tricky to do this within the ServerThread thread, because we never know how long the thread is waiting for a connection. (Since accept() blocks, this could potentially be hours or days or years.) The solution is to use another thread, this one designed exclusively for writing the scores to a file, but using the very same HighScoreList as the ServerThread. Because reading and writing a file is just like doing the same to a socket, this should seem pretty straightforward. Here is SaveFileThread.java:
</P>
<!-- CODE //-->
<PRE>
import java.lang.*;
import java.io.*;
import HighScoreList;
public class SaveFileThread extends Thread {
HighScoreList L;
final int FILE_DELAY = 100000;
File f;
long lastWrite;
SaveFileThread(HighScoreList theList, File theFile) {
L = theList;
f = theFile;
}
public void run() {
while( L != null ) {
if(f.exists())
f.renameTo(new File("test.bak"));
if( L.lastChange > lastWrite) {
try {
PrintStream ps = new PrintStream(new FileOutputStream(f));
ps.println( L.toDataString() );
System.out.println("Writing High Scores to file "+f.getName());
lastWrite = System.currentTimeMillis();
ps.close();
} catch (Exception e);
}
try{ sleep(FILE_DELAY); } catch (Exception e);
}
}
}
</PRE>
<!-- END CODE //-->
<P>In order to make use of this, we are going to have to change main() in HighScoreServer. The method now has to read in the values already stored in a user-specified file, pass this data to the HighScoreList, and then pass the File, along with the list, to the SaveFileThread. It then must start both the SaveFileThread and the ServerThread. Here’s what that looks like:
</P>
<!-- CODE //-->
<PRE>
import java.net.*;
import java.io.*;
import HighScoreList;
import ServerThread;
import SaveFileThread;
class HighScoreServer{
public static void main(String args[]) {
HighScoreList theList = null;
File theFile = new File(args[1]);
String temp = null;
if (!theFile.exists())
System.out.println("No such file\nWill create a new one");
else {
try {
DataInputStream dis = new DataInputStream( new FileInputStream( ⇐
theFile) );
temp = dis.readLine();
} catch (Exception e) {
System.out.println("Unable to read from file. Terminating...");
System.exit(1);
}
}
if(temp != null)
theList = new ⇐
HighScoreList(Integer.valueOf(args[0]).intValue(),temp);
else
theList = new HighScoreList(Integer.valueOf(args[0]).intValue());
if(theList == null) {
System.out.println("Unable to initzialize. Terminating...");
System.exit(1);
}
new ServerThread(theList).start();
new SaveFileThread(theList, theFile).start();
System.out.println("Server initialized. Tracking "+args[0]+" ⇐
scores.\nUsing "+args[1]);
}
}
</PRE>
<!-- END CODE //-->
<H4 ALIGN="LEFT"><A NAME="Heading51"></A><FONT COLOR="#000077">Running the New Server</FONT></H4>
<P>Congratulations! You’ve done it! Compile all your classes, and then start the server with <I>java HighScoreServer 10 data.txt</I> or any other values you like. If the server can’t find the file you specify, it will create a new one. Otherwise, it will attempt to read in the values contained in the file you specify. If this is successful, it should tell you so, and it will then wait for a connection. Load up a few clients with Appletviewer and have fun! If you or a friend have a WWW page, recompile the client to check <I>your</I> IP address and then set it up on the Web page. It will connect seamlessly to your host.</P>
<H3><A NAME="Heading52"></A><FONT COLOR="#000077">Suggestion Box</FONT></H3>
<P>This chapter opens up a whole plethora of possibilities to enhance the high score experience. Try these:
</P>
<DL>
<DD><B>•</B> Extend the HSob structure to include even more data. Perhaps comments or messages that can be viewed by other users. Perhaps use an array to have the HSob hold an unlimited amount of data, and allow the applet to decide what each value is used for.
<DD><B>•</B> Enhance the HighScoreManager class to interact with the user. Perhaps allow the user to send e-mail to a high scorer if the user clicks on that person’s name. This can be accomplished by having the applet context open a URL that starts with “mailto:”. You could also have the HighScoreManager display comments or messages stored as per the previous suggestion.
<DD><B>•</B> Take the code we’ve written in this chapter and plug it into one of the games you’ve written so far (I recommend JavaBlaster). This is pretty easy if you make use of HighScoreManager’s paintScores() method.
</DL>
<H3><A NAME="Heading53"></A><FONT COLOR="#000077">Summary</FONT></H3>
<P>In this chapter we explored the concept of high scores, and discussed how to implement them in Java, both locally and over a network. Being able to track high scores will make any game more enjoyable, and knowing how to do it will make you a better game programmer.
</P><P><BR></P>
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="309-311.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="../ch09/315-318.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>
</BODY>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -