计算机科学 4 第 14 关
UNIT 1 REVIEW
🏦

第一单元大复习

Bank Raid (银行突袭)

🔄 循环
⚔️ 战斗
💰 收集
🦸‍♂️

本单元三大“超能力”

要想通关银行突袭,你需要熟练掌握这三把钥匙:

目标:
1. 消灭所有敌人
2. 收集所有金币
3. 循环往复
🔄
while 循环
While true
📋
数组列表
Arrays
🔢
索引遍历
Index & Loop
🔄

复习:遍历数组

这是处理一群敌人或一堆金币的标准模板。

// 1. 获取列表 auto enemies = hero.findEnemies(); // 2. 设置索引 int index = 0; // 3. 循环遍历 while (index < enemies.size()) { auto enemy = enemies[index]; hero.attack(enemy); // 4. 下一个! index++; }
📋 ➡️ ⚔️

Get List -> Loop -> Action

⚔️

阶段一:清理战场

首先,我们需要消灭所有在场的敌人。

auto enemies = hero.findEnemies(); int enemyIndex = 0; while (enemyIndex < enemies.size()) { auto target = enemies[enemyIndex]; hero.attack(target); enemyIndex++; }
注意:enemyIndex 必须每次循环都增加,否则你会盯着同一个死掉的敌人发呆!
👹 💀 💀
💰

阶段二:收集战利品

敌人清理完毕后,就可以安全地收集金币了。

auto coins = hero.findItems(); int coinIndex = 0; while (coinIndex < coins.size()) { auto coin = coins[coinIndex]; hero.moveXY(coin.pos.x, coin.pos.y); coinIndex++; }
🪙 🏃 🪙
🕹️

战术模拟 (Simulation)

将两个步骤放入 while(true) 主循环中。

  1. Loop 1: 打败所有敌人。
  2. Loop 2: 收集所有金币。
  3. 重复...
📜

完整解决方案

int main() { while(true) { // 第一步:攻击所有敌人 auto enemies = hero.findEnemies(); int enemyIndex = 0; while (enemyIndex < enemies.size()) { auto enemy = enemies[enemyIndex]; hero.attack(enemy); enemyIndex++; } // 第二步:收集所有金币 auto coins = hero.findItems(); int coinIndex = 0; while (coinIndex < coins.size()) { auto coin = coins[coinIndex]; hero.moveXY(coin.pos.x, coin.pos.y); coinIndex++; } } return 0; }