简体   繁体   English

在Java应用程序中暂停游戏

[英]Pausing a game in a java application

I am trying to add pause functionality to a game. 我正在尝试向游戏添加暂停功能。 Unfortunately the method I'm currently using causes the program to take no more inputs so I am unable to resume the game. 不幸的是,我当前使用的方法导致程序不再接受任何输入,因此我无法继续游戏。

Here is what I'm currently doing: 这是我目前正在做的事情:

a pause button calls: 暂停按钮会调用:

public void pause(){
    if(data.paused == true){
        data.paused = false;
    }
    else{
        data.paused=true;
        while(true){
            if(data.paused == true){
                try{
                    Thread.currentThread().sleep(100);
                }
                catch(InterruptedException ie){
                    System.out.println(ie);
                }
            }
            else
                break;
        }
        data.paused=false;
    }
  return;

I then have a TimerTask that I have to deal with: 然后,我有一个TimerTask必须处理:

class aTask extends java.util.TimerTask {
    protected Data data;
    public aTask( Data d ) { data = d; }
    public void run() { 
        try{ 
            if(data.paused){
                try{
                    Thread.currentThread().sleep(100);
                }
                catch(InterruptedException ie){
                    System.out.println(ie);
                }
            }
            else
                data.tick(); 
        } 
        catch( ATCGameOverException e ){ 
            data.gameOver( e.getMessage() );
        }
    }
};

where tick causes an action in the game every second. 滴答声每秒引起游戏动作。

I would think this would allow the game to pause when the button is pressed and then unpause when the button is pressed again, but I would be wrong. 我认为这将允许游戏在按下按钮时暂停,然后在再次按下按钮时取消暂停,但是我错了。 What am I doing wrong? 我究竟做错了什么?

Simply try this : 只需尝试:

public void pause(){
  data.paused = !data.paused;
}

It looks like a threading problem. 它看起来像一个线程问题。 If you use Swing and your pause method is tied to an action listener, than the behaviour is normal: the pause function never returns, Swing main thread never has control again, and cannot manage further actions, including unpausing... Look at this link 如果你使用Swing和你的停顿方法被绑定到一个动作侦听器,比行为是正常的:暂停功能永远不会返回,摇摆主线程永远不会再次控制,而不能管理进一步行动,包括取消暂停...看看这个链接

My solution simply inverse the state of the pause variable, and gives control back to Swing. 我的解决方案只是将暂停变量的状态取反,然后将控制权交还给Swing。 It's the game main loop that will tick the data or not according to the state of this variable. 游戏主循环会根据此变量的状态来标记数据或不标记数据。 No thread is blocked, main loop continues to loop. 没有线程被阻塞,主循环继续循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM