CodeCombat 非阻塞移动与字典

Move vs MoveXY / Object Literals(27-29关)

第 27 关

峭壁追逐 (Cliff Chase)

战术思路分析:动态追踪

目标 Pender Spellbane 不断移动。使用 `moveXY` 会让英雄停下等待目标,导致追逐失败。

关键:`move(pos)` (非阻塞移动)

- **`hero.moveXY(x, y)`:** 阻塞式。程序停止,等待英雄到达目标点。
- **`hero.move(pos)`:** 非阻塞式。英雄只向 `pos` 移动一小步,但程序立即继续执行,允许英雄在下一个循环中获取目标的新位置,实现连续追踪。

move(pos) Check New Pos move(New Pos)

Python 程序解法

1
while True:
外层无限循环
2
# Pender 是这里唯一的朋友,所以她总是最近的朋友。
3
pender = hero.findNearest(hero.findFriends())
寻找 Pender 对象
4
5
if pender:
如果找到目标
6
# move() 只一次移动一步。
7
hero.move(pender.pos)
使用 move(pos) 持续追踪目标
第 28 关

激流回旋 (Slalom)

战术思路分析:坐标对象

在不能使用 `moveXY` 的情况下,移动到固定点需要构造一个 **字典字面量**(Object Literal,如 `{"x": 20, "y": 35}`)来表示位置。

字典字面量作为参数

- `hero.move({'x': 20, 'y': 35})`:将字典直接传递给 `move()`。
- `while hero.pos.x < N:`:利用 `move()` 的非阻塞特性,使用 `while` 循环确保英雄在 X 坐标达到安全点之前一直移动。

move({'x': 20, 'y': 35})

Move one step at a time

Python 程序解法

1
gems = hero.findItems()
获取宝石列表
2
3
while hero.pos.x < 20:
循环直到 X 坐标达到 20
4
hero.move({'x': 20, 'y': 35})
向固定点 (20, 35) 移动
5
6
while hero.pos.x < 25:
移动到 X=25 (收集宝石 0)
7
gem0 = gems[0]
8
hero.move(gem0.pos)
向宝石 0 的位置移动
9
# 当你的 x 小于30的时候,使用物体移动到30,35位置
10
while hero.pos.x < 30:
移动到 X=30
11
hero.move({'x': 30, 'y': 35})
12
# 当你的 x 小于35的时候,移动到宝石[1]的位置
13
while hero.pos.x < 35:
移动到 X=35 (收集宝石 1)
14
gem1 = gems[1]
15
hero.move(gem1.pos)
向宝石 1 的位置移动
16
# 拿到最后一对宝石!
17
while hero.pos.x < 40:
移动到 X=40
18
hero.move({'x': 40, 'y': 35})
19
while hero.pos.x < 45:
移动到 X=45 (收集宝石 2)
20
gem2 = gems[2]
21
hero.move(gem2.pos)
向宝石 2 的位置移动
22
while hero.pos.x < 50:
移动到 X=50
23
hero.move({'x': 50, 'y': 35})
24
while hero.pos.x < 55:
移动到 X=55 (收集宝石 3)
25
gem3 = gems[3]
26
hero.move(gem3.pos)
向宝石 3 的位置移动
第 29 关

兽人山谷挖宝 (Ogre Valley)

战术思路分析:限时抢劫

英雄必须在 20 秒内尽可能多地收集金币,然后撤退到安全位置并建造防御。

阶段控制与 Move

1. **抢劫循环:** `while hero.time < 20:` (基于时间,使用 `move` 动态追踪金币)
2. **撤退循环:** `while hero.pos.x > 16:` (基于位置,确保英雄撤到围栏后)

WHILE Time < 20: Collect()
WHILE Pos.X > 16: Retreat()

Python 程序解法

1
while hero.time < 20:
当游戏时间小于 20 秒
2
# 收集金币
3
coin = hero.findNearest(hero.findItems())
找到最近的硬币
4
hero.move(coin.pos)
使用 move 持续向硬币移动
5
6
while hero.pos.x > 16:
当英雄 X 坐标大于 16 (在围栏右侧)
7
# 撤退到围栏后面
8
hero.move({"x": 15, "y": 38})
移动到围栏后方 (X=15)
9
10
# 建立围栏,挡住兽人。
11
hero.buildXY("fence", 20, 37)
建造围栏