Editor

Board Game Turns

Advanced · Write the code · from Random Values and Simulations: RANDOM(a, b) in Python

From the lesson: Random Values and Simulations: RANDOM(a, b) in Python

A random value is a number a program cannot predict ahead of time, and simulations use random values to copy the uncertainty of the real world, from a coin toss to the way a rumor travels through a school. Games use them to shuffle cards, and weather apps use them to try out thousands of possible tomorrows.

Read the lesson

A game piece starts on square 0. Each turn it moves forward by one dice roll. If it lands exactly on square 13, it slides back to square 5. The game ends when the piece reaches square 20 or beyond.

Write turns_to_finish(rolls) that takes a list of dice results and returns how many turns the game took. If the list runs out before the piece finishes, return -1.

turns_to_finish([6, 6, 6, 6])        ->  4    (6, 12, 18, 24)
turns_to_finish([6, 6, 1, 6, 6, 6])  ->  6    (6, 12, 13 so back to 5, 11, 17, 23)

Taking the rolls as a list keeps the game rules testable. In a simulation, the list would come from random.randint(1, 6).

def turns_to_finish(rolls):
# Move the piece, slide from 13 back to 5, stop at 20 or beyond
pass

What Check runs

Your code runs first, then each of these lines, and 3 more that stay hidden. The output must match exactly.

RunsExpected output
turns_to_finish([6, 6, 6, 6])4
turns_to_finish([6, 6, 1, 6, 6, 6])6

More Simulation exercises

All Python exercises · 50 practice problems