我需要帮助了解如何重新启动游戏。我正在使用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
您的代码太不完整,无法给出比根据[MVC]的代码更好的建议(https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller),开始新游戏应该很简单。 – Paul
哦,不,我希望我已经简化了足够!以及 – tore
@paul也,谢谢你设置我的方向MVC :) – tore