[英]Dice Rolling Game - List to store dice rolling results
我正在研究掷骰子游戏,它会在两个骰子显示相同值之前打印出尝试次数(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)
您的代码中有一些错误。 首先,我不完全确定
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)
与 output 类似:
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}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.