Python 3.1.1 - 为函数分配随机值

时间:2013-09-16 22:47:45

标签: python function

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

当我按原样运行代码时,敌人的攻击和用户的防御不会重新计算。每次调用函数时,我该怎么做才能让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
>>> 

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

1 个答案:

答案 0 :(得分:2)

下面:

userDef = userDef()

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

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