【发布时间】: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的调用。 -
当然,删除那些编号变量
dice1、dice2等会更容易。只需创建一个列表:numbers = [random.randint(1, 6) for _ in range(5)]。 -
@Matthias 谢谢!这大大缩短了我的代码哈哈
标签: python