再试一次按钮,将游戏中的所有内容重置为初始值

时间:2016-07-29 03:19:29

标签: java eclipse

我是java的初学者,正在构建一个包含更多课程的简单游戏。我想添加Try Again功能,将所有内容重置为初始值,就好像程序已关闭并重新打开但没有实际执行此操作。必须从不包含初始化的类调用该函数。

这是我的初始化类:

public class game extends JPanel implements ActionListener{

private static final long serialVersionUID = 1L;
private Menu menu;
private GameOver gameover;


//variables
public static int cyclesToWait = 50;
public static int enemiesKilled = 0;
public static int life = 3;
int roundCount = 0;
Timer gamelooptimer;

//objects
Player p;
ControllerEnemy c;
ControllerRocket r;
ControllerExplosion e;


//is it new round or not --> for enemy control
public static enum ROUND{
    INPROGRESS,
    NEW
}

public static enum STATE{
    MENU,
    GAME,
    OVER
};

public static STATE State = STATE.MENU;
public static ROUND Round = ROUND.INPROGRESS;

public game(){

    setFocusable(true);

    gamelooptimer = new Timer(10, this);
    gamelooptimer.start();

    p = new Player(MainClass.width / 2 - 60, 400);
    c = new ControllerEnemy();
    r = new ControllerRocket();
    e = new ControllerExplosion();
    menu = new Menu();
    gameover = new GameOver();

    addKeyListener(new KeyInput(p));
    addMouseListener(new MouseInput());
}

public void paint(Graphics g){
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.drawImage(getBackgroundImage(), 0, 0, null);

    Font fnt = new Font("arial", Font.BOLD, 22);
    g.setFont(fnt);


    if(State == STATE.GAME){
        p.draw(g2d);
        p.draw(g2d);
        c.draw(g2d);
        r.draw(g2d);
        e.draw(g2d);
        g.drawString("Round: " + roundCount, MainClass.width - 125, 22);
        g.drawString("Enemies Killed: " + enemiesKilled, MainClass.width/2 - 95, 22);
        if(cyclesToWait < 50)
            cyclesToWait++;
    }
    else if (State == STATE.OVER)
        gameover.render(g);
    else
        menu.render(g);


}



@Override
public void actionPerformed(ActionEvent e) {
    repaint();
    if(State == STATE.GAME){    
        p.update();
        c.update();
        r.update();
    }
    if(Round == ROUND.NEW)
        roundCount += 1; 
}
private Image getBackgroundImage(){
    ImageIcon i = new ImageIcon(getClass().getResource("/images/Background.png"));
    return i.getImage();
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

将构造函数中与游戏相关的所有初始化代码重构为initGame方法。现在,您可以在构造函数中调用该方法,并且还有一个调用reset()的{​​{1}}方法。您再试一次按钮应拨打initGame()

resetGame()