「网易官方」极客战记(codecombat)攻略-沙漠-Sarven 救世主-sarven-savior

(点击图片进入关卡)

使用数组把你的朋友带到家,让你的敌人远离。

简介

“数组” 是一个项目列表。

# 一个字符串数组:
friendNames = ['Joan', 'Ronan', 'Nikita', 'Augustus']

默认代码

# 一个数组(Array)就是物品的数列。
# 这个数组是一个朋友名字的数列。
friendNames = ['Joan', 'Ronan', 'Nikita', 'Augustus']
# 数组从零开始计数,不是1!
friendIndex = 0
# 循环该数组中的每一个名字
# 使用 len()方法来得到列表的长度。
while friendIndex < len(friendNames):
    # 使用方括号来获得数组中的名字。
    friendName = friendNames[friendIndex]

 

    # 告诉你的朋友回家。
    # 使用+来连接两个字符串。
    hero.say(friendName + ', go home!')

 

    # 增加索引来获取数组中的下一个名字

 

# 回去建造栅栏让食人魔远离。

概览

数组是有序的数据列表。 在这个关卡中,你有一个数组存储你的四个朋友的字符串名称。

为了拯救你的朋友,你需要告诉他们每个人轮流回家。 您可以使用提供的示例代码来遍历数组。

# friendNames 是一个数组。
friendNames = ['Joan', 'Ronan', 'Nikita', 'Augustus']

 

# 你可以使用方括号包围的数字来访问数组的特定元素:
name = friendNames[0]

 

# 这会让英雄说出 "Joan"
hero.say(name)

你可以使用索引变量而不是数字来访问数组的元素。

要遍历数组中的所有值,请使用while循环在每次循环中递增索引变量!

在每次循环中,你要取出该数组索引处的朋友姓名,然后告诉该朋友回家。

friendNames = ['Joan', 'Ronan', 'Nikita', 'Augustus']

 

# 数组索引从 0 开始
friendIndex = 0

 

# len(friendNames) 返回 friendNames 数组的长度。
# 长度等于数组里的元素个数(在这个例子里是4)

 

while friendIndex < len(friendNames):
    friendName = friendNames[friendIndex]
    hero.say(friendName + ', go home!')
    friendIndex += 1
# 这个 while 循环会以 friendIndex 为 0 执行,然后是 1、2 和 3
# 注意数组的长度是 4,但最后一个元素的索引是 3!

Sarven 救世主 解法

# 一个数组(Array)就是物品的数列。
# 这个数组是一个朋友名字的数列。
friendNames = ['Joan', 'Ronan', 'Nikita', 'Augustus']
# 数组从零开始计数,不是1!
friendIndex = 0
# 循环该数组中的每一个名字
# 使用 len()方法来得到列表的长度。
while friendIndex < len(friendNames):
    # 使用方括号来获得数组中的名字。
    friendName = friendNames[friendIndex]
    # 告诉你的朋友回家。
    # 使用+来连接两个字符串。
    hero.say(friendName + ', go home!')
    # 增加索引来获取数组中的下一个名字
    friendIndex += 1

 

# 回去建造栅栏让食人魔远离。
hero.moveXY(22, 30)
hero.buildXY("fence", 30, 30)
 
本攻略发于极客战记官方教学栏目,原文地址为:
原文地址:https://www.cnblogs.com/codecombat/p/13353252.html