user3130731
user3130731

Reputation: 685

While Loop Stalling Program

Why is my while loop freezing up my program?

gameLoop() is holding up my other programs processes.

    while (running) {
        if (Key.up) {
            player.moveCharacter(1, playerSpeed);
        } else if (Key.down) {
            player.moveCharacter(2, playerSpeed);
        } else if (Key.left) {
            player.moveCharacter(3, playerSpeed);
        } else if (Key.right) {
            player.moveCharacter(4, playerSpeed);
        }
    }

                        // listen for log in data
        while (true) {
            try {
                int direction = socketIn.readByte(); // player direction
                                                        // sent from server
                int px = socketIn.readByte(); // player px
                int py = socketIn.readByte(); // player py
                String username = socketIn.readUTF(); // player username

                player = new Player(direction, px, py, username); // create
                break;
            } catch (IOException e) {
                e.printStackTrace();
                break;
            }
        }
        game.gameLoop(player);

game.gameLoop(player); calls my game loop as you can see, however when it's run my game seizes to continue it's other processes. Can anybody tell me why this is happening? Do I need to put it on a thread?

Upvotes: 2

Views: 679

Answers (5)

Suhaib Ahmad
Suhaib Ahmad

Reputation: 526

I know i'm a few years late for this, but hope it helps anyone reading

you can use a flag for your while-loop condition

flag = true;
while(flag){

    //some code here

    if(condition)
        flag  = false;
}

the if condition is the condition to exit the loop, i.e. when you break out of it.

Upvotes: 0

carexcer
carexcer

Reputation: 1427

You are using while(true), and the only way to go out of the loop is with a break, but if you have that code on the same thread than the thread which manage the GUI, your GUI will freeze and the user will not be able to log in because the GUI is frozen by that loop.

The solution is to set that code on another thread different than the main thread (which manage the GUI).

Upvotes: 1

JVMATL
JVMATL

Reputation: 2124

yes. If you need to stay in the loop for the whole game (after login) then you need to put it in its own thread.

Upvotes: 0

albusshin
albusshin

Reputation: 4010

You're using while (true), so it will continuously check the key state and execute the code blocks. Instead check them every several seconds (or milliseconds)

Upvotes: 0

Alex
Alex

Reputation: 1110

You use while(true) which will never, ever be false. Thus, the loop will never break and your code will continue to repeat it forever.

Upvotes: 0

Related Questions