CodeCombat 狩猎派对

For 循环与动态行军(第 35 关)

第 35 关

狩猎派对 (Hunting Party)

战术思路分析:动态行军

英雄指挥盟友向右侧搜索前进。士兵需要具备**动态决策能力**:

前进 vs 攻击 (`if/else` in `for`)

- **`for friend in friends:`**:高效遍历所有盟友。
- **`if enemy:`**:命令攻击。
- **`else:`**:命令向前移动一小步 (`+ 0.35`)。这种小步移动是实现“平滑行军”的关键,使得部队在发现敌人前保持移动,发现敌人后能立即停止并发起攻击。

IF Enemy: Attack()
ELSE: Command("move", X + 0.35)

Python 程序解法

1
while True:
外层无限循环
2
friends = hero.findFriends()
获取盟友数组
3
# 使用 for 循环,对每个朋友来说:
4
for friend in friends:
遍历每个盟友
5
# 如果他们看到敌人,则命令他们攻击
6
enemy = friend.findNearestEnemy()
盟友寻找最近敌人
7
if enemy:
如果敌人存在
8
hero.command(friend, "attack", enemy)
命令攻击
9
# 否则,命令他们向右侧移动一小步
10
else:
否则
11
moveTo = {"x": friend.pos.x + 0.35, "y": friend.pos.y}
计算新的 X 坐标 (当前 X + 0.35)
12
hero.command(friend, "move", moveTo)
命令缓慢前进