⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 287-290.html

📁 java game programming e-book
💻 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,&nbsp;Macmillan Computer Publishing
    <br>
    <b>ISBN:</b>&nbsp;1571690433<b>&nbsp;&nbsp;&nbsp;Pub Date:</b>&nbsp;11/01/96</font>&nbsp;&nbsp;
</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=287-290//-->
<!--UNASSIGNED1//-->
<!--UNASSIGNED2//-->

<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="284-287.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="291-293.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>
<P><BR></P>
<H4 ALIGN="CENTER"><A NAME="Heading21"></A><FONT COLOR="#000077">Converting Data to Objects</FONT></H4>
<P>To successfully parse this string of data, we must take each name/score pair from the list and convert it to an HSob object. We could have just one method do all of this work, but, because we are going to want to be able to convert back and forth between raw data and objects, we are going to teach the HSob class how to handle raw data.
</P>
<P>Add a third initialization routine to HSob:</P>
<!-- CODE //-->
<PRE>
HSob(String data) &#123;
       Float fl = null;
       String str;
       StringTokenizer st = new StringTokenizer(data, "&#38;");
while (st.hasMoreTokens()) &#123;
        str = st.nextToken();
        if (name == null)
               name = str;
               else
        try &#123;
               fl = Float.valueOf( str );
               score = fl.floatValue();
          &#125; catch (Exception e) &#123;
 other = str;
        &#125;
        &#125;
  &#125;
</PRE>
<!-- END CODE //-->
<P>This method has some new things in it that you probably noticed. The first is an extra variable called <I>other</I>. This is a String that we are going to use to hold any additional information included besides the name and the score (be sure to declare this variable on the same line where you added the name).</P>
<P>Another new concept is the Float class. In Java, for every primitive data type (like int or float), there is a corresponding object class (like Integer or Float) that has some nifty utility methods useful for that data type. You may not know it, but you have already used one such class extensively: the String class.</P>
<P>A String object is just a special class for representing an array of characters. For now, we are going to use the Float class to transform a string representation of a float (like &#147;1000&#148;) into a Float object. You may have realized that this is exactly what we are teaching our HSob class to do! Once we have the Float object, we are then going to extract the actual float number from it, because we really don&#146;t care about the object, only its cargo. This is also the first time you have seen an Exception being caught&#151;don&#146;t fret, though, it won&#146;t be the last.</P>
<P>Before we leave the HSob class for a while, we should add another method that is going to be useful down the line a little bit. This method will take the HSob&#146;s current values and convert them into a raw data string.</P>
<!-- CODE SNIP //-->
<PRE>
public String toDataString() &#123;       //Convert an HSob into a data string

return name &#43; "&#38;" &#43; score &#43; "&#38;" &#43; other;
&#125;
</PRE>
<!-- END CODE SNIP //-->
<H4 ALIGN="CENTER"><A NAME="Heading22"></A><FONT COLOR="#000077">The parseData() Method</FONT></H4>
<P>It&#146;s time to write the data parsing method for the HighScoreList class. Because of all the work we just did with HSob, this is going to be really easy! We are going to have to use our friend the StringTokenizer class, so I hope you haven&#146;t forgotten it yet:
</P>
<!-- CODE //-->
<PRE>
public void parseData(String str) &#123;  // Parse a string of data
StringTokenizer st1=new StringTokenizer(str,"|");
String theStr;
               while (st1.hasMoreTokens()  ) &#123;
               theStr = st1.nextToken();
               if (! theStr.startsWith("null"))
                       addScore( new HSob (theStr));
                       &#125;
&#125;
</PRE>
<!-- END CODE //-->
<P>This bit of code references a method we haven&#146;t yet discussed, so we&#146;d better do that now.
</P>
<H4 ALIGN="CENTER"><A NAME="Heading23"></A><FONT COLOR="#000077">The addScore() Method</FONT></H4>
<P>This is a very important method, so be sure you understand how it works. Its task is to take an HSob and insert it (if applicable) into the list of scores in its proper place in the sequence. Since the list should already be in descending numerical order, all we have to do is search down the list until we find either (1) a lower score or (2) an empty slot. If we find either of these, we add our new score and drop all of the lower scores down one place. Here is the code:
</P>
<!-- CODE //-->
<PRE>
public int addScore(HSob sc) &#123;  // We return the place this score gets
int x,i;
x=0;

if (sc==null) return 0;

while (x&lt;NUM_SCORES) &#123;

if (scores[x] == null || sc.score &gt; scores[x].score) &#123;
       for( i=NUM_SCORES-2 ; i&gt;=x ; i--)
              scores[i&#43;1]=scores[i];
       scores[x]= sc;
lastChange = System.currentTimeMillis();
       return x&#43;1;
       &#125;
x&#43;&#43;;
&#125;

return 0;
&#125;
</PRE>
<!-- END CODE //-->
<P>So long as we never make any changes to the <I>scores[]</I> array except with addScore(), the array will always keep scores in descending order. This means we never have to sort it, which is good news for the speed of our program. Also, here we use the System method currentTimeMillis() to find out how many seconds have transpired since the current epoch began, and we store this in our long variable <I>lastChange</I> if and only if we have actually made a change to the list.</P>
<P>The HighScoreList class is almost finished. Only two things remain. Both of these methods allow the outside class a little more access to the list.</P>
<H4 ALIGN="CENTER"><A NAME="Heading24"></A><FONT COLOR="#000077">The tryScore() Method</FONT></H4>
<P>The first method is tryScore(), which takes a name/score pair, converts it into an HSob, and passes it to addScore(). If addScore() adds this HSob to the list, tryScore() returns a data string representing HSob. Otherwise, it returns null, indicating that the HSob did not make it onto the list. There are actually two tryScore() methods: The first accepts the name/score/etc. data separately, while the second accepts it as a data string. Only the second method actually does any work; the first method just converts the data it receives into a data string and calls the other tryScore(). Here is the code:
</P>
<!-- CODE //-->
<PRE>
public String tryScore( String name, float score, String email, String &#8656;
other) &#123;
HSob temp;

temp = new HSob (name, score, email, other);
return tryScore (temp.toDataString());
&#125;

public String tryScore( String data) &#123;

HSob temp = new HSob (data);
if (addScore(temp) &gt; 0)
       return temp.toDataString();
else
       return null;
&#125;
</PRE>
<!-- END CODE //-->
<H4 ALIGN="CENTER"><A NAME="Heading25"></A><FONT COLOR="#000077">The getScore() Method</FONT></H4>
<P>The last method is getScore(), which will return any individual member of the list if it exists:
</P>
<!-- CODE SNIP //-->
<PRE>
public HSob getScore(int num) &#123;
if (num &lt; NUM_SCORES)
       return scores[num];
else
       return null;
&#125;
</PRE>
<!-- END CODE SNIP //-->
<P>That&#146;s it! If you really want to, you can compile the HighScoreList, but unfortunately, you cannot run it. In fact, the HighScoreList is utterly useless by itself. You may feel that you have done all of this work for nothing, but you will soon see that putting a lot of work into the foundation classes will make writing the exciting stuff a <I>lot</I> easier. This is one of the lessons any OOP programmer has to learn very well.</P><P><BR></P>
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="284-287.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="291-293.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>


</BODY>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -