【问题标题】:How can I add a randomly generated number to a variable that has already been set?如何将随机生成的数字添加到已设置的变量中?
【发布时间】:2018-03-09 16:49:46
【问题描述】:

我在模拟 D&D(龙与地下城)战役时遇到了一些代码问题。

这是代码,但我只是在最近的部分遇到困难。

我编写了滚动 4 面骰子和 20 面骰子的代码,将 20 面骰子的结果除以 4 面骰子的结果,然后将此值添加到预设值 10像这样:

import math
strength = 10
dexterity = 10
wisdom = 10
intelligence = 10
constitution = 10
charisma = 10
attributes = ['strength', 'dexterity', 'wisdom', 'intelligence', 'constitution', 'charisma', strength, dexterity, wisdom, intelligence, constitution, charism]
import random
print("You have 6 attributes. Each level is 10. This is your chance to improve your stats.")
for iCount in range(0, 5):  
    print("Time to roll for", attributes[iCount]+".")
    roll = input("Press enter to roll a dice.")
    dice_result = random.randint(1,12)
    print("You roll a 12-sided dice and get", dice_result)
    roll = input("Press enter to roll another dice.") 
    dice_result2 = random.randint(1,4)
    print("You roll a 4-sided dice and get", dice_result2)
    attributes[iCount+6] = dice_result // dice_result2
    print("Your", attributes[iCount] ,"is", attributes[iCount+6])
import time
strength += 10
print("Your strength is", strength)
time.sleep(2)
dexterity += 10
print("Your dexterity is", dexterity)
time.sleep(2)
wisdom += 10    
print("Your wisdom is", wisdom)
time.sleep(2)
intelligence += 10
print("Your intelligence is", intelligence)
time.sleep(2)
constitution += 10
print("Your constitution is", constitution)
time.sleep(2)
charisma += 10
print("Your charisma is", charisma)
time.sleep(2)

没有语法错误,尽管当我的代码运行时,我会得到第一个变量的低值,然后其余变量的值相同。

【问题讨论】:

  • 更新列表中的值不会更新您用于填充列表的变量。所以strength 仍然是10,无论你存储在attributes 列表中。
  • 您应该使用字典,而不是单独的变量。请参阅Python tutorial

标签: python


【解决方案1】:

当您将strengthdexterity 等的值添加到您的attributes 数组时,您只是添加了它们的当前值。更新数组中的这些值不会更新原始变量,反之亦然:

>>> a = 5
>>> b = [a]
>>> a = 6
>>> b
[5]
>>> b[0] = 7
>>> a
6

您应该考虑改用字典:https://docs.python.org/3/tutorial/datastructures.html#dictionaries

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多