第 14 关
银行突袭 (Bank Raid)
战术思路分析:逐个击破与收集
英雄必须遍历数组中的**所有敌人**并攻击,然后遍历数组中的**所有金币**并收集。
数组遍历核心流程(两部分)
- **索引变量:** `enemyIndex = 0`
- **循环条件:** `while enemyIndex < len(enemies):`
- **索引步进:** `enemyIndex += 1` (防止死循环)
外层 `while True` 的作用
将敌人遍历和物品遍历代码放在一个 `while True` 中,确保英雄能够持续防御和收集,应对不断变化的战场。
WHILE True:
WHILE Enemy Index < len(E): Attack()
WHILE Coin Index < len(C): Collect()
Python 程序解法
1
while True:
外层无限循环,持续进行攻防和收集
2
enemies = hero.findEnemies()
获取敌人列表
3
# enemyIndex 用于迭代 enemies 数组。
4
enemyIndex = 0
初始化敌人索引为 0
5
# 当 enemyIndex 小于 len(enemies) 时
6
while enemyIndex < len(enemies):
**内层循环 1:** 遍历所有敌人
7
# 攻击索引为 enemyIndex 的敌人
8
enemy = enemies[enemyIndex]
获取当前索引的敌人
9
hero.attack(enemy)
攻击敌人
10
# 给 enemyIndex 加上 1。
11
enemyIndex += 1
索引步进 +1
12
coins = hero.findItems()
获取金币列表
13
# coinIndex 用于迭代 coins 数组。
14
coinIndex = 0
初始化金币索引为 0
15
while coinIndex < len(coins):
**内层循环 2:** 遍历所有金币
16
# 用 coinIndex 从 coins 数组中得到一个金币。
17
coin = coins[coinIndex]
获取当前索引的金币
18
# 收集那个金币。
19
hero.moveXY(coin.pos.x, coin.pos.y)
移动收集
20
# 给 coinIndex 的值增加 1。
21
coinIndex += 1
索引步进 +1