race()

Racing function for CLI Pets.

race(distance=50, racers=3, pets=None, speed=0.1, show_winner=True)

Race pets across the terminal.

Parameters:

Name Type Description Default
distance int

Length of the race track (default: 50)

50
racers int

Number of racing pets (default: 3)

3
pets list[str] | None

Specific pets to race; if None, random pets are chosen (default: None)

None
speed float

Seconds between updates (default: 0.1)

0.1
show_winner bool

Whether to announce the winner (default: True)

True
Source code in src\cli_pets\race.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def race(
    distance: int = 50,
    racers: int = 3,
    pets: list[str] | None = None,
    speed: float = 0.1,
    show_winner: bool = True,
) -> None:
    """Race pets across the terminal.

    Args:
        distance: Length of the race track (default: 50)
        racers: Number of racing pets (default: 3)
        pets: Specific pets to race; if None, random pets are chosen (default: None)
        speed: Seconds between updates (default: 0.1)
        show_winner: Whether to announce the winner (default: True)
    """
    ### Setup ----
    if pets is None:
        pets = random.sample(PETS, min(racers, len(PETS)))
    else:
        pets = pets[:racers]  # Limit to number of racers

    positions = [0] * len(pets)

    ### Race Loop ----
    with Live(console=console, refresh_per_second=10) as live:
        while max(positions) < distance:
            # Update positions randomly
            for i in range(len(positions)):
                positions[i] += random.randint(0, 2)

            # Render race
            display = Text()
            for i, pet in enumerate(pets):
                pos = min(positions[i], distance)
                line = " " * pos + pet + "\n"
                display.append(line)

            live.update(display)
            time.sleep(speed)

    ### Declare Winner ----
    if show_winner and len(pets) > 1:
        winner_idx = positions.index(max(positions))
        console.print(f"\n[bold yellow]🏆 {pets[winner_idx]} wins![/bold yellow]")