我正在为Heroscape游戏制作掷骰子(这样我们就可以和海外朋友一起玩了)。heroscape的骰子有6个面。3面显示头骨,1面有符号,2面有盾牌。在
我让它随机生成其中一个面,但我希望它在最后列出结果(即,你掷了6个头骨,2个符号和4个盾牌)。在
这是我当前的代码:
loop = 1
while loop == 1:
diceChoose = raw_input('Pick your dice. (Press 1 for a D20 roll, and 2 for attack /defense dice.) ')
if diceChoose == ('1'):
import random
for x in range(1):
print random.randint(1,21),
print
raw_input("YOUR DICE ROLL(S) HAVE COMPLETED. PRESS ANY KEY TO CONTINUE.")
elif diceChoose == ('2'):
diceNo = int(raw_input('How many dice do you need? '))
testvar = 0
diceRoll = ['skull', 'skull', 'skull', 'symbol', 'shield', 'shield']
from random import choice
while testvar != diceNo:
print choice(diceRoll)
testvar = testvar + 1
if testvar == diceNo:
print ('YOUR DICE ROLLS HAVE COMPLETED')
raw_input("PRESS ANY KEY TO CONTINUE.")
else: loop = raw_input('Type 1 or 2. Nothing else will work. Press 1 to start the program again.')
我试过的是一堆if语句,但是我意识到如果我尝试print('diceRoll'),我得到的只是整个数组,而不是随机选择的骰子掷骰子。在
我不知道如何保存每一个骰子,这样以后我可以打印这个数字。在
(我的想法是
^{pr2}$
我认为解决这个问题的一个好的数据结构应该是标准库中
collections
模块中的Counter
。它的工作原理有点像字典,将对象映射到整数计数。但是,您可以向它添加值,这将增加它们的计数。在所以,我会这么做:
关键行是
counter.update(choice(diceValues) for _ in range(diceNo))
。这使用一个“生成器表达式”调用counter.update
,该表达式生成diceNo
随机滚动结果。如果您还没有学习生成器表达式,我建议您检查一下,因为它们可以派上用场。在欢迎来到这里。我修改了您的代码的一些部分,使它们更类似于我的样式-如果有帮助的话,可以随意修改它们。在
将循环代码更改为:
这可以完成同样的事情,只是它更像Python。在
然后,在一个选项卡中,告诉
^{pr2}$skull, symbol
和shield
的集合数值。在本例中,我们将其设置为0。在接下来,将
^{3}$diceNo = int(raw_input('How many dice do you need? '))
下面的代码改为这样。它应该缩进一个。在这段代码对所需掷骰子的数量重复。然后将1添加到与该名称相关联的变量中。在
在它的正下方,我们向用户显示信息。在
因为你似乎对代码有问题,所以我决定把它全部发布出来。在
相关问题 更多 >
编程相关推荐