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

2024-04-27 14:18:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了一个问题,一些代码,我正在做的模拟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)

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


Tags: yourtimeissleepdicestrengthattributesintelligence
1条回答
网友
1楼 · 发布于 2024-04-27 14:18:44

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

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

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

相关问题 更多 >