[英]Problems with while loops
我正在制作一個項目,正在構建一個棋盤游戲的數字化版本,我遇到了一個問題,一個while循環沒有像我預期的那樣。
基本上, 如果玩家手中剩下一塊石頭 ,並且下一個坑不是空的,他們會拿起下一個坑石並繼續這樣做,直到下一個坑為空 。
現在,我的代碼繼續, 而下一個坑是空的, 而一塊石頭仍在他們的手中,但是,如果它不是空的話,它不會拾取下一個坑石頭,它只是添加一個,直到下一個坑為空。
所以我的代碼幾乎就在那里,只是不完全。 所以我正在尋找一些幫助來改進當前的代碼(在需要工作的代碼之上的一個重要評論)。
如果解釋很差,請告訴我,我會盡力重寫它。
干杯
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;
}
}
而不是有多重嵌套循環。 您可能只需要更新手中的寶石和坑中的寶石,讓主循環繼續正常,因為主循環只是主要的游戲邏輯循環:抓住石頭,放入凹坑,抓住更多的石頭並重復?,?? ?,盈利!
例如:
代替:
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;
}
}
做類似的事情:
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
}
(注意:我不是100%遵守你要求的規則,只是試着按照你所說的去做)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.