gpt4 book ai didi

Python 3.1.1 - 为函数分配随机值

转载 作者:行者123 更新时间:2023-12-01 05:36:37 25 4
gpt4 key购买 nike

我需要一种方法来为函数分配随机值,调用该函数并将值打印到屏幕上。

当我按原样运行代码时,敌人的攻击和用户的防御不会重新计算。我该怎么做才能让Python在每次调用函数时重新计算这些变量?

import random

enemyName = "Crimson Dragon"

def dragonAtk():
return random.randint(5,10)

def userDef():
return random.randrange(8)

userHp = 100
userName = input("What is your name? ")
enemyAttackname = "Fire Blast"

def enemyAttacks():
global battleDmg
global userHp
global enemyAtk
global userDef

enemyAtk = dragonAtk()
userDef = userDef()

print (">>> " + enemyName + " attacks " + userName + " with " + enemyAttackname + "!")
if enemyAtk < userDef:
print (">>> " + userName + " successfully defended the enemy's attack!")
elif enemyAtk == userDef:
print (">>> " + userName + " successfully parried the enemy's attack!")
else:
battleDmg = enemyAtk - userDef
userHp -= battleDmg
print (">>> " + userName + " takes " + str(battleDmg) + " DMG! "\
+ userName + " has " + str(userHp) + " HP remaining!")

enemyAttacks()
input()
enemyAttacks()
input()

这是我的结果

What is your name? Murk
>>> Crimson Dragon attacks Murk with Fire Blast!
>>> Murk takes 6 DMG! Murk has 94 HP remaining!

Traceback (most recent call last):
File "C:\Users\Junior\Desktop\python projects\test", line 37, in <module>
enemyAttacks()
File "C:\Users\Junior\Desktop\python projects\test", line 22, in enemyAttacks
userDef = userDef()
TypeError: 'int' object is not callable
>>>

所以,我看到它通过敌人攻击()运行了一次,但第二次给了我一个错误。不知道该怎么做。有什么想法吗?

最佳答案

这里:

userDef = userDef()

您已经覆盖了您的函数。因此,当您再次调用该函数时,您正在尝试调用该函数,但您有一个整数(因此出现错误)。

将变量重命名为其他名称,这样就不会覆盖函数。

关于Python 3.1.1 - 为函数分配随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18838576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com