如何将已随机生成的数字添加到已设置的变量中?

时间:2018-03-09 16:49:46

标签: python

我遇到了一些问题,我正在做一些代码来模拟D& D(龙与地下城)广告系列。

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

我制作了一个代码来滚动一个4面骰子和一个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)

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

1 个答案:

答案 0 :(得分:2)

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

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

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