Search code examples
pythonfunctionloopswhile-loopdice

Python Loops - Determining Box Cars with Dice


I need to write a program that will figure how many rolls it takes to roll Box Cars (6+6).

I'm stumbling with the roll counter. I cannot get the function to loop through the counter and return the roll count to the main program. This is what I have so far.

import random

roundCounter = 0
rollCounter = 0


def roll(die1,die2):
    nRolls = 0    
    print(die1, die2) # for testing purpose only
    while True:
        nRolls += 1
        if die1 == 6 and die2 == 6:
            break
        return nRolls

while True:
    roundCounter += 1
    die1 = random.randrange(1, 7)
    die2 = random.randrange(1, 7)
    roll(die1,die2)

    print('Round #', roundCounter, 'took', rollCounter, 'rolls')


    roll_again = input('Press Enter to go again, or q to quit:')
    if roll_again == 'q':
        break

I am able to output the round counter. An example is below.

3 6
Round # 1 took 0 rolls
Press Enter to go again, or q to quit:
5 4
Round # 2 took 0 rolls
Press Enter to go again, or q to quit:
4 6
Round # 3 took 0 rolls
Press Enter to go again, or q to quit:
6 5
Round # 4 took 0 rolls
Press Enter to go again, or q to quit:
5 5
Round # 5 took 0 rolls
Press Enter to go again, or q to quit:
3 2
Round # 6 took 0 rolls
Press Enter to go again, or q to quit:
6 4
Round # 7 took 0 rolls
Press Enter to go again, or q to quit:

Any thoughts on what I'm missing?


Solution

  • You have two fatal problems in your function's loop:

    while True:
        nRolls += 1
        if die1 == 6 and die2 == 6:
            break
        return nRolls
    

    The first is that you return on the first lop iteration, rather than waiting for boxcars to appear.

    The second is that you fail to re-roll the dice; die1 and die2 are passed into the function, which effectively treats them as constants: you never change them. Unless you happened to pass in a pair of 6s, you'll hit the first return (first problem).

    You need to work through your process for doing this, as a human being, and be more careful of making your code match.