Legends ofPythos
Claim your name
Writing Real Programs

Brokk, the Forge-Giant

The last fight of this track

Boss · level 13

Brokk

the Forge-Giant

Health4 of 4 stages standing
The Iron Pass is the only road through the mountains, and Brokk has shut it. He and his brother forged Thor's hammer to win a wager with Loki, and Loki cheated him anyway. Now Brokk trusts no one. He guards the pass from inside the Forge-Giant, an iron war-machine that runs on the runes chalked on his slate. Your code is your weapon. Every stage you win lands a blow; every run that fails brings its iron fist down.

The fight

Four stages, each building on the last. Every stage opens with a finished version of the code from the stage before, so you pick up where you left off. This fight draws on match, keyword-only parameters, closures, your own exceptions, files and dates.
Stage 1: The slate. Read his slate and see every move coming.
Stage 2: The hold. Keep a tally of every bolt it forges and hurls.
Stage 3: The ledger. Read his records, and keep your own.
Stage 4: The missing plate. Work out how long the gap in its armour stays open.

The fight

0 of 4 stages won

Stage 1 of 4

+60 XP
The Forge-Giant does nothing that isn't chalked on Brokk's slate: forge <item> <qty>, hurl <item> <qty> or stock. Read his slate and it can't surprise you. Define an exception class UnknownOrder with a docstring, then write parse(line), which splits the line into words and uses match to return a tuple: 'forge bolts 3' gives ('forge', 'bolts', 3), 'hurl spikes 12' gives ('hurl', 'spikes', 12) and 'stock' gives ('stock',). Anything else, including a quantity that is not all digits, raises UnknownOrder with the whole line in its message. The caught helper at the top is for the tests.
def caught(action):
    """Brokk's tongs: run action and hand back the exception it raised, or None.
    The tests use this; leave it as it is."""
    try:
        action()
    except Exception as error:
        return error
    return None




class UnknownOrder(Exception):
    # Give the class a docstring
    pass




def parse(line):
    # match on the words of the line and return a tuple, or raise UnknownOrder
    pass

Run your code to check it against the tests.

Stage 2 of 4

+60 XP
Everything the machine hurls comes out of its hold, so keep a tally. Keep stage 1 and write make_tally(*, strict=True), a factory that starts a fresh tally of the hold and returns a function run(line) that reads one order from the slate and updates your tally. Each tally keeps its own stock dictionary in the enclosing function. run returns a string: forging adds to the stock and returns f'Forged {qty} {item}'; hurling takes from it and returns f'Hurled {qty} {item}'; stock returns the hold as item=qty pairs sorted by item and joined with ', ', or 'empty' when the hold is empty. An item whose count reaches 0 is removed. If an order asks the machine to hurl more than the hold has, that's a bluff: when strict is true, raise ValueError and leave the hold as it was; when it is false, the machine hurls only what it has, and the message gives that number ('hurl bolts 5' with 2 in the hold returns 'Hurled 2 bolts'). strict can only be given by keyword.
def caught(action):
    """Brokk's tongs: run action and hand back the exception it raised, or None.
    The tests use this; leave it as it is."""
    try:
        action()
    except Exception as error:
        return error
    return None




class UnknownOrder(Exception):
    """Not one of Brokk's orders."""




def parse(line):
    match line.split():
        case ['forge', item, qty] if qty.isdigit():
            return ('forge', item, int(qty))
        case ['hurl', item, qty] if qty.isdigit():
            return ('hurl', item, int(qty))
        case ['stock']:
            return ('stock',)
        case _:
            raise UnknownOrder(f'Not an order: {line}')




def make_tally(*, strict=True):
    # Keep a stock dictionary here, define run(line) inside, and return run
    pass

Run your code to check it against the tests.

Stage 3 of 4

+60 XP
Brokk writes the machine's hold into a ledger file, one item,qty line per item. Read it and you know everything the machine holds, even what you didn't see forged; write your own tally down and you never lose track. Keep everything, define an exception class CorruptLedger, and write save(stock, path), which writes the stock dictionary to the file with its lines sorted by item, and load(path), which reads it back into a dictionary with whole-number quantities. A missing file loads as {}. A line that cannot be read, because it does not have exactly one comma or its quantity is not a whole number, raises CorruptLedger with the message f'line {number}: {line}' (lines count from 1), chained from the original error with raise ... from. The chalk helper is for the tests.
def caught(action):
    """Brokk's tongs: run action and hand back the exception it raised, or None.
    The tests use this; leave it as it is."""
    try:
        action()
    except Exception as error:
        return error
    return None




class UnknownOrder(Exception):
    """Not one of Brokk's orders."""




def parse(line):
    match line.split():
        case ['forge', item, qty] if qty.isdigit():
            return ('forge', item, int(qty))
        case ['hurl', item, qty] if qty.isdigit():
            return ('hurl', item, int(qty))
        case ['stock']:
            return ('stock',)
        case _:
            raise UnknownOrder(f'Not an order: {line}')




def make_tally(*, strict=True):
    stock = {}


    def run(line):
        match parse(line):
            case ('forge', item, qty):
                stock[item] = stock.get(item, 0) + qty
                return f'Forged {qty} {item}'
            case ('hurl', item, qty):
                have = stock.get(item, 0)

Run your code to check it against the tests.

Stage 4 of 4

+60 XP
One plate is missing from the Forge-Giant's armour, right over its furnace, and the dwarves in the forge-wall are beating out a new one. Until it's ready, the furnace is open to your blow. Keep everything and write ready_on(start, days). It takes the day the plate goes on the anvil, as an ISO date string such as '2026-09-18', and the number of days of work it needs, and returns the day the plate is ready, as an ISO date string. The forge rests on Sundays. Start from start and step forward one day at a time with timedelta: the start day itself doesn't count, and every day after it counts except Sunday (weekday() is 6), so Saturdays count. With days at 0, the answer is start. date.fromisoformat() turns the string into a date, and a date's .isoformat() turns it back. For example, ready_on('2026-09-18', 2) is '2026-09-21': Saturday the 19th counts, Sunday the 20th doesn't.
def caught(action):
    """Brokk's tongs: run action and hand back the exception it raised, or None.
    The tests use this; leave it as it is."""
    try:
        action()
    except Exception as error:
        return error
    return None




class UnknownOrder(Exception):
    """Not one of Brokk's orders."""




def parse(line):
    match line.split():
        case ['forge', item, qty] if qty.isdigit():
            return ('forge', item, int(qty))
        case ['hurl', item, qty] if qty.isdigit():
            return ('hurl', item, int(qty))
        case ['stock']:
            return ('stock',)
        case _:
            raise UnknownOrder(f'Not an order: {line}')




def make_tally(*, strict=True):
    stock = {}


    def run(line):
        match parse(line):
            case ('forge', item, qty):
                stock[item] = stock.get(item, 0) + qty
                return f'Forged {qty} {item}'
            case ('hurl', item, qty):
                have = stock.get(item, 0)

Run your code to check it against the tests.