掷骰子游戏 - 存储掷骰子结果的列表

Dice Rolling Game - List to store dice rolling results

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

我已经尝试 google 并检查了 Whosebug 骰子滚动查询的过去历史,但我仍然无法弄清楚如何解决代码。请帮助,我认为它与嵌套列表或字典有关,但我无法弄清楚。

下面是我的代码:

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)

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

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

专线为您效劳。

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

首先 - 您的 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 变量进行了更改。

我会做类似于@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}")