【问题标题】:How do I reset the value of variables in a loop? (Python 3.1.1)如何在循环中重置变量的值? (Python 3.1.1)
【发布时间】:2013-08-21 21:32:20
【问题描述】:

当我运行我的代码并进入游戏的战斗部分时,我会随机获得分配给我的角色攻击、防御、伤害和健康的值。但是,在他们的第一轮之后,他们一直获得相同的值并且无法重置。

例如,用户的攻击是一个从 4 到 11 的随机数。程序“滚动”5 并将其分配给变量 userAtk

userAtk = random.randint(4,11)

我假设每次循环运行时,它都会生成一个新值。 但它不是,每次我打印变量时,它的值都是第一次分配的。 我错过了什么吗?

下面是我的代码

import random

# VARIABLES
#
#
# This variable is the user's character name
userName = input("Brave warrior, what is your name? ")

# This variable is used in the input function to pause the game
enterNext = ("Press enter to continue...")

# This variable is used to format the user input prompt
# as well as the battle text
prompt = ">>>>>  "

# This variable is used to add a new line to a string
newLine = "\n"

# This variable is used to display a message when the hero dies
heroDeadmsg = userName + " has fallen!"

# These variables represent the dragon's stats (HP, ATK & DEF)
dragonHp = 100
dragonAtk = random.randint(5,10)
dragonDef = random.randrange(8)

# These variables represent the user's stats (HP, ATK & DEF)
userHp = 90
userAtk = random.randint(4,11)
userDef = random.randrange(8)

# These variables calculate battle damage and HP
dragonDmg = (userAtk - dragonDef)
dragonHp -= dragonDmg
userDmg = (dragonAtk - userDef)
userHp -= userDmg

# This variable prints the options in the battle menu
battleMenu = """Attack (a) - Magic (m) - Item (i) - Run (r)""" 

# This variable determines who goes first
cointoss = random.randint(0, 1)

# These variables print the actions in each turn
dragonAttack = \
    prompt + "Crimson Dragon attacks you with " + str(dragonAtk) + " ATK!"\
    + newLine + prompt + "You defend with " + str(userDef) + " DEF!"\
    + newLine + prompt

userAttack = \
    prompt + "You attacked with " + str(userAtk) + " ATK!"\
    + newLine + prompt + "Crimson Dragon defends with " + str(dragonDef) + " DEF!"\
    + newLine + prompt

userMagic = \
    prompt + userName + " tried to use Magic!"\
    + newLine + prompt + userName + " has no magic!"\
    + newLine + prompt

userItem = \
    prompt + userName + " tried use an Item!"\
    + newLine + prompt + userName + " has no Items!"\
    + newLine + prompt

userRetreat = \
    prompt + userName + " tries to retreat!"\
    + newLine + prompt + "The enemy won't let you escape!"\
    + newLine + prompt


# These variables show health during battle 
printDragonhp = "Crismon Dragon has " + str(dragonHp) + " HP remaining!"
printUserhp = userName + " has " + str(userHp) + " HP remaining!"

# This variable simulates the results of a coin toss
coinToss = random.randint(0, 1)


#
#
# CONDTITIONS
#
#
# These conditions determines who attacks first
if coinToss == 0:
    currentTurn = "dragon"
elif coinToss == 1:
    currentTurn = "user"
else:
    print("The Coin Toss Failed!")    

#
#
# BATTLE MECHANICS
#
#

while currentTurn:
# Mechanics for the Crimson Dragon's Turn
if currentTurn == "dragon":

    # Prints the Crimson Dragon's Attack and ends the turn
    print(newLine + prompt + "Crimson Dragon moves!"\
          + newLine + prompt + newLine + dragonAttack\
          + newLine + prompt + userName + " takes " + str(userDmg) + " DMG!"\
          + newLine + prompt + printUserhp)
    currentTurn = "user"
    input(prompt)

    # Need to implent a way to reset ATK and DEF

