Exercise: Game Night Toolkit
Finish a game night package of modules, dice and scores, keep a try-out line from running on import, connect the modules with import lines, and run it all from its own virtual environment with pinned requirements.
Apprentice · Python · Updated
A group of friends plays board games every Friday, and their toolkit is a Python package, gamenight: one module rolls the dice, one keeps the scores, and a third plays a round. The files are laid out and the functions are named. You'll finish the functions, stop a try-out line from running every time a module is imported, and write the import lines that connect the modules, all inside the exercise's own virtual environment.
Get the exercise code
Open this lesson's GitHub repository, github.com/ask-codey/exercise-python-game-night-toolkit, also linked from the Exercise box beside the lesson. Clone it into your python-course folder. In VS Code's terminal:
cd ~/python-course
git clone https://github.com/ask-codey/exercise-python-game-night-toolkit.git
Git makes a folder, exercise-python-game-night-toolkit, with the exercise code inside. Open that folder in VS Code (File > Open Folder), open its terminal with Terminal > New Terminal, and make the exercise's virtual environment, then install what its requirements.txt pins. On Windows (PowerShell):
python -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt
On a Mac (zsh):
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
The prompt starts with (.venv) once the virtual environment is on, and pip's last line says it installed pytest-9.2.0, the exact version the file pins. Virtual Environments and pip explains each command, and what to do if PowerShell won't run the second one.
The folder holds:
gamenight/: the package.__init__.pymakes the folder a package;dice.pyandscores.pyhold the functions to finish;__main__.pyplays one round.tests/: the tests, which import your modules and check what each function returns, and run the package the way you would. You don't need to change them.requirements.txt,pytest.iniand.gitignore: the pinned package, where pytest finds the tests and the package, and what Git leaves out (.venv/among them).
What to do
Each function is declared with its name and parameters, and for now it stops with a NotImplementedError that says Not built yet. The docstring under each one says what it should return, with examples:
def roll_dice(rng, count, sides=6):
"""Return a list of count dice rolls, each a whole number from 1 to sides.
Roll each die with rng.randint(1, sides), one die after another, so the same
seed always gives the same list.
roll_dice(random.Random(7), 3) -> [3, 2, 4]
roll_dice(random.Random(7), 2, sides=20) -> [11, 5]
roll_dice(random.Random(7), 0) -> []
"""
raise NotImplementedError("Not built yet.")
Work through it in four steps:
gamenight/dice.py:roll_dice(rng, count, sides=6)returns a list ofcountrolls, eachrng.randint(1, sides).rngis arandom.Random, so a test can hand in dice with a fixed seed.gamenight/scores.py:add_points(scores, player, points)adds the points to the player's total in thescoresdictionary (a new player starts at 0) and returns the new total.leaderboard(scores)returns(player, points)pairs, the most points first, with players who tie in name order.gamenight/dice.pyagain:is_doubles(rolls)returnsTruewhen there are at least two dice and they all show the same number. Then fix the try-out line at the bottom of the file, which prints a test roll every time another file importsdice.py: put it underif __name__ == "__main__":, so it runs only whendice.pyis the file being run. Move it; don't delete it.gamenight/__main__.py: add the import lines where its comment says:roll_diceandis_doublesfromgamenight.dice, andadd_pointsandleaderboardfromgamenight.scores.
Check your work
Run the tests from the exercise folder, with the virtual environment on:
pytest
At first all 18 tests fail. That's expected: each step you finish turns its tests green. A failing test's message says what it called, what it expected and what came back, for example roll_dice(random.Random(7), 3) should return [3, 2, 4], but it returned [3, 2].
To play the round yourself, run the package from the exercise folder (not from inside gamenight/):
python -m gamenight
Hints
- Build the rolls with a loop that appends, or a list comprehension:
counttimes, roll one die withrng.randint(1, sides). Rolling with anything else gives different numbers from the same seed. scores.get(player, 0)gives a player's total, or 0 for a player who isn't in the dictionary yet. Dictionaries: Looking Things Up by Name shows it.- A set keeps one of each value, so with two or more dice, the rolls all match when
set(rolls)has exactly one number in it. - Sort twice for the leaderboard: sort
scores.items()by name first, then by points withreverse=True. Players who tie keep the order the first sort gave them, as Sorting with key and lambda shows. - Read the error
python -m gamenightprints: its last line names the first name Python couldn't find, and Your Own Modules and Packages shows thefrom … importline that brings a name in from a module inside a package.
When you're done
Every test is green: pytest's last line says 18 passed. And python -m gamenight prints:
Game night: round 1
Dev rolls 3 and 1: 4 points
Cleo rolls 4 and 5: 9 points
Ben rolls 4 and 5: 9 points
Ana rolls 3 and 3: doubles, 12 points
Leaderboard
1. Ana: 12
2. Ben: 9
3. Cleo: 9
4. Dev: 4
Now look at what you didn't change: the tests import your modules, and __main__.py imports them too, and neither had to copy a line of your code. If game night switched to 20-sided dice, how many files would you change?
Submit your exercise
The exercise is how you finish this lesson. When your work is done, put it on GitHub in a repo of your own, then submit that repo's address here. Hand In Your Work with Git walks through each step.
On GitHub, click +, then New repository. Name it (for example
exercise-python-game-night-toolkit), choose Public, and click Create repository. Leave out the README: your folder already has one.In VS Code's terminal, in your exercise folder, send your work to your new repo. Point your copy at your own repo, then commit and push:
git remote set-url origin https://github.com/your-name/exercise-python-game-night-toolkit.git git add . git commit -m "My solution" git push -u origin mainPaste your repo's address, such as
https://github.com/your-name/exercise-python-game-night-toolkit, into Submit your exercise on this page. The site checks that the repo is public and holds your commits, and then the lesson is complete.
Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts. Your .venv folder stays on your computer: .gitignore leaves it out, and requirements.txt is all anyone needs to make it again.
So what
Real Python projects are packages of small modules, each with one job, run from their own virtual environment with pinned requirements, and that's the shape every project from here on takes.