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

📄 211-217.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:Extending Your Video Game</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=6//-->
<!--PAGES=211-217//-->
<!--UNASSIGNED1//-->
<!--UNASSIGNED2//-->

<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="207-211.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="217-223.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>
<P><BR></P>
<H3><A NAME="Heading9"></A><FONT COLOR="#000077">Source Code for Modified Classes</FONT></H3>
<P>Listings 6-1 through 6-5 show the source of the classes we&#146;ve modified in this chapter: GameManager, GunManager, UFOManager, GunSprite, and UFO.
</P>
<P><B>Listing 6-1</B> GameManager class</P>
<!-- CODE //-->
<PRE>
import java.applet.*;
import java.awt.*;

/////////////////////////////////////////////////////////////////
public class GameManager extends Applet
implements Runnable &#123;

  // animation variables
  static final int REFRESH_RATE = 80; // in ms
  Thread animation;
  Graphics offscreen;
  Image image;

  // game variables used when playing
  static final int UFO_VALUE = 130;   // 130 points
  static final int MAX_LANDED = 5;    // at most 5 aliens
                                     //   can land

  static final int MAX_LEVEL = 9;    //
  static final int MAX_ENERGY = 113; //

  private int score;
  private int numLanded;            // num of aliens landed

  Image ufoImages[] =  new Image[6];    // 6 ufo Images
  Image attackImages[] =  new Image[6]; // 6 attack Images
  Image explodeImages[] =  new Image[4];// 4 explode Images
  Image gunImage;                       // gun image
  GunManager gm;                       // refers to gun manager
  UFOManager um;                       // refers to ufo manager

  // state of game
  private boolean playing;            // if game playing
  private int screen;                 // which screen to show
  static final int INTRO = 0;         // intro screen
  static final int GAME_OVER = 1;     // game over screen

  AudioClip expsound;                // explosion sound

  // fonts
  Font smallFont = new Font("Helvetica",Font.BOLD,12);
  Font mediumFont = new Font("Helvetica",Font.BOLD,14);
  Font bigFont = new Font("Helvetica",Font.BOLD,18);

  FontMetrics fm;                      // use to center string

  int width, height;                   // applet dimensions

  // strings
  String scoreString = "Score: ";
  String ufoLandedString = "UFOs Landed: ";
  String gameOverString =     "  GAME OVER  ";
  String clickString = "Shift-Click to Continue";
  String alienLandingString = "Alien Landing";
  int stringWidth;
  String introString[] = new String[8];


  public void init() &#123;
    showStatus(&#147;Loading Images -- WAIT!&#148;);
    setBackground(Color.black);        // applet background
    width = bounds().width;            // set applet dimensions
    height = bounds().height;
    loadImages();

    try &#123;
       expsound = getAudioClip(getCodeBase(),"Explosion.au");
    &#125;
    catch (Exception e) &#123; &#125;
    um = new UFOManager(2,MAX_LEVEL,width,height,ufoImages,
                     attackImages,explodeImages,
                     this,expsound);
    gm = new GunManager(MAX_ENERGY,5,width,height,gunImage,
                     um.getUFO(),
                     this);
    um.initialize(gm);              // initialize gun parameters

    playing = false;                    // not playing
    screen = INTRO;                     // show intro screen

    image = createImage(width,height); // make offscreen buffer
    offscreen = image.getGraphics();
    offscreen.setFont(bigFont);        // font for intro
    fm = offscreen.getFontMetrics(bigFont); // font metrics
    stringWidth = fm.stringWidth(alienLandingString);

    introString[0] = "You are Humanity's last hope!";
    introString[1] = "Destroy the green Alien Landers";
    introString[2] = "by using the Mouse to Move";
    introString[3] = "your Missile Launcher. Click";
    introString[4] = "to Fire Missile. If 5 Aliens";
    introString[5] = "Land, or Energy Runs Out,";
    introString[6] = "Humans will be Eaten Alive!";
    introString[7] = "Click to start Game";
 &#125;

  // load all images used in game
  public void loadImages() &#123;

    MediaTracker t = new MediaTracker(this);
    gunImage = getImage(getCodeBase(),"image/gun.gif");
    t.addImage(gunImage,0);
    for (int i=0; i&lt;ufoImages.length; i&#43;&#43;) &#123;
      ufoImages[i] = getImage(getCodeBase(),
                        "image/ufo" &#43; i &#43; ".gif");
      t.addImage(ufoImages[i],0);
      attackImages[i] = getImage(getCodeBase(),
                        "image/attack" &#43; i &#43; ".gif");
      t.addImage(attackImages[i],0);
    &#125;
    for (int i=0; i&lt;explodeImages.length; i&#43;&#43;) &#123;
      explodeImages[i] = getImage(getCodeBase(),
                         "image/explode" &#43; i &#43; ".gif");
      t.addImage(explodeImages[i],0);
    &#125;

    // wait for all images to finish loading //
    try &#123;
      t.waitForAll();
    &#125;  catch (InterruptedException e) &#123;
    &#125;

    // check for errors //
    if (t.isErrorAny()) &#123;
      showStatus("Error Loading Images");
    &#125;
    else if (t.checkAll()) &#123;
      showStatus("Images successfully loaded");
    &#125;

  &#125;

  // initialize params for new game
  public void newGame() &#123;

    score = 0;                         // no score
    numLanded = 0;                     // no aliens landed
    gm.newGame();                      // call newGame in
    um.newGame();                      //   manager classes
    offscreen.setFont(smallFont);     // set font in game
  &#125;
  // handle mouse events //

  public boolean mouseMove(Event e,int x,int y) &#123;
    if (playing) &#123;
      gm.moveGun(x);
    &#125;
    return true;
  &#125;
  public boolean mouseDrag(Event e,int x,int y) &#123;
    if (playing) &#123;
      gm.moveGun(x);
    &#125;
    return true;
  &#125;

  public boolean mouseDown(Event e,int x,int y) &#123;
    if (playing) &#123;
      gm.fireMissile(x);
    &#125;
    else if (screen == INTRO) &#123;        // start game for mouse
                                            //   down on intro screen
      playing = true;
      newGame();
    &#125;
    else if (screen == GAME_OVER) &#123;    // else go back to intro
      if (e.shiftDown()) &#123;              //   if shift-click
       screen = INTRO;
      &#125;
    &#125;

    return true;
  &#125;


  // start the Video Game Loop
  public void start() &#123;
    showStatus(&#147;Starting Game!&#148;);
    animation = new Thread(this);
     if (animation != null) &#123;
       animation.start();
     &#125;
  &#125;

  // update managers. only update gun if playing
  public void updateManagers() &#123;
    if (playing) &#123;
      gm.update();
    &#125;
    um.update();
  &#125;
  // override update so it doesn't erase screen
  public void update(Graphics g) &#123;
    paint(g);
  &#125;

  // paint the applet depending on mode of game
  public void paint(Graphics g) &#123;
    if (playing) &#123;
      offscreen.setColor(Color.black);
      offscreen.fillRect(0,0,width,height);  // clear buffer

      // draw status info
      offscreen.setColor(Color.cyan);
      offscreen.drawString(scoreString&#43;score,width - 113,13);
      offscreen.drawString(ufoLandedString&#43;numLanded,
                        width - 113,27);

      // tell UFOManager and GunManager to paint
      um.paint(offscreen);
      gm.paint(offscreen);


      g.drawImage(image,0,0,this);
    &#125;
    else if (screen == INTRO) &#123;
      offscreen.setColor(Color.black);
      offscreen.fillRect(0,0,width,height);  // clear buffer

      offscreen.setFont(smallFont);
      offscreen.setColor(Color.cyan);
      offscreen.drawString(scoreString&#43;score,width - 113,13);
      offscreen.drawString(ufoLandedString&#43;numLanded,
                        width - 113,27);
      um.paint(offscreen);

      offscreen.setFont(bigFont);

      offscreen.setColor(Color.green);
      offscreen.drawString(alienLandingString,
                (width-stringWidth)/2,
                height/6);

      offscreen.setColor(Color.magenta);
      offscreen.setFont(mediumFont);

      // draw instructions
      for (int i=0; i&lt;introString.length-1; i&#43;&#43;) &#123;
       offscreen.drawString(introString[i],13,(3&#43;i)*height/12);
      &#125;
      offscreen.setColor(Color.green);
      offscreen.drawString(introString[7],
                (width-stringWidth)/2,
                height*11/12);

      g.drawImage(image,0,0,this);

    &#125;

    else if (screen == GAME_OVER) &#123;
      offscreen.setColor(Color.black);

      offscreen.fillRect(0,0,width,height);  // clear buffer

      // draw status info
      offscreen.setFont(smallFont);
      offscreen.setColor(Color.cyan);
      offscreen.drawString(scoreString&#43;score,width - 113,13);
      offscreen.drawString(ufoLandedString&#43;numLanded,
                        width - 113,27);

      um.paint(offscreen);
      gm.paint(offscreen);

      offscreen.setFont(bigFont);

      offscreen.setColor(Color.red);
      offscreen.drawString(gameOverString,
                 (width-stringWidth)/2,
                 height/2);
      offscreen.setFont(mediumFont);
      offscreen.setColor(Color.green);
      offscreen.drawString(clickString,
                 (width-stringWidth-17)/2,
                 height*11/12);

      g.drawImage(image,0,0,this);


    &#125;
  &#125;

  // the Video Game Loop
  public void run() &#123;
    while (true) &#123;
      repaint();
      updateManagers();
      Thread.currentThread().yield();
      try &#123;
       Thread.sleep (REFRESH_RATE);
      &#125; catch (Exception exc) &#123; &#125;;

    &#125;

  &#125;


  // stop animation
  public void stop() &#123;

    showStatus("Game Stopped");
    if (animation != null) &#123;
      animation.stop();
      animation = null;
    &#125;
  &#125;

  // increase score
  public void incrementScore() &#123;
    score &#43;= UFO_VALUE;
  &#125;

  // count number of ufo's landed
  public void alienLanded() &#123;
    numLanded&#43;&#43;;
    if (numLanded == MAX_LANDED) &#123;
      gameOver();
    &#125;
  &#125;

  // handle game over
  public void gameOver() &#123;
    if (playing) &#123;
      playing = false;
      screen = GAME_OVER;
    &#125;
  &#125;
&#125;
</PRE>
<!-- END CODE //-->
<P><BR></P>
<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="207-211.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="217-223.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>


</BODY>

⌨️ 快捷键说明

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