# Mechanics for the User's Turn    
if currentTurn == "user":

    # Prints the Battle Menu and asks for the User's choice
    print(newLine + prompt + battleMenu\
          + newLine + prompt)
    userChoice = input(prompt)

    # Prints the User's Attack and ends the turn
    if userChoice == "a":
        print(userAttack)
        if userHp < 1:
            print(heroDeadmsg)
            break

        input (prompt)
        currentTurn = "dragon"
    # Prints the User's Magic and ends the turn
    elif userChoice == "m":
        print(userMagic)
        input (prompt)
        currentTurn = "dragon"
    # Prints the User's Item and ends the turn   
    elif userChoice == "i":
        print(userItem)
        input (prompt)
        currentTurn = "dragon"
    # Prints the User's Retreat and ends the turn    
    elif userChoice == "r":
        print(userRetreat)
        input (prompt)
        currentTurn = "dragon"
    # Prints an error message for invalid entries
    else:
        print(newLine + prompt + "That is not a valid menu item."\
              + newLine + prompt + "Please try again.")

【问题讨论】:

  • 你不需要` character for multiple line statements when parentheses are involved. For example, in your multiline print function calls you can remove the `。
  • 另外,你应该看看 python 的string formatting。您可以使用它来缩短用于使用 + 运算符构建字符串的所有行。
  • 您似乎在寻找一种神奇的东西,每次您将其作为数字访问时,它都有不同的价值。你实际上可以创建这样一个类型,但是那里有很多混淆的可能性,这就是为什么 Python 没有给你这样一个内置的类型。特别是,random.randint() 返回;它只是随机选择一个常规的旧 int 并将其返回给您。

标签: python variables loops reset


【解决方案1】:

random.randint(4,11) 只是在[4, 11] 范围内选择一个整数并返回该数字。因此,当您执行userAtk = random.randint(4,11) 时,您只是得到一个号码并将其存储为userAtk,每次您访问userAtk 时,您都会得到相同的号码。

如果您希望userAtk 成为一种神奇的东西,每次访问它时就像在[4, 11] 范围内的不同数字一样......好吧,这并非不可能(请参阅here 快速&肮脏的刺伤它)......但它几乎肯定会导致更多的混乱而不是好处。

例如,您的代码尝试打印出str(userAtk)...,但如果您每次访问它时的值都不同,那么打印出来的内容将与计算伤害的内容不同!想象一下,如果你在玩桌面 D&D,地牢大师掷骰子告诉你掷骰结果,然后立即忘记结果并再次掷骰子以确定你是否命中。所以他可能会说,“你掷出 20。你错过了。”这样不好。

可能有用的是让userAtk实际上是一个函数:

def userAtk():
    return random.randint(4, 11)

对于所有类似的变量也是如此。然后,在您只是访问一个数字的任何地方,您都将调用该函数:

def dragonDmg():
    return userAtk() - dragonDef()

然后,您可能希望将调用这些函数的结果存储在每个循环内的一些局部变量中。

但关键是,无论你怎么做,你都必须有变量,每次循环都要重新计算。

【讨论】:

  • 谢谢!我很高兴我能够清楚地向社区传达我的答案!你甚至确切地知道我在想什么(即使我错了)所以,实际上我大约 2 天前才开始使用 Python,我真的只是在这里进行实验,我还没有开始定义函数。
  • 那么当你说“存储调用这些函数的结果”时,你的意思是像给变量赋值吗?
  • @Junior:确实,分配变量是存储值的明显方式。当然,您也可以通过将它们附加到列表,或将它们作为参数传递给函数(最终为参数变量分配值)或其他各种方式来存储它们。
【解决方案2】:

据我所知,因为userAtk 不在循环中。如果您希望它在循环内重置,请在循环内调用random.randint(4,11)

【讨论】:

  • 我以为我做到了,因为我已经编写了分配给它的变量,但我错了,它不能那样工作。 abarnert 实际上一针见血stackoverflow.com/a/18325841/2644456 谢谢大家
【解决方案3】:

我相信即使你调用 randint() 一百万次,你仍然会得到重复(我相信你知道这一点)。我曾经使用字典来跟踪已使用/未使用的随机数,并且只需检查字典是否已被使用。可能误解了这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    • 2020-02-14
    • 1970-01-01
    • 2013-04-10
    • 1970-01-01
    相关资源
    最近更新 更多