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

📄 774-778.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:Slider Puzzle</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=19//-->
<!--PAGES=774-778//-->
<!--UNASSIGNED1//-->
<!--UNASSIGNED2//-->

<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="771-774.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="778-778.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>
<P><BR></P>
<P>The final thing to do is to declare a method called imageUpdate() to receive these messages and take appropriate action, as shown in Listing 19-6.
</P>
<P><B>Listing 19-6</B> The image observer</P>
<!-- CODE //-->
<PRE>
public boolean imageUpdate(Image img, int flags, int x, int y, int w, &#8656;int h) &#123;

// When image is drawn, redraw THIS BLOCK.
// This is done by first finding where the block in the grid.
// THIS IS A BIT CRUDE!

    int iy,ix;

    if ((flags &#38; (SOMEBITS|FRAMEBITS|ALLBITS)) != 0) &#123;
        for (iy=0;iy&lt;GridSize.height;iy&#43;&#43;)
            for (ix=0;ix&lt;GridSize.width;ix&#43;&#43;)
                if ( grid[iy][ix].img == img ) &#123;
                    grid[iy][ix].changed = true;
                    repaint(100);
                    return (flags &#38; (ALLBITS|ERROR)) == 0;
                &#125;
    &#125;
    return (flags &#38; (ALLBITS|ERROR)) == 0;
&#125;
</PRE>
<!-- END CODE //-->
<P>The first thing this method does is check the flags that have been set to determine if the graphic is to be drawn again. If some of the graphic (SOMEBITS), a complete frame (FRAMEBITS), or the whole thing (ALLBITS) is ready, then call drawImage() again to display whichever of the parts is complete.
</P>
<P>The next trick to work out is which graphic is to be redrawn. The array of blocks is searched, looking for an image that matches the one passed to imageUpdate(), the image&#146;s <I>changed</I> flag is set, and repaint(100) is called to signal the AWT to call update() within 100 milliseconds.</P>
<H4 ALIGN="LEFT"><A NAME="Heading11"></A><FONT COLOR="#000077">The Randomize Button</FONT></H4>
<P>So far, you have seen how the program interacts with the user by the use of the mouse. You also need to understand how the Randomize button works.
</P>
<P>Before a button can be used, it must be drawn, as done in Listing 19-7.</P>
<P><B>Listing 19-7</B> Drawing the button</P>
<!-- CODE SNIP //-->
<PRE>
setLayout(new BorderLayout());
...
Panel p = new Panel();
add("South",p);
p.add(new Button("Randomize"));
</PRE>
<!-- END CODE SNIP //-->
<P>Here, an object of class Panel was created and placed at the bottom of the applet (&#147;South&#148;), then a single button was added to it. &#147;South&#148; is a container of the BorderLayout class. The BorderLayout class probably offers the simplest way to arrange things in an applet window.
</P>
<P>Whenever a button is clicked, the Web browser or applet viewer calls the action() method. You can intercept these events by defining a method of the same name in your applet, as in Listing 19-8.</P>
<P><B>Listing 19-8</B> Detecting whether a button has been selected</P>
<!-- CODE SNIP //-->
<PRE>
public boolean action(Event evt, Object arg) &#123;
    if ( arg.equals("Randomize") ) &#123;
        random = true;
        repaint();
    &#125;
    return true;
&#125;
</PRE>
<!-- END CODE SNIP //-->
<P>The applet can then simply check to see if the value of the argument passed equals the name of the button drawn earlier, and then take the appropriate action.
</P>
<P>Here a <I>random</I> flag is set and a call made to repaint(). The repaint() method causes update() to be called &#147;as soon as possible.&#148; The update() method detects the <I>random</I> flag and then executes another method to mix up the position of the blocks, rather than draw the grid as normal.</P>
<P>The randomize() method animates the movement of the blocks by performing a sequence of moves, ensuring that the grid is redrawn between each movement so that the user can observe the blocks being jumbled about. This is demonstrated in Listing 19-9.</P>
<P><B>Listing 19-9</B> Mixing up the puzzle</P>
<!-- CODE //-->
<PRE>
private void randomize(Graphics g)&#123;
    int i,iter=GridSize.height*GridSize.width*GridSize.width;
    Point from;
    for (i=0; i&lt;iter;i&#43;&#43;) &#123;
        if ( Math.random() &gt; 0.5 )
            move(new Point(blank.x,(int)(Math.random() *&#8656;GridSize.height)));
        else
            move(new Point((int)(Math.random() *&#8656;GridSize.width),blank.y));
        drawGrid(g);
    &#125;
&#125;
</PRE>
<!-- END CODE //-->
<P>The randomize() method first decides whether to do a horizontal or vertical movement. It then randomly picks a block in that row or column and calls the move() method to shift this block, or blocks. The drawGrid() method is executed between each random movement so that this scrambling process becomes an animated sequence. The number of moves is determined by the size of the puzzle. For instance, in Figure 19-8, 8x8x8, or 512 moves, are performed to get this huge puzzle well mixed up.
</P>
<P><A NAME="Fig8"></A><A HREF="javascript:displayWindow('images/19-08.jpg',383,432 )"><IMG SRC="images/19-08t.jpg"></A>
<BR><A HREF="javascript:displayWindow('images/19-08.jpg',383,432)"><FONT COLOR="#000077"><B>Figure 19-8</B></FONT></A>&nbsp;&nbsp;The 8&#215;8 puzzle!</P>
<P>Originally this method simulated a madman on the mouse, clicking away frantically at random locations on the puzzle. The problem with this, however, is that a block selected at random has a less than even chance of not being able to move. It had to be decided whether to simply increase the number of iterations or somehow change the code so that every random move would result in a block, or blocks, moving.
</P>
<BLOCKQUOTE>
<P><FONT SIZE="-1"><HR><B>Note</B><BR>You might be wondering why this method simulates lots of moves rather than just shuffling the blocks in some other way.
<P>The answer is that simply scrambling the blocks could result in an unsolvable configuration! By performing a series of simulated moves, the puzzle is guaranteed to be solvable.<HR></FONT>
</BLOCKQUOTE>
</P>
<H3><A NAME="Heading12"></A><FONT COLOR="#000077">Adding Enhancements</FONT></H3>
<P>Now that you have created the basic game, you may want to add some enhancements to make it more enjoyable and challenging. Most of the ideas included here for enhancing this program come from Joseph Carlson&#146;s original Amiga program.
</P>
<H4 ALIGN="LEFT"><A NAME="Heading13"></A><FONT COLOR="#000077">Adding a Solve Button</FONT></H4>
<P>Add a Solve button to the panel and the necessary code to the action() method to <I>catch </I>this event when the button is clicked. The applet then works out the shortest path to the solved puzzle, and animates the movement of the blocks to show the applet solving the puzzle.</P>
<P>This can be accomplished by performing a game tree traversal. Your program allocates a score to the current puzzle configuration, based on the number of pieces already in the correct place. Then, it evaluates all the possible moves from this configuration in order, from the highest scoring downward. Since this algorithm is recursive, when the solution is found, all the moves from the current position to the final goal configuration may be obtained by falling back up the tree and recording the moves taken at each depth.</P>
<P>Keep in mind that this process can take quite a while, and consume quite a lot of memory, especially if attempting to solve the 8x8 puzzle!</P>
<H4 ALIGN="LEFT"><A NAME="Heading14"></A><FONT COLOR="#000077">Using Pictures Instead of Numbers</FONT></H4>
<P>Instead of numbers, each block could contain a piece of an image. To make this very flexible, the applet could be made to load an arbitrary image, then cut it up into smaller images to use as the blocks.
</P><P><BR></P>
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="771-774.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="778-778.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>


</BODY>

⌨️ 快捷键说明

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