Reputation:
I'm working on a project at the moment that's building a digitised version of a board game, and i'm having an issue with a while loop thats not doing as i expected.
Basically, if the player has 1 stone left in his/her hand, and the next pit is not empty, they pick up the next pits stones and continue doing so, until the next pit is empty.
Now, my code continues while the next pit is empty and while one stone is remaining in their hand, however, it doesn't pick up the next pits stones if it isn't empty, it just adds one until the next pit is empty.
So my code is almost there, just not quite. So i'm looking for some help to improve the current code (a big comment above the code that needs work).
Let me know if the explanation is poor, i'll do my best to re-write it.
Cheers
while(hand == 1 && pit.next.stones != 0 && pit.next.pit == false) {
int stones = pit.next.stones;
for(int i = stones; i >= 1; i--) {
hand++;
}
while(Hand >= 1 && pit.next.stones != 0) {
hand--;
addPieces(pit.next);
pit = pit.next;
}
}
Upvotes: 3
Views: 171
Reputation: 4699
Rather than having mutli-nested loops. You should probably just update the stones in hand and stones in the pit and let the main loop continue as normal since the main loop is just the main game logic loop: grab stones, drop in pits, grab more stones and repeat?, ???, profit!
Eg:
Instead of:
while(hand >= 1 && pit.next != null) {
// ...
while (hand == 1 && pit.next.stones != 0 && pit.next.pit == false) {
int stones = pit.next.stones;
for (int i = stones; i >= 1; i--) {
hand++;
}
while (hand >= 1 && pit.next.stones != 0) {
hand--;
addPieces(pit.next);
pit = pit.next;
}
}
do something like:
while(hand >= 1 && pit.next != null) {
// ...
if(hand == 1 && pit.next.stones > 0 && pit.next.pit == false) {
// update stones in hand
hand += pit.next;
// update stones in pit
pit.next.stones = 0;
}
// let main loop continue
}
(Note: I'm not 100% on the rules you are going for, just tried to follow what you said)
Upvotes: 1