[英]How to implement a Loop statement
我制作了一个简单的Yahtzee游戏,但我想的尽可能少。 当前,用户必须按Enter键(使用任何值)才能继续。 我想使用循环语句,使骰子继续滚动直到Yahtzee(所有滚动的数字都相同)。 我还要一个10秒的计时器。 向此代码添加循环语句的最佳方法是什么? PS:这不是功课,我想在Yahtzee晚上做这个游戏。 我的女儿醒了easil ...哈哈
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)
将while True:...
替换为while boolean_variable: ...
并在while
循环之前将该boolean_variable
的值设置为True
,并在if
条件下实现Yahtzee =>时将其设置为False
。
但是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
条件应该更像是这个条件。 还有其他方法可以检查列表中的所有元素是否相同 。
如果您想检查所有骰子号是否相同,就这么简单。
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并停止循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.