CodeCombat 一维列表与索引

列表、访问与遍历(9-13关)

第 9 关

团队合作 (Teamwork)

战术思路分析:分工合作

三颗宝石,三个人分工收集。`hero.findItems()` 返回一个包含所有宝石的**列表(数组)**。

核心:索引从 0 开始

列表中的元素是从 **0** 数起的。
- 第一个元素:`items[0]`
- 第二个元素:`items[1]`
- 第三个元素:`items[2]`

Items = [Gem A, Gem B, Gem C]
Gem A = Items[0]

Python 程序解法

1
# findItems() 返回一个项目数组。
2
items = hero.findItems()
获取所有物品的列表
3
4
# 从数组中获取第一颗宝石。索引是 0。
5
gem0 = items[0]
获取第一个元素(索引 0)
6
7
# 告诉 Bruno 拿到 gem0
8
hero.say("Bruno " + gem0)
向 Bruno 发送取第一个宝石的命令
9
10
# 告诉 Matilda 拿到第二个宝石 (items[1])。
11
hero.say("Matilda " + items[1])
使用列表索引直接访问第二个元素(索引 1)
12
13
# 为最后一个宝石 items[2] 创建一个变量:
14
gem2 = items[2]
获取第三个元素(索引 2)
15
16
# 使用 moveXY() 移至该宝石的位置
17
hero.moveXY(gem2.pos.x, gem2.pos.y)
英雄自己去拿第三个宝石
第 10 关

协助防御 (Assisted Defense)

战术思路分析:避免空列表错误

英雄只负责攻击列表中的**第一个敌人** (`enemies[0]`)。如果列表是空的,直接读取 `enemies[0]` 会导致程序崩溃。

核心:检查列表长度 (`len()`)

我们使用 `if len(enemies) > 0:` 来确保列表中至少有一个元素。
`len()` 函数返回列表的长度。一个空列表的长度为 0。

IF len(Enemies) > 0:
  Attack(Enemies[0])

Python 程序解法

1
while True:
外层无限循环
2
# 得到一个敌人的数组。
3
enemies = hero.findEnemies()
获取所有敌人的列表
4
# 如果数组不为空。
5
if len(enemies) > 0:
判断列表长度是否大于 0
6
# 攻击 "enemies" 数组中的第一个敌人。
7
hero.attack(enemies[0])
攻击第一个元素(索引 0)
8
# 返回到起始位置。
9
hero.moveXY(40, 20)
返回到防御点
第 11 关

招募队伍 (Recrut)

战术思路分析:动态更新列表

农民(被检测为敌人)一旦被招募,就会从列表中消失。英雄必须在每次循环中**更新**农民列表。

核心:循环末尾的 `findEnemies()`

我们必须在 `while` 循环的**末尾**重新调用 `neutrals = hero.findEnemies()`。这样,每次新的迭代开始时,`neutrals` 列表都是最新的。

WHILE ...:
  Say Name
  List = FindEnemies()

Python 程序解法

1
# 中立单位被检测为敌人。
2
neutrals = hero.findEnemies()
首次获取中立农民列表
3
while True:
外层无限循环
4
if len(neutrals):
如果列表非空
5
# 说出 neutrals 数组中的第一个元素
6
hero.say(neutrals[0])
呼叫第一个农民
7
else:
8
hero.say("没有人在这儿")
如果没有可招募的农民
9
# 使用 findEnemies() 给 neutrals 变量重新赋值
10
neutrals = hero.findEnemies()
**关键:** 更新列表以检查下一次迭代
第 12 关

第二宝石 (Second Gem)

战术思路分析:排除陷阱

第一个宝石是陷阱,**第二个宝石**才是安全的。

关键:索引 1

- 第二个宝石的索引是 **`1`**。
- 访问前,必须检查 `len(items) >= 2`,以防止访问不存在的元素而导致程序崩溃。

IF len(Items) >= 2:
  Move(Items[1])

Python 程序解法

1
while True:
外层无限循环
2
items = hero.findItems()
获取物品列表
3
# 如果 items 数组元素个数大于或等于 2:
4
if len(items) >= 2:
确保列表中有第二个元素
5
# 移动到 items 数组中的第二项
6
hero.moveXY(items[1].pos.x, items[1].pos.y)
移动到安全宝石(索引 1)
7
# 否则:
8
else:
9
# 移动到中心标记。
10
hero.moveXY(40, 34)
回到待命点
第 13 关

Sarven 救世主 (Sarven Savior)

战术思路分析:列表遍历

英雄有朋友名字的列表,需要**逐个**呼叫他们回家。

遍历三要素

  • **初始化:** `friendIndex = 0`
  • **条件:** `while friendIndex < len(friendNames):` (索引小于列表长度)
  • **步进:** `friendIndex += 1` (每次循环后索引加 1)

WHILE Index < len(List):
  Say(List[Index])
  Index += 1

Python 程序解法

1
friendNames = ['Joan', 'Ronan', 'Nikita', 'Augustus']
朋友名字列表
2
3
friendIndex = 0
初始化索引为 0
4
5
while friendIndex < len(friendNames):
循环条件:索引小于列表长度
6
friendName = friendNames[friendIndex]
获取当前索引对应的名字
7
8
hero.say(friendName + ', go home!')
发出命令
9
10
friendIndex += 1
索引步进 +1
11
12
hero.moveXY(22, 30)
移动到绿洲
13
hero.buildXY("fence", 30, 30)
建造围栏