代码如上,hero.say()测试了下,己方生命值900多,敌方也900多,感觉代码好像没啥问题,敌方明明人越来越多,生命值后面突然变成800多,但是冲上去打又打不过,搞不明白是哪里出了问题,求指点~
def sumHealth(units): totalHealth = 0 unitIndex = 0 unit = units[unitIndex] while unitIndex < len(units): totalHealth += unit.health unitIndex +=1 return totalHealth while True: friends = hero.findFriends() enemies = hero.findEnemies() friendHealth = sumHealth(friends) enemyHealth = sumHealth(enemies) hero.say("friends have " + friendHealth) hero.say("enemies have " + enemyHealth) if sumHealth(friends) > sumHealth(enemies): hero.say("Attack")
你必须有两个功能; 一个用于敌人的健康,一个用于朋友的健康。
but the function is the same. how to define two functions? @MunkeyShynes
你需要一個功能給你的朋友,一個給敵人。 然後,在您的True循環中,您需要比較函數的輸出totalHealth。 當你的朋友的總體健康比敵人的總體健康要高時,比如說“攻擊”。
唯一可以实现它的方法是使用两个独立的函数。 一个是敌人,一个是朋友。 是的,它们是相同的功能,但它们在分开时起作用。
另外,您还需要1个空间才能正确放置最后一行代码。
另外,刪除:
hero.say("friends have " + friendHealth)
hero.say("enemies have " + enemyHealth)
由於某種原因,這兩條線都在殺死整個事情。 當我包含這兩行時,即使我的代碼也不起作用。可能是由於他們造成的延誤。
`
def sumHealthFriend():
totalHealthFriend = 0
friendIndex = 0
friend = friends[friendIndex]
while friendIndex < len(friends):
totalHealthFriend += friend.health
friendIndex += 1
return totalHealthFriend
def sumHealthEnemy():
totalHealthEnemy = 0
enemyIndex = 0
enemy = enemies[enemyIndex]
while enemyIndex < len(enemies):
totalHealthEnemy += enemy.health
enemyIndex += 1
return totalHealthEnemy
`
不知道我是否正确理解了你的意思,以上是我试的分开两个函数(功能),但是还是和之前一样。我用hero.say()看了下运算的值,一开始,friends是972,enemies是990,之后加人进来,friends变成了1380,enemies变成了820,所以我觉得问题可能是我的算法或者定义有误。(ps:我没有分开的代码计算出来的值也是一样的)
ps:我看了一下,如果一开始friends是972(9个人,每人108),enemies是990(9个人,每人110),后面每次都是先来一个enemy,再来一个friend,这样的话,怎么可能打得过呀~
嘗試對這兩項功能進行這些更改。
def sumHealthFriend():
totalHealthFriend = 0
friendIndex = 0
while friendIndex < len(friends):
friend = friends[friendIndex]
if friend:
totalHealthFriend += friend.health
friendIndex += 1
return totalHealthFriend
成功了。好像就是因为我把应当放在while循环里面的一条语句放在了循环外,当我将它放进循环里面,用我的最初版本的代码也行得通了。非常感谢你的提示。
1 Like
