「网易官方」极客战记(codecombat)攻略-沙漠-许愿井-wishing-well_codecombat

(点击图片进入关卡)

从许愿井中获得准确数目的金币。

简介

你需要刚好 104 金钱。

使用 sumCoinValues() 函数得到金币总价值。

如果不够,说 "Non satis" .

如果太多,说 "Nimis" .

如果的确是 104 金钱,那就开始收集。

提示: 看一下 sumCoinValues() 的代码,看看它怎么做到的!

默认代码

# 你需要104的金钱,不多也不少。

less = "Nimis"

more = "Non satis"

requiredGold = 104

# 此函数计算所有的硬币值的总和。

def sumCoinValues(coins):

    coinIndex = 0

    totalValue = 0

    # 遍历所有的金币。

    while coinIndex < len(coins):

        totalValue += coins[coinIndex].value

        coinIndex += 1

    return totalValue

def collectAllCoins():

    item = hero.findNearest(hero.findItems())

    while item:

        hero.moveXY(item.pos.x, item.pos.y)

        item = hero.findNearest(hero.findItems())

while True:

    items = hero.findItems()

    # 获得硬币的总值

    goldAmount = sumCoinValues(items)

    # 如果有金币,那么金币数目 (goldAmount) 不会是零

    if goldAmount != 0:

        # 如果goldAmount 小于requiredGold。

 

            # 那就说“Non satis”

 

        # 如果goldAmount 大于requiredGold。

 

            # 那么说出“Nimis”。

 

        # 如果 “goldAmount” 等于 “requiredGold”

 

            # 如果有刚好 104 金币,就全部收集。

 

        pass

概览

史上最简单的 求和函数 就是将数组内的数字相加:

def sumNumbers(array):

    index = 0

    total = 0

    while index < len(array):

        total += array[index]

        index += 1

我们遍历数组元素,并加到 total 中。

在这关。我们有一个对象(金币)数组,所以我们要把每个金币的 value 属性加起来。

许愿井解法

# 你需要104的金钱,不多也不少。

less = "Nimis"

more = "Non satis"

requiredGold = 104

# 此函数计算所有的硬币值的总和。

def sumCoinValues(coins):

    coinIndex = 0

    totalValue = 0

    # 遍历所有的金币。

    while coinIndex < len(coins):

        totalValue += coins[coinIndex].value

        coinIndex += 1

    return totalValue

def collectAllCoins():

    item = hero.findNearest(hero.findItems())

    while item:

        hero.moveXY(item.pos.x, item.pos.y)

        item = hero.findNearest(hero.findItems())

while True:

    items = hero.findItems()

    # 获得硬币的总值

    goldAmount = sumCoinValues(items)

    # 如果有金币,那么金币数目 (goldAmount) 不会是零

    if goldAmount != 0:

        # 如果goldAmount 小于requiredGold。

        if goldAmount < requiredGold:

            # 那就说“Non satis”

            hero.say(more)

        # 如果goldAmount 大于requiredGold。

        if goldAmount > requiredGold:

            # 那么说出“Nimis”。

            hero.say(less)

        # 如果 “goldAmount” 等于 “requiredGold”

        if goldAmount == requiredGold:

            # 如果有刚好 104 金币,就全部收集。

            collectAllCoins()