[英]Python Dice Rolling game - How to check separate rolls and add total
嗨,大家好,我正在用python创建骰子。 下面是我的工作代码。 到目前为止,如果一个玩家掷骰子一次,我可以很容易地检查掷骰数是否为1,但是我如何做到这一点,以便如果我想掷骰子说10次,我希望能够检查这10个卷中的任何一个都等于1,然后停止它,如果没有一个等于1,我将它们全部加起来。 基本上,我如何检查每个单独滚动的结果,如果没有滚动1,将它们加起来。
import random
import sys
def rollingdice(roll): #define function
total = 0 #starting count
for i in range(roll):
total+= random.randint(1, 6)
if total == 1:
print("You rolled a 1: You have zero points for the round")
else:
print(total)
main()
def main():
roll=int(input("Player 1: How many times will you roll "))
rollingdice(roll)
main()
只需添加一个变量来保存滚动数并检查它是否为1,然后如果是则跳出循环
def rollingdice(roll): #define function
total = 0 #starting count
for i in range(roll):
rolled = random.randint(1, 6)
if rolled == 1:
print("You rolled a 1: You have zero points for the round")
break
total += rolled
if rolled != 1: print(total)
main()
另一种方法:
from itertools import takewhile
import random
def rollingdice(roll):
rolls = (random.randint(1, 6) for i in range(roll))
rolls = list(takewhile(lambda n: n != 1, rolls))
if len(rolls) == roll:
print(total)
else:
print("You rolled a 1: You have zero points for the round")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.