python - python 中的骰子模拟与无限的可定制骰子?
问题描述
我正在研究经典的“在 python 中构建一个骰子模拟”学校项目,我试图让它变得非常复杂。基本上,我正在尝试的是一种方法,当你按下一个按钮时,我不想滚动一个 n 面 x 次的骰子,我想滚动 x 个骰子,每个骰子都有自己的面数。我对python一窍不通,所以我什至不知道这是否可能。据我所知,它似乎需要大量的变量,因为在创建信息时没有真正的方法可以“保存”信息。这是我的代码,它确实有效:
from random import randint
stop="c"
dicenumb=0
print ("Automatic Dice Roller")
while stop !="x":
if stop == "c":
print ("Type how many dice you want to roll, then press enter.")
d=input("")
print ("Type how many sides you want each dice to have, then press enter.")
s=input("")
print("rolling %s dice with %s side(s)!" % (d,s))
for x in range (0,int(d)):
dicenumb += 1
print("Dice # %s is...%s!" % (dicenumb,randint(1,int(s))))
dicenumb=0
print("Press enter to roll, c then enter to change the amount of dice and sides, or x then enter to exit!")
stop=input("")
这是我正在处理的代码,以便尝试这样做:
from random import randint
stop="c"
dicenumb=0
dicecust=0
print ("Automatic Dice Roller")
while stop !="x":
if stop == "c":
print ("if you want to enter the values of each dice individually, press i, then enter. Otherwise, press enter")
ind=input("")
if ind != "i":
print ("Type how many dice you want to roll, then press enter.")
d=input("")
print ("Type how many sides you want each dice to have, then press enter.")
s=input("")
print("rolling %s dice with %s side(s)!" % (d,s))
for x in range (0,int(d)):
dicenumb += 1
print("Dice # %s is...%s!" % (dicenumb,randint(1,int(s))))
dicenumb=0
else
for x in range (0,int(d)):
print ("how many dice would you like to roll? maximum of 10.")
custnumb=input("")
dicecust += 1
print "how many sides would you like dice #%s to have?" % dicecust
print("Press enter to roll, c then enter to change the amount of dice and sides, or x then enter to exit!")
stop=input("")
解决方案
建立一个你想要掷骰子的列表,然后遍历这个列表:
from random import randint
n = int(input("How many dice would you like to roll?\n"))
dice = [
int(input(f"How many sides would you like die #{i} to have?\n"))
for i in range(1, n + 1)
]
for i, die in enumerate(dice, 1):
print(f"Die #{i} is... {randint(1, die)}!")
How many dice would you like to roll?
6
How many sides would you like die #1 to have?
4
How many sides would you like die #2 to have?
100
How many sides would you like die #3 to have?
6
How many sides would you like die #4 to have?
6
How many sides would you like die #5 to have?
20
How many sides would you like die #6 to have?
100
Die #1 is... 1!
Die #2 is... 51!
Die #3 is... 4!
Die #4 is... 6!
Die #5 is... 9!
Die #6 is... 57!
推荐阅读
- css - 为什么第 n 个子颜色在 markdown++ 查看器中不起作用?
- c# - Mongodb C# 驱动程序执行字符串包含对嵌入文档中的属性的查询
- selenium - TestNG中Appium测试用例的顺序执行导致测试用例失败
- r - 在 R 中创建嵌套列表
- visual-studio-code - 如何让vscode在保存时自动重命名文件?
- android - 如何使用 Firestore 集合中的经度和纬度在地图上显示带有标记的位置?
- ruby - postgresql 中枚举类型列的包含过滤
- java - 为什么android程序不能在我的手机上运行(它可以在虚拟手机上正常运行)
- php - 使用数组的 PHP 递归
- java - Flutter 说它“无法解决项目”