像剥洋葱一样,一层一层地处理数据。
Outer Loop (外层) 控制整体进度
Inner Loop (内层) 处理具体任务
目标: 只收集金币(价值为3),忽略其他。
逻辑:
value。while(true) { auto coins = hero.findItems(); int index = 0; // 🔄 内层循环:遍历硬币数组 while(index < coins.size()) { auto coin = coins[index]; // ⚖️ 过滤:只捡金币(value == 3) if (coin.value == 3) { hero.moveXY(coin.pos.x, coin.pos.y); } index++; // 👉 下一个! } }
auto coin = hero.findNearestItem(); // 🔄 只要还能找到金币,就一直循环 while (coin) { hero.moveXY(coin.pos.x, coin.pos.y); // ⚠️ 关键:必须重新寻找下一个目标! // 否则 hero 会一直盯着口袋里的这枚硬币 coin = hero.findNearest(hero.findItems()); }
只要地上还有东西 (while coin),
就绝不停止工作。
这种循环依赖于状态的改变
(金币被捡走了 -> 消失了)。
锁定一个敌人后,
只要它还站着 (health > 0),
就一直攻击。
这是处理持续性动作的最佳方式。
auto enemy = hero.findNearest(hero.findEnemies()); if (enemy) { // 🔄 只要血量大于 0,就一直打 while (enemy.health > 0) { hero.attack(enemy); // 每次攻击,enemy.health 都会减少 // 直到变成 0,循环自动停止 } }
while(i < array.size()) { ... i++; }
用途:处理列表中的每一个元素(如:检查每个硬币的价值)。
while(enemy.health > 0) { ... }
用途:对着同一个目标持续操作,直到状态改变(如:打到死为止)。
while(true) 保证游戏一直进行!