Code

Side Quest: Replay the Race

Games with dice are hard to debug, because every run is different. If something strange happens on turn 5, how do you see it again? Use a seed: same seed, same rolls, same game. Every time.

Keep the generator local

random.seed(7) resets the shared generator that every random.randint(...) call uses. That works until some other code also rolls a die. Then your numbers shift and the replay breaks.

A local random.Random(seed) belongs to your function alone:

import random

def roll_three(seed):
    rng = random.Random(seed)   # this function's own dice
    rolls = []
    for _ in range(3):
        rolls.append(rng.randint(1, 6))
    return rolls

roll_three(4) == roll_three(4)   # True, every time

Make a new generator at the start of each simulation, so the same seed always starts the same story.

Order matters

A seed fixes the sequence of numbers, not who gets them. If Moss rolls before Pip, both get different numbers. A replay must make the same calls in the same order.

Assignment

Pip and Moss race along the Shell Shore. Both start at 0.

  1. race(seed, turns): make one random.Random(seed). Each turn, Pip rolls rng.randint(1, 6) first, then Moss rolls. Add each roll to that racer's position. Return a list with one (pip, moss) tuple per turn.
  2. winner(seed, turns): call race(seed, turns) and look at the last positions. Return "Pip", "Moss" or "tie". You can assume turns is at least 1.
  3. Don't use the shared functions such as random.randint or random.seed.