【问题标题】:Dice Rolling Game - List to store dice rolling results掷骰子游戏 - 存储掷骰结果的列表
【发布时间】:2021-04-06 04:21:25
【问题描述】:

我正在开发掷骰子游戏,它会在两个骰子显示相同值之前打印出尝试次数 (n)。 我还想打印出过去的滚动结果。但是,我的代码只显示了最后的滚动结果(n-1 次尝试)。

我尝试用谷歌搜索并检查 stackoverflow 骰子滚动查询的过去历史,但我仍然无法弄清楚如何解决代码。请帮忙,我认为这与嵌套列表或字典有关,但我就是想不通。

下面是我的代码:

from random import randint

stop = 0
count = 0
record = []

while stop == 0:
    roll = [(dice1, dice2) for i in range(count)]
    dice1 = randint(1,6)
    dice2 = randint(1,6)
    if dice1 != dice2:
        count += 1
    else:
        stop += 1
    
record.append(roll)

if count == 0 and stop == 1:
    print("You roll same number for both dice at first try!")
else:
    print(f"You roll same number for both dice after {count+1} attempts.") 

print("The past record of dice rolling as below: ")
print(record)

【问题讨论】:

    标签: python python-3.x list dictionary dice


    【解决方案1】:

    您的代码中有一些错误。首先,我不完全确定是什么

    roll = [(dice1, dice2) for i in range(count)]
    

    line 正在为你服务。

    不过,您可以进行一些简单的更改。

    首先 - 您的 record.append(...) 行在您的循环之外。这就是为什么您只看到上一次运行的原因。它只记录一次运行。

    其次,当您满足匹配条件时,您的while 语句可以是一个简单的while True:,其中包含break。您不需要 stop 变量。

    from random import randint
    
    count = 0
    record = []
    
    while True:
        dice1 = randint(1,6)
        dice2 = randint(1,6)
        record.append([dice1,dice2])
        if dice1 != dice2:
            count += 1
        else:
            break
    
    
    if count == 0:
        print("You roll same number for both dice at first try!")
    else:
        print(f"You roll same number for both dice after {count+1} attempts.")
    
    print("The past record of dice rolling as below: ")
    print(record)
    

    类似这样的输出:

    You roll same number for both dice after 8 attempts.
    The past record of dice rolling as below: 
    [[1, 6], [2, 1], [1, 6], [5, 6], [5, 3], [6, 3], [6, 5], [4, 4]]
    

    请注意,我已将 .append(...) 带入您的 while 循环。正如我所描述的,我还围绕stop 变量进行了更改。

    【讨论】:

    • 非常感谢您在编码改进方面提供的解决方案和建议。祝你有美好的一天。
    【解决方案2】:

    我会做类似于@TeleNoob 的事情。只需使用while True: 并在满足条件时中断。

    这是我的返工:

    from random import randint
    
    roll = 0
    die1_record = []
    die2_record = []
    
    while True:
        die1 = randint(1,6)
        die2 = randint(1,6)
        die1_record.append(die1)
        die2_record.append(die2)
        
        roll += 1
        if die1 == die2:
            break
    
    print(f"You rolled same number for both dice after {roll} attempt(s).") 
    print("The past record of dice rolling is: ")
    print(f"die1: {die1_record}")
    print(f"die2: {die2_record}")
    

    【讨论】:

      猜你喜欢
      • 2012-02-29
      • 2015-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多