我的代码中有哪些部分涉及重新启动游戏?

时间:2017-02-23 23:40:54

标签: java

我需要帮助了解如何重新启动游戏。我正在阅读Java中的Killer Game Programming一书中的教程,我希望重新启动游戏而不必再次退出并运行游戏。我正在努力理解我必须重新初始化以开始新游戏的代码的哪一部分。我试图弄清楚让我保持游戏的方式,但重置游戏。现在我只知道如何重置游戏,因为我还没有参与统计数据。

我有一个keylistener,我想按下" N"重启游戏。

if(e.getKeyCode() == KeyEvent.VK_N){
                newGame();

我的问题是newGame()应该怎么做才能重新开始游戏?

此代码不会运行,因为我试图删除我认为与我的问题无关的所有内容。

希望我没有删除太多:S

主类

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class WormChase extends JFrame implements WindowListener
{
  private WormPanel wp;        // where the worm is drawn


  public WormChase(long period)
  { super("The Worm Chase");
    makeGUI(period);

    pack();
    setResizable(false);
    setVisible(true);
  }  // end of WormChase() constructor



  // ----------------------------------------------------

  public static void main(String args[])
  { 
    int fps = DEFAULT_FPS;
    if (args.length != 0)
      fps = Integer.parseInt(args[0]);

    long period = (long) 1000.0/fps;
    System.out.println("fps: " + fps + "; period: " + period + " ms");

    new WormChase(period*1000000L);    // ms --> nanosecs 
  }


} // end of WormChase class

第二课

public class WormPanel extends JPanel implements Runnable
{
  private static final int PWIDTH = 500;   // size of panel
  private static final int PHEIGHT = 400; 


  private Thread animator;           // the thread that performs the    animation

  private WormChase wcTop;
  private Worm fred;       // the worm
  private Obstacles obs;   // the obstacles

  public WormPanel(WormChase wc, long period)
  {
    wcTop = wc;
    this.period = period;

    // create game components

    addKeyListener( new KeyListener() {

            if(e.getKeyCode() == KeyEvent.VK_N){
                newGame();
            }
    });
  }


  public void addNotify()
  // wait for the JPanel to be added to the JFrame before starting
  { super.addNotify();   // creates the peer
    startGame();         // start the thread
  }


  private void startGame()
  // initialise and start the thread 
  { 
    if (animator == null || !running) {
      animator = new Thread(this);
      animator.start();
    }
  } // end of startGame()


  private void newGame()
  // initialise and start the thread 
  { 

  public void run()
  /* The frames of the animation are drawn inside the while loop. */
  {

    running = true;

    while(running) {
      gameUpdate();
      gameRender();
      paintScreen();

    }

  }



}  // end of WormPanel class

0 个答案:

没有答案