第 26 关
许愿井 (Wishing Well)
战术思路分析:精确求和与判定
许愿井需要英雄提供的金币**刚好等于 104**,不多也不少。
阶段 1:求和函数 (`sumCoinValues`)
我们使用一个函数来遍历金币列表,并将每个硬币的 `coin.value` 属性累加到 `totalValue` 中。
阶段 2:三路分支判断
使用三个独立的 `if` 语句(`<`,`>`,`==`)来判断 `goldAmount` 是否:太少、太多,或正好符合要求。
IF Total < 104: Say("Non satis")
IF Total > 104: Say("Nimis")
IF Total == 104: CollectAll()
Python 程序解法
1
less = "Nimis"
定义“过多”的消息
2
more = "Non satis"
定义“不足”的消息
3
requiredGold = 104
定义目标金币数
4
5
def sumCoinValues(coins):
**函数 1:** 计算所有硬币值的总和
6
coinIndex = 0
7
totalValue = 0
初始化总价值为 0
8
while coinIndex < len(coins):
遍历硬币列表
9
totalValue += coins[coinIndex].value
累加每个硬币的价值
10
coinIndex += 1
索引步进
11
return totalValue
返回总价值
12
13
def collectAllCoins():
**函数 2:** 收集所有硬币
14-17
# ... 收集循环逻辑 ...
使用 while 循环和 findNearest 收集所有物品
18
19
while True:
外层无限循环
20
items = hero.findItems()
获取硬币列表
21
# 获得硬币的总值
22
goldAmount = sumCoinValues(items)
调用求和函数
23
# 如果有硬币,那么硬币数目 (goldAmount) 不会是零
24
if goldAmount != 0:
只有有硬币才判断
25
# 如果 goldAmount 小于requiredGold
26
if goldAmount < requiredGold:
判断:是否太少
27
hero.say(more)
说 "Non satis"
28
# 如果 goldAmount 大于requiredGold
29
if goldAmount > requiredGold:
判断:是否太多
30
hero.say(less)
说 "Nimis"
31
# 如果 goldAmount 正好等于 requiredGold
32
if goldAmount == requiredGold:
判断:是否正好
33
# 就收集所有的硬币:
34
collectAllCoins()
执行收集