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

Java游戏中暂停/恢复功能的实现,java,Java,我已经用*running=”暂停了游戏!正在运行 但是,如果使用此选项,则无法取消暂停 和thread.resume()或thread.wait()在按下“p”时取消暂停也不起作用 private volatile boolean running; private Thread thread; public static enum STATE { MENU, GAME, }; public static STATE State = STATE.MENU; public vo

我已经用
*running=”暂停了游戏!正在运行

但是,如果使用此选项,则无法取消暂停

thread.resume()
thread.wait()
在按下“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){
这一行是暂停


设置运行=!runnning只会更改变量,除非在游戏循环中使用变量,否则实际上不会停止任何操作


要暂停该方法,请使用
Thread.sleep()
,或者简单地停止该线程,如果不知道要暂停多长时间,请重新启动该线程。

此时,只要
running
设置为false,游戏线程就会退出(run()方法返回)

应更改为类似以下内容:

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

当然,您需要区分“运行”和“暂停”,才能打破此循环。

如果您已经打破了此循环,请将“运行”设置为“真”,否则不会重新启动它。
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();
}