0
我做口袋妖怪的基本版本,我有一個功能,看起來像這樣:改變改名從函數(蟒蛇)內的全局變量
global userhp, comphp
userhp = 100
comphp = 100
def doturn(attacker, enemy, move, attackerhp, enemyhp):
from random import randint
if move == 1:
dmg = randint(18, 25)
enemyhp -= dmg
print("\t" + attacker, "have done", str(dmg), "damage")
print("\t" + enemy, "now have", enemyhp, "health\n")
if move == 2:
dmg = randint(8, 35)
enemyhp -= dmg
print("\t" + attacker, "have done", str(dmg), "damage")
print("\t" + enemy, "now have", enemyhp, "health\n")
if move == 3:
dmg = randint(15, 22)
attackerhp += dmg
print("\t" + attacker, "have healed", str(dmg), "health")
print("\t" + attacker, "now have", attackerhp, "health\n")
下面是一個例子電話:
doturn(user, comp, 3, userhp, comphp)
我遇到的問題是更改attackerhp和enemyhp不會影響userhp和comphp。它保持在100,遊戲無法進展。我需要一種改變全局變量的方式,但也需要這樣做,而不是將變量硬編碼到函數中,因爲這樣它只會對用戶或計算機有效。
我已經能夠解決它,但我的解決方案是返回損壞值並將其應用於userhp和comphp以外的此功能。我可以爲用戶和comp編寫單獨的函數,或者通過if語句檢查是誰轉向它,並且這樣做,但我很想保持這種緊湊。對於任何反饋,我們都表示感謝。
縮進沒有任何意義。 – khelwood