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

📄 639-642.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:NetOthello</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=15//-->
<!--PAGES=639-642//-->
<!--UNASSIGNED1//-->
<!--UNASSIGNED2//-->

<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="636-639.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="642-646.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>
<P><BR></P>
<H4 ALIGN="CENTER"><A NAME="Heading28"></A><FONT COLOR="#000077">Sending Moves</FONT></H4>
<P>The last thing we have to do in NetOthello is change the mouseDown() method to reflect all of the changes we have been making. It must check to see if it is the user&#146;s turn or not. Most importantly, we are not going to have mouseDown() call doMove() directly. Rather, it will send a message to the server that will get echoed back so that both clients will update at the same time. (We wouldn&#146;t want to give either client an advantage.) This is the very last piece of networking code we have to write. Here&#146;s how mouseDown() should work:
</P>
<!-- CODE //-->
<PRE>
public boolean mouseDown(Event evt, int x, int y) &#123;

if( turn == local) &#123; /* if it&#146;s our turn */
       if( validMoveXY(x,y,turn) ) &#123; /* if we got a valid move */
              int xx,yy;
                  xx= (int)(x/theBoard.pieceWidth);
                  yy=(int)(y/theBoard.pieceHeight);
              boolean flag=false;
/* be SURE the move gets sent */
       while( !flag )
               try&#123;
                   ps.println("move|"&#43;xx&#43;"|"&#43;yy);
                   ps.flush();
        System.out.println("Sent move: "&#43;xx&#43;","&#43;yy);
        flag = true;
        &#125; catch (Exception e) &#123;
             flag = false;
             &#125;
       return true;
       &#125;
&#125;

return false;
&#125;
</PRE>
<!-- END CODE //-->
<P>Congratulations! The networking code is finished. NetOthello can now successfully interact with a server and play Othello against another client applet running on another machine. Unfortunately, there is no server yet! Obviously, we are going to have to write that code next.
</P>
<H3><A NAME="Heading29"></A><FONT COLOR="#000077">Writing the GameServer</FONT></H3>
<P>Our goal with GameServer is to create a generic multiplayer game server that can be used with only slight modifications by any similar game client. The concepts behind it are very similar to those used to create the ChatServer in Chapter 9, Advanced Networking and Multiplayer Gaming Concepts, as is the class hierarchy, so be sure you understand that program before you proceed here.
</P>
<H4 ALIGN="LEFT"><A NAME="Heading30"></A><FONT COLOR="#000077">Step 1: Creating GameServer.class</FONT></H4>
<P>This class doesn&#146;t actually do very much except create a GameServerThread and start it. Its one responsibility is to get a port number from the user, or else default to 8314.
</P>
<!-- CODE //-->
<PRE>
import GameServerThread;

class GameServer &#123;
public static void main(String args[]) &#123;
int thePort;
try&#123;
       thePort = Integer.valueOf(args[0]).intValue();
&#125; catch (Exception e) &#123;
       thePort = 8314;
&#125;

new GameServerThread(thePort).start();
&#125;
&#125;
</PRE>
<!-- END CODE //-->
<H4 ALIGN="LEFT"><A NAME="Heading31"></A><FONT COLOR="#000077">Step 2: Writing GameServerThread.class</FONT></H4>
<P>This class has the responsibility of setting up a ServerSocket and accepting Socket connections from clients. It must also manage a list of GameGroups (again stored in a Vector) and pass the new connection along to the next open GameGroup to be handled. If there are no open GameGroups, it must create a new one. Once a GameGroup is full, it must be started by GameServerThread. GameServerThread also performs garbage collection on the list it maintains and weeds out any dead or disconnected GameGroups.
</P>
<P>The GameServerThread begins by establishing a server presence on the designated port:</P>
<!-- CODE //-->
<PRE>
import java.net.*;
import java.lang.*;
import java.util.*;
import GameGroup;

public class GameServerThread extends Thread &#123;
ServerSocket servSock = null;
Vector v;

GameServerThread(int port) &#123;
        try &#123;
            servSock = new ServerSocket(port);
        &#125; catch (Exception e) &#123;
            System.out.println("Could not initialize. Exiting.");
            System.exit(1);
        &#125;
System.out.println("Server successfully initialized. Waiting for connec-
tion on port "&#43;port);
v = new Vector();
&#125;
</PRE>
<!-- END CODE //-->
<P>Once the GameServerThread is started, it waits, accepting connections and handing them off to GameGroups as necessary:
</P>
<!-- CODE //-->
<PRE>
public void run() &#123;
GameGroup tempGroup=null;

while(servSock != null ) &#123;
Socket tempSock;
        try &#123;
        tempSock = servSock.accept();
        System.out.println("Received New Connection.");
        if( !v.isEmpty() ) &#123;
               tempGroup = (GameGroup)v.lastElement();
               if( tempGroup.full() )
              v.addElement(  new GameGroup( tempSock ) );
              else &#123;
                      tempGroup.addClient(tempSock);
                      if( tempGroup.full() )
                             tempGroup.start();

               &#125;
         &#125; else
                      v.addElement(new GameGroup( tempSock ) );
for( int x=0; x&lt;v.size()-1;x&#43;&#43;)
       if( !((GameGroup)v.elementAt(x)).isAlive() )
              v.removeElementAt(x);

        &#125; catch (Exception e) &#123;
            System.out.println("New Connection Failure. Exiting.\n"&#43;e);
          System.exit(1);
        &#125;
try&#123; sleep(100); &#125; catch (Exception e);
&#125;
&#125;
</PRE>
<!-- END CODE //-->
<P>It weeds out any dead threads from the Vector here. The last thing the GameServerThread has to do is clean up after itself when it is destroyed. This can only happen when the whole program is about to exit, so we can get rid of the ServerSocket:
</P>
<!-- CODE SNIP //-->
<PRE>
public void finalize() &#123;
       try &#123;
               servSock.close();
       &#125; catch(Exception e);
       servSock = null;
&#125;
&#125;
</PRE>
<!-- END CODE SNIP //-->
<P>Was that easy enough? Well, for a little more challenge, check out this next class.
</P><P><BR></P>
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="636-639.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="642-646.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>


</BODY>

⌨️ 快捷键说明

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