【问题标题】:How do I roll a dice and store the total number using Python3.4如何使用 Python3.4 掷骰子并存储总数
【发布时间】:2016-09-19 12:00:34
【问题描述】:
import tkinter
import random

def rollDice():
   x=random.randint(1,6)
   total=0
   if x == 1:
   total+=1
   ....
print(total)

我想添加我在.rollDice 中滚动的每个数字并存储到total 中,最大为50。我该怎么做?

【问题讨论】:

  • 你是什么意思最大是50?直到total 变为 50 或更多或掷骰子 50 次?您也不必检查x 的值。只需像这样将其添加到总数中:total += x
  • 听起来你在要求我们做你的功课。
  • 不确定这与 tkinter 有什么关系。你已经有了+= 运算符,所以进入一个while循环(虽然总数小于或等于50,即<=),每次都加上掷骰子的结果。
  • @BryanOakley 实际上这对我来说是一项额外的任务,我目前在我的第一个学期,编程入门。但是,是的,我要求你提高我的家庭作业。 :D
  • @PaulRooney 感谢您的帮助,现在我尝试在 tkinter 中添加标签和按钮,一旦您按下按钮,它将滚动一次。这是我的简单工作,对不起语法,我的英语不太好。 w = Button(root,text="Roll A Dice",command=rollDice,wraplengt=30,bg="pink").grid(row=6, column=1) root.mainloop()

标签: python tkinter


【解决方案1】:

正如@PaulRooney 所说,我不确定tkinter 与此有什么关系。据我了解,您想掷骰子直到您的total 达到或超过 50.. 所以这是我的看法:

from random import randint

def rollDice():
    return randint(1,6)

total = 0
while total < 50:
    new_roll = rollDice()
    total += new_roll
    print('You rolled a {}. The new total is {}'.format(new_roll, total))
# You rolled a 3. The new total is 3
# You rolled a 3. The new total is 6
# You rolled a 4. The new total is 10
# You rolled a 6. The new total is 16
# You rolled a 2. The new total is 18
# You rolled a 1. The new total is 19
# You rolled a 5. The new total is 24
# You rolled a 5. The new total is 29
# You rolled a 4. The new total is 33
# You rolled a 5. The new total is 38
# You rolled a 2. The new total is 40
# You rolled a 3. The new total is 43
# You rolled a 4. The new total is 47
# You rolled a 6. The new total is 53

【讨论】:

  • 谢谢你:D 如果可能的话,添加一个按钮到“掷骰子”?
  • 有可能,但最好将其作为一个单独的问题提出,因为它与这个问题本质上无关。
猜你喜欢
  • 2021-04-06
  • 1970-01-01
  • 2018-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-06
  • 1970-01-01
相关资源
最近更新 更多