allyozturk
allyozturk

Reputation: 117

Java infinite loop in despite of statement makes condition false

I am new on Java, but my problem can be language independent. I have a Player class and in my game logic, i have a map stores created players. I write a method -getNext()- that returns the next player to me and it works like a charm. But in the game, players that eliminated must not get in line. So I write a new method -getNextAlive()- should return next alive (!isLoser) player. If there isn't any loser player, getNextAlive() is working but if there is, program gets in while loop and looping infinitely. In while loop I switch to next player and sure that next is alive, but I think while(p.checkLose()) not affected in while changes and give this output forever:

player: allyozturk

I can't get why this happens in this way, what should I do for skipping all isLoser players and get the next alive one? (BTW, I use libgdx ArrayMap and my map is ordered because of order of next player is importont for my game)

in-game I use:

currPlayer = currPlayer.getNextAlive();

and here my Player.java is:

    public class Player{
        private static int counter;
        public static int alives;

        private int uniqueId;
        private String name;
        private boolean isLoser;
        .
        .
        .
        private Player getNext(){
            int index = MyGdxGame.players.indexOfKey(uniqueId);
            if(++index < MyGdxGame.players.size)
                return MyGdxGame.players.getValueAt(index);
            else
                return MyGdxGame.players.getValueAt(0);
        }

        public Player getNextAlive(){
            Player p = getNext();
            while(p.checkLose()){
                p = getNext();
                MyGdxGame.logger.error("player: " + p.getName()); // just for testing purpose
            }
            return p;
        }
    }

And an addition question coming from some curiosity and some for doing the best: Is it totally appropriate that using a method returns Player in the Player class?

Upvotes: 2

Views: 305

Answers (1)

talex
talex

Reputation: 20455

Replace p = getNext(); with p = p.getNext();

Upvotes: 8

Related Questions