Home > other >  How do I stop this code dice game at y>4?
How do I stop this code dice game at y>4?

Time:12-07

The given question is:

"You can roll a dice up to six times. You can stop when you want and you get the dollar amount shown on that roll. For example, Max rolls a 2, 4, 3, 6, and decides to stop. He wins $6. Hans rolls a 3, 2, 4, 5 and stops. David wins $5. Let’s assume you keep rolling until you get a 4 or greater, then you stop. How much would you typically win on each play? What happens if the maximum possible rolls are reduced from 6 to 4?"

The code I've written is:

import random

rounds = 0
#x = [1,2,3,4,5,6]
#y = 0

while rounds < 6:
    rounds =  rounds   1
    max_rolls = 1

    while max_rolls < 6 :
        #x_trial = (random.choice(x))
        x_trial = random.randint(1,6)


        if x_trial < 4:
        #if x_trial < 4  :
            max_rolls = max_rolls   1
            #y = 0
            #max_rolls = 1
        else :
            y = x_trial
            break


    print ("Round number:", rounds)
    print("Times rolled:", max_rolls)
    print("Your score:", y)
    print ("Your prize:", y);

The output I get is:

Round number: 1
Times rolled: 1
Your score: 5
Your prize: 5
Round number: 2
Times rolled: 2
Your score: 6
Your prize: 6
Round number: 3
Times rolled: 1
Your score: 4
Your prize: 4
Round number: 4
Times rolled: 1
Your score: 6
Your prize: 6
Round number: 5
Times rolled: 3
Your score: 6
Your prize: 6
Round number: 6
Times rolled: 1
Your score: 5
Your prize: 5

What I want to do:

I want the code to stop if y > 4. I don't want it to run for 6 rounds. I want it to stop in the round when y > 4.

CodePudding user response:

First of all, import sys at the begining of your script, then insert the following code after the first while statement:

if y > 4:

sys.exit()

CodePudding user response:

Your logic looks off. The first thing I notice is that you have two nested loops. You break from the inner one, but the outer one still goes to completion. That's why you're not breaking when you want to.

I don't think that you need a nested loop at all, unless you want an outer loop for different players, or to allow someone to enter the maximum number of rolls.

Also, choose your variable names wisely. You've got a variable named max_rolls, which you set to 1 and then increment. With that name, I expected it to be set to either 4 or 6, and I would expect another variable named roll_count or something like that to get set to 1 (or 0) and then incremented, and compared to max_rolls. Do you see how choosing such names makes your code more readable?

Lastly, Python has a short-hand convention for incrementing a counter. Rather than saying var = var 1, you can say var = 1. It's shorter and more direct, making the code a little more readable.

  • Related