Python掷骰子游戏如何检查分掷和添加

2024-10-03 13:21:31 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,伙计们,我正在用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()

Tags: 代码importyou游戏formaindef玩家
2条回答

只需添加一个变量来保存滚动的数字,并检查它是否为1,如果是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")

相关问题 更多 >