【问题标题】:Don't see why this loop does not get reached不明白为什么没有达到这个循环
【发布时间】:2015-08-31 10:20:52
【问题描述】:

由于许多布尔检查我有点困惑,让我介绍一下我的下一个代码。

        } else {
        //check whether the player starts again. the first time we lose the player
        //will definitely get into this loop
        if(!startAgain){
            // we only do this to set a timer, we don't want to start a new game so we set this
            // to false
            newgame = false;
            startAgain = true;
            deadTime = System.nanoTime();
        }
        deadTimepassed = (System.nanoTime() - deadTime)/1000000;
        if((deadTimepassed < 2000) && (newgame = false)){
            newGame();
        }
    }
}

这个 else 语句可以看作是玩家第一次被敌方导弹击中。制作爆炸动画。我需要让屏幕冻结 2 秒,然后重新开始游戏。我不明白为什么永远不会达到第二个 if 语句。以下是我的 ontouch 方法和我的新游戏方法:

    @Override
public boolean onTouchEvent(MotionEvent event) {

    //What happens when the player touches the screen!

    if (event.getAction() == MotionEvent.ACTION_DOWN) {

        // Boolean check for when player is playing, if he isn't the chopper does nothing.
        // we see that the chopper only hangs still if all these booleans are true!
        if ((!player.isPlaying()) && (newgame = true) && (startAgain = true)) {
            player.setPlaying(true);

        } if(player.isPlaying()) {
            player.setUp(true);
            startAgain = false;
        }
        return true;
    }

    if (event.getAction() == MotionEvent.ACTION_UP) {
        player.setUp(false);
        return true;
    }
    return super.onTouchEvent(event);
}

    public void newGame(){
    newgame = true;
    missles.clear();
    if(player.getScore()>best) {
        best = player.getScore();
        SharedPreferences.Editor editor = saveBest.edit();
        editor.putInt("new best",best);
        editor.commit();
    }
    player.resetScore();
    player.setY(HEIGHT/2);
}

正如人们所看到的,新游戏只是重置了玩家的位置,我唯一想做的就是在此之前将屏幕冻结 2 秒钟,这应该在第二个 if 语句中发生,但它永远不会得到到达...

有什么建议吗?

ps:deadTimepassed 在公共类方法下方被引入为“private long”。

【问题讨论】:

  • newgame = false 是一个作业。应该是!newgame
  • 我也可以使用 newgame == false (只是出于好奇,所以我明白为什么会失败)
  • @KeesTil 是的,你可以
  • @KeesTil = 是赋值 == 是比较。
  • 可以,但不推荐在使用布尔值时。

标签: java if-statement boolean


【解决方案1】:

要在 2 秒内冻结您的 Thread(因此,程序将冻结,您的屏幕也会冻结),您可以使用 Thread.sleep() 功能:

try {
    Thread.sleep(2000);
} catch (InterruptedException e) {
    e.printStackTrace();
}

您必须将其放在 try-catch 块中,因为它可以为您提供 InterruptedException

希望对你有所帮助!

【讨论】:

  • 这不是停止动画的最佳方式。这会冻结所有应用程序(或至少在执行时冻结当前线程)。
  • 我想到了这个,这个方法的问题是我不能在冻结状态下播放动画。感谢您的帮助,尽管我很感激:)
猜你喜欢
  • 2016-01-24
  • 1970-01-01
  • 2021-05-19
  • 1970-01-01
  • 2018-08-16
  • 1970-01-01
  • 1970-01-01
  • 2022-12-10
  • 1970-01-01
相关资源
最近更新 更多