CodeCombat 团队指挥与召唤

列表遍历与非阻塞移动(30-31关)

第 30 关

安息之云指挥官 (Cloudrip Commander)

战术思路分析:召唤与集结

英雄拥有**首领之星**,可以召唤士兵并指挥他们。

阶段 1:召唤士兵

使用 `hero.costOf("soldier")` 检查所需金钱,确保在召唤前 (`hero.summon`) 金钱足够。

阶段 2:命令集结

使用 `while` 循环遍历 `hero.findFriends()` 数组,并使用 `hero.command(unit, "move", {x: N, y: N})` 命令每个士兵移动到集合点。

WHILE Gold > Cost: Summon()
WHILE Index < len(S): Command("move", {x, y})

Python 程序解法

1
# 每个士兵消耗 20 金钱。
2
while hero.gold > hero.costOf("soldier"):
当金钱足够召唤士兵时
3
hero.summon("soldier")
召唤士兵
4
5
soldiers = hero.findFriends()
获取盟友数组
6
soldierIndex = 0
初始化索引
7
# 添加一个 while 循环来命令所有的士兵。
8
while soldierIndex < len(soldiers):
遍历所有士兵
9
soldier = soldiers[soldierIndex]
获取当前士兵
10
hero.command(soldier, "move", {"x": 50, "y": 40})
命令士兵移动到集合点
11
soldierIndex += 1
索引步进
12
13
# 去加入你的朋友!
14
target = {"x": 48, "y": 40}
英雄的移动目标(字典)
15
while hero.distanceTo(target):
当英雄未到达目标时
16
hero.move(target)
使用 move (非阻塞) 持续移动
第 31 关

佣兵山 (Mountain Mercenaries)

战术思路分析:持续战斗指挥

英雄必须在收集硬币的同时,持续指挥盟友攻击最近的敌人。

一个 `while True` 包裹所有逻辑

- **`move(coin.pos)`:** 英雄使用非阻塞移动收集硬币。
- **`hero.command(soldier, "attack", enemy)`:** 在同一循环内,英雄找到敌人并命令所有士兵攻击。
英雄在每一步都能同时管理移动、召唤和指挥。

WHILE True:
  Collect()
  Summon()
  Command "attack"

Python 程序解法

1
while True:
外层无限循环
2
# 移动到最近的硬币处。
3
coin = hero.findNearest(hero.findItems())
寻找最近的硬币
4
if coin:
如果硬币存在
5
hero.move(coin.pos)
使用 move 持续收集
6
7
# 如果攒够了招募士兵的资金,就招募一个。
8
if hero.gold > hero.costOf("soldier"):
如果金钱足够
9
hero.summon("soldier")
召唤士兵
10
11
enemy = hero.findNearest(hero.findEnemies())
寻找最近的敌人
12
if enemy:
如果敌人存在
13
soldiers = hero.findFriends()
获取盟友数组
14
soldierIndex = 0
初始化索引
15
# 遍历你所有的士兵,命令他们攻击。
16
while soldierIndex < len(soldiers):
遍历所有士兵
17
soldier = soldiers[soldierIndex]
获取当前士兵
18
soldierIndex += 1
索引步进
19
# 使用 'attack' 命令,让你的士兵们发起攻击。
20
hero.command(soldier, "attack", enemy)
命令士兵攻击敌人