MCPcopy Create free account
hub / github.com/asweigart/PythonStdioGames

github.com/asweigart/PythonStdioGames @main

Chat with this repo
repository ↗ · DeepWiki ↗ · + Follow
729 symbols 2,074 edges 220 files ⚖ custom 255 documented · 35% updated 20mo ago★ 97310 open issues

Browse by type

Functions 712 Types & classes 17
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

PythonStdioGames

A collection of Python 3 source code for simple, text-based games & simulations to use as example programs.

INSTALL: pip install --user gamesbyexample

(Use pip3 on macOS and Linux.)

RUN LAUNCHER: python -m gamesbyexample

I'm not accepting pull requests currently, but feel free to leave comments or send suggestions to al@inventwithpython.com

If you need help installing Python, visit https://installpython3.com/

I Just Found This Web Page, How Do I Play These Games?

First, install the Python interpreter. This comes with the barebones IDLE editor. There are other editors you can use. On Windows, you can also use the Visual Studio Code editor. PyCharm Community Edition is an editor for Windows, Linux, and macOS. You can also use a browser-based editor like REPL.it. These are all free.

Then, click in the src and gamesbyexample folders in this repo to find the .py files of various Python games. For example, this is the code for snailrace.py. The code for each game its entirely in one .py file, so you can copy the code directly into your editor. I recommend typing it in by hand, rather than using copy-paste. This will give you "muscle memory" of each part of the code. (Though some of these games require you download a data file into the same folder as your .py file.) Then you can run the program. If you get error messages, note the line number in the error message and check for typos you've made.

After learning basic syntax, many programmers want to move on to the next step and see how these programming concepts are used in "real" programs. Most open source projects are far too large and complicated. These games have been designed to be short, simple, and fun. You can use them as learning examples to see how to make your own programs.

