【问题标题】:How to implement a Loop statement如何实现循环语句
【发布时间】:2019-05-09 09:08:49
【问题描述】:

我用我能想到的几行代码制作了一个简单的 Yahtzee 游戏。目前,用户必须按 Enter(任意值)才能继续。我想使用循环语句,以便骰子继续滚动直到 Yahtzee(所有滚动数字都相同)。我也想要一个 10 秒的计时器。向此代码添加循环语句的最佳方法是什么?附言这不是家庭作业,我想为我的 Yahtzee 之夜制作这款游戏​​。我的女儿很容易醒来......哈哈

import random

while True:
    dice1 = random.randint(1,6)
    dice2 = random.randint(1,6)
    dice3 = random.randint(1,6)
    dice4 = random.randint(1,6)
    dice5 = random.randint(1,6)
    numbers = (dice1, dice2, dice3, dice4, dice5)
    sum1 = sum(numbers)
    if  sum1 == ("5" or "10" or "15" or "20" or "25"):
        print("Winner, winner, chicken dinner!", dice1, dice2, dice3, dice4, dice5)
    else:
        print("Your rolls are: ", dice1, dice2, dice3, dice4, dice5)
    input("Press return key to roll again.")

编辑:这是我的最终产品。谢谢大家的帮助!!

import random
import time
input("Press return key to roll.")
for x in range(0,10000):
    numbers = [random.randint(1,6) for _ in range(5)]
    if all(x == numbers[0] for x in numbers):
        print("Winner, winner, chicken dinner!", numbers)
        input("Press return key to play again.")

    else:
        print("Your rolls are: ", numbers)        
        print("Next roll in one second.")
        time.sleep(1)   

【问题讨论】:

  • sum1 == ("5" or ...) 条件仅在 sum1'5'(string) 时为真。你需要的是sum1 in (5, 10, ...)sum1 是整数,需要用整数进行测试(5'5' 不同)。
  • 你有一个循环 (while True:)。如果所有数字都相同,请在您比较的地方添加一行。如果这是真的break 则退出循环。将input 替换为对time.sleep 的调用。
  • 当然,删除那些编号变量dice1dice2 等会更容易。只需创建一个列表:numbers = [random.randint(1, 6) for _ in range(5)]
  • @Matthias 谢谢!这大大缩短了我的代码哈哈

标签: python


【解决方案1】:

如果您想检查所有骰子的数字是否相同,就这么简单。

allDice = [dice1, dice2, dice3, dice4, dice5] #List of dice variables
if all(x == allDice[0] for x in allDice): # If all dice are the same
    print("Yahtzee")
    break # Break out of while loop

拥有“计时器”的最简单方法是添加time.sleep()。您必须import time 否则将无法正常工作。

所以替换 input("Press return key to roll again.")time.sleep(10)

这意味着每 10 秒掷一次骰子,直到所有骰子的数字相同,如果它们相同,则打印 Yahtzee 并停止循环。

【讨论】:

  • 您的解决方案仅适用于 1 的值。每个号码的简单解决方案是if len(set(values)) == 1:
  • 为什么是x==1?骰子的值可以从 1 到 6。
  • 对不起,我把它放进去测试,忘了改成列表值。
  • 把它改成all(x == allDice[0] for x in allDice[1:])
  • 我刚开始工作,回家后会测试这个。谢谢!
【解决方案2】:

while True:... 替换为while boolean_variable: ...,并将boolean_variable 的值设置为True,在while 循环之前设置为False,当您在if 条件中实现Yahtzee => 时。

但是,10 秒计时器是什么意思?内部while 循环结束时的time.sleep(10) 可以实现十秒的休眠时间。

编辑boolean_variable 示例

import time
...
not_yahtzee = True
while not_yathzee:
    ....
    if sum == 5 or sum == 10 or ... :
        ...
        not_yahtzee = False
    else:
        ...
        time.sleep(10)

... 代表您已有的代码。正如对您的问题所评论的那样,if 条件应该看起来更像这个条件。 There are other ways on how to check all the elements in a list are the same.

【讨论】:

  • 我还是新手。如何使用 boolean_variable?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-19
  • 1970-01-01
  • 2013-04-08
  • 2014-12-14
  • 1970-01-01
  • 1970-01-01
  • 2015-12-11
相关资源
最近更新 更多