【问题标题】:running a loop at timed intervals Java以定时间隔运行循环Java
【发布时间】:2017-09-07 11:29:56
【问题描述】:

以下是我当前正在运行的代码。我正在尝试制作基于文本的街机游戏 Tron 版本。我希望游戏自动运行,除非用户输入方向(WASD)。我研究过计时器,我知道如果我要使用 swing,我可以实现动作侦听器,但这个项目是在没有 GUI 的情况下严格完成的。我想知道是否有人可能对如何使游戏更具动态性而不是回合制有一些想法。

while (player1.playerAlive) {
    String directionPrompt = "please enter a direction: \n" + "(W) -   UP\n" + "(S) - DOWN\n" + "(A) - LEFT\n" + "(D) - RIGHT";
    String continueMovingInput;
    continueMovingInput = userMoveInput("To auto move:(Press Enter), to change direction, " + directionPrompt);`

    if (continueMovingInput.equals("") || continueMovingInput.equals("w") || continueMovingInput.equals("a") || continueMovingInput.equals("s") || continueMovingInput.equals("d")) {
        switch (continueMovingInput) {
            case "w":
                player1.moveUp();
                break;
            case "a":
                player1.moveLeft();
                break;
            case "s":
                player1.moveDown();
                break;
            case "d":
                player1.moveRight();
                break;
            default:
                System.out.println("auto move");
                break;
        }

        boolean collision = player1.movePlayer();
        if (!collision) {
            gridArena.gridPlacer(player1.getPlayerX(), player1.getPlayerY(), 1);
            gridArena.gridPrinter();
        } else {
            break;
        }
    } else {
        System.out.println("incorrect selection");
    }
}

编辑:有人建议我同时运行两个线程,一个循环检查输入,然后一个运行主游戏。虽然这样的事情似乎是个好主意,但我不确定如何与运行游戏的线程共享输入线程接收到的输入。

【问题讨论】:

    标签: java loops time automation


    【解决方案1】:

    您可以使用Thread.sleep(millis),例如:

        while(true){
            //do something
            Thread.sleep(1000);
        }
    

    【讨论】:

      【解决方案2】:
          int intervals = 1000;
          do {
              if (System.currentTimeMillis() % intervals == 0) {
                  System.out.println("asd");
              }
          } while (true);
      

      我不确定我的理解是否正确。但也许像上面这样的东西?您有无穷无尽的 while 循环,并且每一秒都发生了一些事情(在这种情况下,文本正在显示)。

      【讨论】:

        猜你喜欢
        • 2023-04-03
        • 2013-08-04
        • 1970-01-01
        • 2015-08-01
        • 1970-01-01
        • 2018-08-30
        • 2017-12-26
        • 2019-01-07
        • 1970-01-01
        相关资源
        最近更新 更多