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



我需要帮助了解如何重新启动游戏。我在Java的《杀手级游戏编程》中关注了一个教程,我想重新启动游戏而不退出并运行游戏。我正在努力理解我必须重新初始化的代码的哪一部分才能启动新游戏。我试图找出一种让我保持游戏机的方式,但要重置游戏。现在,我只是知道如何重置游戏,因为我还没有涉及统计数据。

我有一个钥匙单元,我想按" 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

您应该将关键侦听器移至启动游戏的基类(蠕虫),然后您应该制作一种初始化所有内容的方法,就像蠕虫构造器一样,因为这就是启动的方法游戏。因此,您需要确切地做的是抓住构造函数中的所有内容,将其移动到诸如" StartGame"之类的方法,然后在构造函数中称为。我现在在想,您可以将关键侦听器保留在窗口类中,但是您需要注意到基类,您已经在重新启动的情况下结束了游戏。这意味着,按下n键时,钥匙侦听器需要杀死运行游戏的窗口,并注意您要启动新游戏的主线程。这意味着您将再次致电构造函数。

即使您想重新启动游戏,而不必杀死以主方法启动的窗口,则需要考虑游戏开始时设置的所有内容以及那里有什么值。然后,您只需创建一个将所有内容设置为"启动"值的方法,然后您就可以运行游戏。

基本上意味着重新创建您在蠕虫类中使用和使用的每个对象,例如Fred = New Wormchase等...

我真的不喜欢嵌套功能,所以我一定会尝试避免它,即使Java不支持它(newgame() -> run())

最新更新