running a loop at timed intervals Java

我们两清 提交于 2021-02-05 11:30:29

问题


Below is the code I am currently running. I am trying to make a text based version of the arcade game Tron. I want the game to run automatically unless the user enters a direction (WASD). I have looked into timers and I know that if I were to use swing I could implement action listeners but this project is to be done strictly without a GUI. I was wondering if anyone might have some ideas how to make the game more dynamic and not turn based.

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");
    }
}

EDIT: Somebody suggested that I run two threads at the same time, one looping to check for input and then one running the main game. Although something like this seems like a good idea, I am unsure how to share the inputs received by the input thread with the thread that is running the game.


回答1:


You can use Thread.sleep(millis), for example:

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



回答2:


    int intervals = 1000;
    do {
        if (System.currentTimeMillis() % intervals == 0) {
            System.out.println("asd");
        }
    } while (true);

I'm not sure if i understand you correct. But maybe somethings like this above one? You have endless while loop and in every second something happened ( in this case text is displaying).



来源:https://stackoverflow.com/questions/46095252/running-a-loop-at-timed-intervals-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!