简体   繁体   English

Python Dice Rolling游戏-如何检查单独的骰子并添加总数

[英]Python Dice Rolling game - How to check separate rolls and add total

Hi guys I am in the midst of creating a dice in game in python. 嗨,大家好,我正在用python创建骰子。 Below is my working code. 下面是我的工作代码。 So far if a player were to roll the dice one time, I can easily check if the rolled number is 1, however how can I make it so that if I want to roll lets say 10 times, I want to be able to check if any of those 10 rolls, any of them equaled 1, and then stop it, if none equaled 1, I would add them all up. 到目前为止,如果一个玩家掷骰子一次,我可以很容易地检查掷骰数是否为1,但是我如何做到这一点,以便如果我想掷骰子说10次,我希望能够检查这10个卷中的任何一个都等于1,然后停止它,如果没有一个等于1,我将它们全部加起来。 Basically How do I check the result of each seperate roll, and adding them up if a 1 is not rolled. 基本上,我如何检查每个单独滚动的结果,如果没有滚动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()

Just add a variable to hold the rolled number and check if it is 1, then break out of the loop if it is 只需添加一个变量来保存滚动数并检查它是否为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()

Another approach: 另一种方法:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM