计算机科学 3
第 7-8 关 ADVENTURE LOG
📜

练习 while 循环

Practice While Loops

🏜️ 海市蜃楼
🧪 菠菜力量
📚

多重任务:一章接一章

程序执行就像读书,读完第一章,才读第二章。

// 第一章:攒钱 (循环) while (hero.gold < 25) { collectCoins(); } // 第二章:买东西 (单次) hero.buildXY("decoy", 71, 68); // 第三章:挑衅 (循环) while (hero.health == hero.maxHealth) { hero.say("Come on!"); }
注意:代码是顺序执行的。上一个循环不结束,就不会执行下面的代码。
1. 攒够 25 金币
⬇️
2. 建造诱饵
⬇️
3. 满血挑衅
🧪

菠菜力量:计数器

我们需要数数:喝了几瓶药水?

int potionCount = 0; // 初始 while (potionCount < 7) { drinkPotion(); potionCount ++; // 关键! 自增 }

potionCount++ (或 += 1):
每喝一瓶,就在本子上画一道杠。

Count: 0
⚠️

陷阱:差一错误 (Off-by-one)

如果写成 while (count <= 7) 会怎样?

<= 7:第 7 瓶喝完,7 <= 7 成立,还会再喝第 8 瓶!(喝多了)

< 7:第 7 瓶时,7 < 7 不成立,停止。(刚刚好)

🤢

喝了第 8 瓶...

🧪🧪🧪🧪🧪🧪🧪🧪
🏜️

实战:海市蜃楼 (Mirage)

利用多个循环完成连续任务。

int main() { // 1. 攒钱 while(hero.gold < 25) { auto item = hero.findNearestItem(); if(item) hero.moveXY(item.pos.x, item.pos.y); } // 2. 造诱饵 (只做一次) hero.buildXY("decoy", 71, 68); // 3. 挑衅 (直到受伤) while(hero.health == hero.maxHealth) { hero.say("来打我啊!"); } hero.moveXY(22, 15); return 0; }
👻

Decoy Ready!

💪

实战:菠菜力量 (Spinach Power)

精确控制循环次数。

int main() { int potionCount = 0; // 只喝 7 瓶 while (potionCount < 7) { auto item = hero.findNearestItem(); if (item) { hero.moveXY(item.pos.x, item.pos.y); potionCount++; // 计数+1 } } // 喝完去战斗 while (true) { auto enemy = hero.findNearestEnemy(); if (enemy) hero.attack(enemy); } return 0; }
🥦

Power Up!

📜

冒险总结

"顺序很重要:
先循环A,结束了,再循环B。"
"计数器要归零,
每次循环加个一 (count++)。"
"小心 < 和 <= 的区别,
别喝坏了肚子!"
🏆