Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

python - Dice Rolling Game - List to store dice rolling results

I am working on dice rolling game which prints out the number of attempts (n) before both dice shows the same value. I would like to also print out the past rolling results. However, my code only shows the last rolling results (n-1 attempts).

I have tried to google and check the past history of stackoverflow dice rolling queries and I still can't figure out how to solve the code. Please help, I think it has got to do with nested list or dictionaries, but I just can't figure it out.

Below is my code:

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have a few mistakes in your code. The first, is that I'm not entirely sure what the

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

line is doing for you.

You can make a few simple changes though.

First - your record.append(...) line is outside of your loop. That is why you only see the previous run. It's only recording one run.

Second, your while statement can be a simple while True: with a break in it when you meet your matching condition. You don't need the stop variable.

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)

With output similar to this:

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]]

Notice that I've brought the .append(...) into your while loop. I've also made the changes around the stop variable as I described.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...