Note that some programs require you to download an extra file from this repo. For example, the [sudoku.py](https://github.com/asweigart/PythonStdioGames/blob/master/src/gamesbyexample/sudoku.py) game loads its puzzles from the [sudokupuzzles.txt](https://github.com/asweigart/PythonStdioGames/blob/master/src/gamesbyexample/sudokupuzzles.txt) file.

About this Collection

After beginners learn the syntax of Python and basic programming concepts (loops, branching, functions, etc.) they often hit a dead-end: "How do I become better at programming?" At this point, people will tell them to work on their own practice projects (which leaves them without guidance on what to make and how to make it) or to contribute to open source projects (which can be difficult to find, understand its code base, and get guidance on how to contribute).

What helped me learn to code was finding small projects whose source code I copied and then made small adjustments to. This gave me insight on how loops, branching, and functions combined together into actual programs.

To help others down the same path, I'm creating a collection of example programs aimed at being easy to copy and understand by beginners. These programs (mostly games) have the following constraints:

  • They're short, with a limit of 256 lines of code. This makes them easy to read and understand in one sitting. The shorter the better. The "256" number was arbitrarily selected, but this also means programs will fit on 4 or 5 printed pages.
  • They fit into a single source code file and have no installer. This makes these games trivial to share by copy/pasting code to a pastebin site. Data/image/save files can be used, but the source should link to some examples in their comments.
  • They only use the Python standard library. Fewer things to install means wider compatibility and less chance of failing during environment setup.
  • They only use stdio text; print() and input() in Python. The output being in the same text medium as the text source code makes it less abstract, and easier to see the cause-effect relationship between code and output. This means there's no graphics or mouse input, but makes it simple to port these programs to other languages since they all support stdio text.
  • They're necessarily turn-based. Relying on input() means the program must wait for the user to enter text, but this means we can't have real-time programs that respond to single key-presses.
  • They're well commented. Comments should be aimed at beginners and will be more verbose. The 256-line limit includes comments and whitespace. If the program is too long to include abundant comments and sensible whitespace, the program should be simplified, not the comments.
  • They use as few programming concepts as possible. If classes, list comprehensions, recursion, aren't necessary for the program, then they are't used.
  • Elegant and efficient code is worthless next to code that is easy to understand and readable. These programs are for education, not production. Standard best practices, like not using global variables, can be ignored to make it easier to understand.
  • They do input validation and are bug free. It should be impossible to crash a program with bad input or an edge case.
  • All functions have docstrings. This is good documentation practice, but also enables the help() function to work in the interactive shell.

Additional Guidelines

Additional guidelines include:

  • Don't use f-strings. Raspberry Pis as of 2019 have Python 3.5 installed, and f-strings only came about in 3.6. One guideline for these programs is to be as widely compatible as possible.
  • Some of these programs use the bext module, which adds curses-like features like color, clearing the screen, and moving the cursor
  • Include a link to a run-through of the program on https://pythontutor.com so that the student can see how the program runs.
  • Longer, more descriptive variable names are better than shorter ones. Avoid using single-letter variable names except for i and j, or x and y.
  • Have comments marked as # (!) that describe minor changes that they can make (increasing health, changing difficulty, etc.)
  • Use jsdifflib to create online diffs. This is an easy way for students to find their own typos when copying the code. An example is here: https://inventwithpython.com/invent4thed/diff/
  • Use assert statements to catch common typos the student makes when typing in the code, especially for constants that they may modify.
  • Use Python 3. The only time Python 2 is appropriate to use is when there's a large existing codebase. But this is for new programmers working on greenfield projects.
  • Stick to characters in WGL4 character repertoire, which is basically CP 1252, code pages for Cyrillic/Greek/Turkish/Baltic characters, and the MS-DOS era CP437 "extended ASCII" encoding. Windows' command line is the limiting factor here; it can't display all UTF-8 characters.
  • The source code must be typeable. Don't put box-drawing or extended ascii characters directly into the source code, but rather make chr() calls instead to acquire these characters.
  • Time can be a factor, even if the programs aren't real-time. You can check for time or add pauses in between calls to input(), but note that you'll never be able to interrupt when the user is typing.
  • The pyperclip module can be used to interact with the clipboard. Large amounts of text can be input-ed into or output-ed from the program using the clipboard.
  • I use %s string interpolation instead of f-strings. I love f-strings, but they were only introduced in Python 3.6 and I don't want to limit the versions that these programs are compatible with.
  • For all dictionaries, I have a short comment explaining what types the keys and values are. For example, # Keys=places, values=strings of the suspect & item there.
  • Use the "DOS box-drawing" characters to draw complicated board games. Though sticking to +, -, and | for lines is good too since it's simpler.
  • Player vs player games can often be simpler and shorter than player vs computer games. This necessarily means that multiplayer games must be "perfect information" games since both players can view the screen.
  • Don't modify mutable objects (e.g. lists) in functions to pass information into/out of the function; only use parameters and return values. This can make your program seem magical to someone not familiar with the Python Data Model.
  • Avoid insulting the player when they lose. This is something I learned from instructing programming classes for kids. They respond poorly to messages like, "Game Over, Dummy!" even if they seem innocuous to adults.

After making several of these programs, I've notice various "categories" of program complexity. Programs can be of zero or more of these categories:

  • Absolute beginner level. No functions, no nested data structures, avoid nested loops. Just uses simple branching and loops.
  • Choose-your-own-adventure level. Programs don't model things with data structures, but rather mostly use flow control.
  • STDIO-only. You can't undo things that have been previously printed (aside from "printing" backspace characters to erase characters on the current line). The output is like an append-only log file.
  • Curses-like. Requires the bext module, but can clear/refresh the screen, draw at arbitrary places on the screen in color, etc.
  • Modify source code to run. Instead of getting input from input(), the user edits variables at the top of the file to change the settings in the program.

Additional modules I recommend using:

  • bext for colorful text and controlling the positioning of the text cursor.
  • blessings for a better version of curses.
  • pyperclip for copying/pasting text with the clipboard.
  • playsound for playing audio files.
  • pyttsx3 for text to speech.
  • pytextcavas for 2D strings you can draw on
  • pyrect for rectangle data structure
  • pybresenham for various line-drawing functions

Completed Programs in This Collection

Alphabetize Quiz - A time-based quiz game to see how fast you can alphabetize letters.

Alphabetize Word Quiz - A time-based quiz game to see how fast you can alphabetize words.

Analog Clock - An analog clock animation. Press Ctrl-C to stop.

Bagels - A deductive logic game where you must guess a number based on clues.

Birthday Paradox Simulation - Explore the mathematics of the "Birthday Paradox". More info at https://en.wikipedia.org/wiki/Birthday_problem

Blackjack - A card game also known as 21. More info at: https://en.wikipedia.org/wiki/Blackjack

Bouncing Ball - A bouncing ball animation. Press Ctrl-C to stop.

Bouncing Lines - A bouncing line animation. Press Ctrl-C to stop.

Calendar Maker - Create monthly calendars, saved to a text file and fit for printing.

Chance Checkers - Checkers, but you can move 3 random checkers per turn. These checkers are randomly decided, and can be the player's own checkers or their opponents', but you can't move your opponents' promoted checkers. In this version, capturing is not mandatory.

Daleks - Try to get the robots to crash into each other.

Checkers - The classic checkers board game. In this version, capturing is not mandatory.

Chomp - A dangerously delicious logic game. Inspired by a Frederik Schuh and David Gale puzzle, published by Martin Gardner in Scientific American (January 1973) More info at: https://en.wikipedia.org/wiki/Chomp

Clickbait Headline Generator - A clickbait headline generator for your soulless content farm.

Coin Flip Simulator - Simulate a large number of coin flips.

Collatz Sequence - Generates numbers for the Collatz sequence, given a starting number.

Collatz Sequence Stats - Finds out how long various Collatz Sequences are.

Connect Four - A board game to get four tiles in a row.

Conway's Game of Life - The classic cellular automata simulation. Press Ctrl-C to stop. More info at: https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life

Conway's Game of Life (Terminal) - The classic cellular automata simulation. Press Ctrl-C to stop. More info at: https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life

Countdown - Show a countdown timer animation using a seven-segment display. Press Ctrl-C to stop. More info at https://en.wikipedia.org/wiki/Seven-segment_display Requires our sevseg.py program.

Diagonal Maze - Prints out a random, diagonal maze. Inspired by the 10 PRINT CHR$(205.5+RND(1)); : GOTO 10 program.

Dice Roller - Simulates dice rolls using the Dungeons & Dragons notation.

Digital Clock - Display a digital clock of the current time with a seven-segment display. Press Ctrl-C to stop. More info at https://en.wikipedia.org/wiki/Seven-segment_display Requires our sevseg.py program.

DNA - A simple animation of a DNA double-helix. Press Ctrl-C to stop. Thanks to matoken for inspiration: https://asciinema.org/a/155441

Eeny-Meeny-Miny-Moe - An elimination game for multiple players. Press Ctrl-C to stop. More info at https://en.wikipedia.org/wiki/Eeny,_meeny,_miny,_moe More info at https://en.wikipedia.org/wiki/Josephus_problem

Etch a Sketch - Draw a trailing line on the screen.

Factorization - Find all the factors of a number.

Fireflies - A beautiful animation of fireflies. Press Ctrl-C to stop.

Fish Tank - A peaceful animation of a fish tank. Press Ctrl-C to stop.

FizzBuzz Calculation - Calculates the answers for the fizz buzz programming problem.

FizzBuzz Game - A number game where you also race against the clock.

Flippy (a Reversi clone) - (Requires Pygame) Play against the computer and try to flip their tiles.

Flood Fill - An example of a "flood fill" algorithm. This is a basic demo o

Core symbols most depended-on inside this repo

browse all functions →

Shape

Function 653
Method 59
Class 17

Languages

Python95%
TypeScript5%
C#1%

Modules by API surface

src/gamesbyexample/pygame_games/tetrominoforidiots.py21 symbols
src/gamesbyexample/pygame_games/tetromino.py21 symbols
src/gamesbyexample/pygame_games/pentomino.py21 symbols
src/gamesbyexample/pygame_games/gemgem.py19 symbols
src/gamesbyexample/pygame_games/flippy.py19 symbols
src/gamesbyexample/zombiebitefight.py17 symbols
src/gamesbyexample/pygame_games/slidepuzzle.py16 symbols
src/gamesbyexample/pygame_games/memorypuzzle.py16 symbols
src/gamesbyexample/pygame_games/inkspill.py15 symbols
src/gamesbyexample/pygame_games/fourinarow.py14 symbols
src/gamesbyexample/tictactoeoop.py12 symbols
src/gamesbyexample/slitheringsnakes.py12 symbols

For agents

$ claude mcp add PythonStdioGames \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page