在Java游戏中实现暂停/恢复功能

时间:2015-04-23 12:03:47

标签: java

我已设法使用*running = !running

暂停游戏

但如果使用

,则无法取消暂停

thread.resume()thread.wait()在“P' P'按下

private volatile boolean running;
private Thread thread;

public static enum STATE {
    MENU,
    GAME,
};

public static STATE State = STATE.MENU;

public void init(){
    requestFocus();
}

private synchronized void start(){
    if(running)
        return;

    running = true;
    thread = new Thread(this);
    thread.start();
}

private synchronized void stop(){
    if(!running)
        return;

    running = false;
    try{
        thread.join();
    }catch(InterruptedException e){
        e.printStackTrace();
    }
}

public void run() {
    init();

    while(running){
        /some codes
    }
    stop();
}

private void render(){

    if(State == STATE.GAME){
        p.render(g);
        c.render(g);

    }else if(State == STATE.MENU){
        menu.render(g);
    }

    g.dispose();
    bs.show();
}

public void keyPressed(KeyEvent e){
    int key = e.getKeyCode();

    if(State == STATE.GAME){
    if(key == KeyEvent.VK_RIGHT){
        p.setVelX(5);
    }else if(key == KeyEvent.VK_LEFT){
        p.setVelX(-5);
    }else if(key == KeyEvent.VK_DOWN){
        p.setVelY(5);
    }else if(key == KeyEvent.VK_UP){
        p.setVelY(-5);
    }else if(key == KeyEvent.VK_SPACE && !is_shooting){
        c.addEntity(new Bullet(p.getX(), p.getY(), tex, this));
        is_shooting = true;
    }else if(key == KeyEvent.VK_P){

此行将暂停。

        running = !running;
    }
    }
}

public void keyReleased(KeyEvent e){
    int key = e.getKeyCode();

    if(key == KeyEvent.VK_RIGHT){
        p.setVelX(0);
    }else if(key == KeyEvent.VK_LEFT){
        p.setVelX(0);
    }else if(key == KeyEvent.VK_DOWN){
        p.setVelY(0);
    }else if(key == KeyEvent.VK_UP){
        p.setVelY(0);
    }else if(key == KeyEvent.VK_SPACE){
        is_shooting = false;
    }else if(key == KeyEvent.VK_P){


// This line doesn't work.

        running = true;
    }
}

2 个答案:

答案 0 :(得分:1)

目前,只要running设置为false,您的游戏线程就会退出(run()方法返回)。

public void run() {
    init();
    while(running){
        /some codes
    }
    stop();
}

应该改为更像这样的东西:

public void run() {
    init();
    while(true){
        if(!running) {
            Thread.sleep(1000);  //1 second or something else
            continue;
        }
        //Game logic here
    }
    stop();
}

您当然需要区分运行和暂停,以便能够摆脱这种循环。

答案 1 :(得分:0)

设置running =!runnning只会更改变量,除非你在游戏循环中使用变量,否则你实际上并没有停止任何变量。

要暂停该方法,请使用Thread.sleep()或只是停止该主题,如果您不知道要暂停多长时间,请再次启动该主题。