List of 87 Programming Ideas for Beginners
Posted by Al Sweigart in misc
After you've learned the basic concepts, the best way to improve your coding skills is to work on projects. You may not know enough to contribute to popular open source projects, but you can create small programs on your own. Here's a list of 81 projects suitable for beginners. They're short, can be done in any language, and don't require additional software library installation. These projects are drawn from my free books, The Big Book of Small Python Projects, Cracking Codes with Python, and Invent Your Own Computer Games with Python. Each program has a link to a sample Python implementation, but I encourage you to make it from scratch.
What you don't want to do is start on a large, ambitious project: it's frustrating to spend weeks on something that you never actually finish. You can learn a lot by instead working on several small, simple programs. There are plenty of terrible "1001 Programming Ideas" blog posts that copy/paste every idea from "flip a coin" programs to "make your own ChatGPT". My list is carefully curated to be achievable by beginners.
More importantly, these projects can all be done with just printing text to the screen and taking keyboard input. There are no graphics, GUIs, or web servers you need to set up. This list has games, simulations, puzzles, and digital art programs. These programs can be written in a few dozen or few hundred lines of code. I suggest trying to write them yourself from scratch, but you can also follow the links to working Python source code for each project.
I also produce a trailer video for the projects in The Big Book of Small Python Projects if you want a quick preview tour.
Bagels | Birthday Paradox | Bitmap Message | Blackjack | Bouncing DVD Logo | Caesar Cipher | Caesar Hacker | Calendar Maker | Carrot in a Box | Cho Han | Clickbait Headline Generator | Collatz Sequence | Conway's Game of Life | Countdown | Deep Cave / Winding River | Diamonds | Dice Math | Dice Roller | Digital Clock | Digital Stream / Matrix Screensaver | DNA Visualization | Ducklings | Etching Drawer | Factor Finder | Fast Draw | Fibonacci | Fish Tank | Flooder | Forest Fire Sim | Four in a Row | Guess the Number | Gullible | Hacking Minigame | Hangman & Guillotine | Hex Grid | Hourglass | Hungry Robots | J'Accuse! | Langton's Ant | Leetspeak | Lucky Stars | Magic Fortune Ball | Mancala | Maze Runner 2D | Maze Runner 3D | Million Dice Statistics | Mondrian Art Generator | Monty Hall | Multiplication Table | Ninety Nine Bottles | niNety nniinE BoOttels | Numeral Systems | Periodic Table of the Elements | Pig Latin | Powerball Lottery | Prime Numbers | Progress Bar | Rainbow | Rock Paper Scissors | Rock Paper Scissors (Always Win Version) | ROT 13 Cipher | Rotating Cube | Royal Game of Ur | Shining Carpet | Simple Substitution Cipher | Sine Message | Sliding Tile Puzzle | Snail Race | Soroban Japanese Abacus | Sound Mimic | sPoNgEcAsE | Sudoku Puzzle | Text To Speech Talker | Three Card Monte | Tic Tac Toe | Tower of Hanoi Puzzle | Twenty Forty Eight | Vigenère Cipher | Water Bucket Puzzle | Sonar Treasure Hunt | Reversegam / Reversi / Othello | Transposition Cipher | Transposition Cipher Hacker / English Detection | Affine Cipher | Frequency Analysis / Vigenere Cipher Hacker | Public Key Cryptography / Large Prime Number Generation
Bagels
Bagels is a deductive logic game where you must guess a 3-digit number. After each guess you are given clues: "Pico" means one digit is correct but in the wrong position, "Fermi" means one digit is correct and in the right position, and "Bagels" means no digit is correct.
For example, game play could look like this:
Guess #1:
> 123
Pico
Guess #2:
> 456
Bagels
Guess #3:
> 178
Pico Pico
--snip--
Guess #7:
> 791
Fermi Fermi
Guess #8:
> 701
You got it!
Birthday Paradox
The Birthday Paradox is the surprisingly high probability that two people will have the same birthday even in a small group of people. Even in a group as small as 23 people, there’s a 50 percent chance of a matching birthday. This program performs several probability experiments to determine the percentages for groups of different sizes.
You can find out more about the Birthday Paradox at https://en.wikipedia.org/wiki/Birthday_problem.
For example, when the program runs it could look like this:
How many birthdays shall I generate? (Max 100)
> 23
Here are 23 birthdays:
Oct 9, Sep 1, May 28, Jul 29, Feb 17, Jan 8, Aug 18, Feb 19, Dec 1, Jan 22,
May 16, Sep 25, Oct 6, May 6, May 26, Oct 11, Dec 19, Jun 28, Jul 29, Dec 6,
Nov 26, Aug 18, Mar 18
In this simulation, multiple people have a birthday on Jul 29
Generating 23 random birthdays 100,000 times...
Press Enter to begin...
Let's run another 100,000 simulations.
0 simulations run...
10000 simulations run...
--snip--
90000 simulations run...
100000 simulations run.
Out of 100,000 simulations of 23 people, there was a
matching birthday in that group 50955 times. This means
that 23 people have a 50.95 % chance of
having a matching birthday in their group.
That's probably more than you would think!
Bitmap Message
The Bitmap Message replaces the non-space characters in a multiline string with your own text message. For example, this multiline string:
************** * *** ** * ******************************
********************* ** ** * * ****************************** *
** ***************** ******************************
************* ** * **** ** ************** *
********* ******* **************** * *
******** *************************** *
* * **** *** *************** ****** ** *
**** * *************** *** *** *
****** ************* ** ** *
******** ************* * ** ***
******** ******** * *** ****
********* ****** * **** ** * **
********* ****** * * *** * *
****** ***** ** ***** *
***** **** * ********
***** **** *********
**** ** ******* *
*** * *
** * *
....................................................................
...could be combined with the "message" string Hello!
to produce this string:
Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!He
lo!Hello!Hello l !He lo e llo!Hello!Hello!Hello!Hello!He
llo!Hello!Hello!Hello He lo H l !Hello!Hello!Hello!Hello!Hello H
el lo!Hello!Hello!He lo!Hello!Hello!Hello!Hello!Hel
o!Hello!Hello lo e lo!H ll !Hello!Hello!H l
!Hello!He llo!Hel Hello!Hello!Hell ! e
Hello!He ello!Hello!Hello!Hello!Hell H
l H llo! ell ello!Hello!Hell !Hello el o
lo!H l ello!Hello!Hell ell !He o
!Hello llo!Hello!Hel el He o
!Hello!H lo!Hello!Hell l !H llo
ello!Hel Hello!He H llo Hell
ello!Hell ello!H l Hell !H l o!
ello!Hell ello!H l o o!H l H
lo!Hel ello! el o!Hel H
lo!He llo! e llo!Hell
llo!H llo! llo!Hello
llo! ll lo!Hell e
llo l e
ll l H
Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!Hello!He
Blackjack
Blackjack, also known as 21, is a card game where players try to get as close to 21 points as possible without going over. The user plays against an AI blackjack dealer. (Email me if you are a VC who wants to invest in my blackjack AI. I'm in between banks right now, so make the checks out to "cash".)
For example, when the program runs it could look like this:
Money: 5000
How much do you bet? (1-5000, or QUIT)
> 400
Bet: 400
DEALER: ???
___ ___
|## | |2 |
|###| | ♥ |
|_##| |__2|
PLAYER: 17
___ ___
|K | |7 |
| ♠ | | ♦ |
|__K| |__7|
(H)it, (S)tand, (D)ouble down
> h
You drew a 4 of ♦.
--snip--
DEALER: 18
___ ___ ___
|K | |2 | |6 |
| ♦ | | ♥ | | ♠ |
|__K| |__2| |__6|
PLAYER: 21
___ ___ ___
|K | |7 | |4 |
| ♠ | | ♦ | | ♦ |
|__K| |__7| |__4|
You won $400!
--snip--
Bouncing DVD Logo
The bouncing DVD logo! If you are of a certain age, you’ll remember those ancient technological devices called DVD players. When not playing DVDs, they would display a diagonally traveling DVD logo that bounced off the edges of the screen. This program simulates this colorful DVD logo by making it change direction each time it hits an edge. We’ll also keep track of how many times a logo hits a corner of the screen. This creates an interesting visual animation to look at, especially for the magical moment when a logo lines up perfectly with a corner.
The Bext package can print directly to XY coordinates on the screen. Bext also lets you print in different colors. Otherwise, you could do the trick of printing fifty or so \n
newline characters to "clear" the screen before printing an updated screen of DVD logos.
For example, when the program runs it could look like this:
Caesar Cipher
The Caesar cipher is an ancient encryption algorithm that encrypts letters by shifting them over by a certain number of places in the alphabet. We call the length of shift the key. For example, if the key is 3, then A becomes D, B becomes E, C becomes F, and so on. To decrypt the message, you must shift the encrypted letters in the opposite direction. This program lets the user encrypt and decrypt messages according to this algorithm.
For example, when the program runs it could look like this:
Do you want to (e)ncrypt or (d)ecrypt?
> e
Please enter the key (0 to 25) to use.
> 4
Enter the message to encrypt.
> Meet me by the rose bushes tonight.
QIIX QI FC XLI VSWI FYWLIW XSRMKLX.
--snip--
Do you want to (e)ncrypt or (d)ecrypt?
> d
Please enter the key (0 to 26) to use.
> 4
Enter the message to decrypt.
> QIIX QI FC XLI VSWI FYWLIW XSRMKLX.
MEET ME BY THE ROSE BUSHES TONIGHT.
If you’d like to learn about ciphers and code breaking in general, you can read my book Cracking Codes with Python.
Caesar Hacker
This Caesar cipher hacking program can hack messages encrypted with the Caesar cipher even if you don’t know the key. There are only 26 possible keys for the Caesar cipher, so a computer can easily try all possible decryptions and display the results to the user. In cryptography, we call this technique a brute-force attack. You'll be able to reuse some of the code you wrote for the Caesar cipher program.
For example, when the program runs it could look like this:
Enter the encrypted Caesar cipher message to hack.
> QIIX QI FC XLI VSWI FYWLIW XSRMKLX.
Key #0: QIIX QI FC XLI VSWI FYWLIW XSRMKLX.
Key #1: PHHW PH EB WKH URVH EXVKHV WRQLJKW.
Key #2: OGGV OG DA VJG TQUG DWUJGU VQPKIJV.
Key #3: NFFU NF CZ UIF SPTF CVTIFT UPOJHIU.
Key #4: MEET ME BY THE ROSE BUSHES TONIGHT.
Key #5: LDDS LD AX SGD QNRD ATRGDR SNMHFGS.
Key #6: KCCR KC ZW RFC PMQC ZSQFCQ RMLGEFR.
--snip--
If you’d like to learn about ciphers and code breaking in general, you can read my book Cracking Codes with Python.
Calendar Maker
This calendar maker program generates printable text files of monthly calendars for the month and year you enter. Dates and calendars are a tricky topic in programming because there are so many different rules for determining the number of days in a month, which years are leap years, and which day of the week a particular date falls on. Fortunately, Python’s datetime
module handles these details for you. This program focuses on generating the multiline string for the monthly calendar page. Other languages also have datetime and calendar packages. Consult the documentation for your language.
Enter the year for the calendar:
> 2029
Enter the month for the calendar, 1-12:
> 12
December 2029
...Sunday.....Monday....Tuesday...Wednesday...Thursday....Friday....Saturday..
+----------+----------+----------+----------+----------+----------+----------+
|25 |26 |27 |28 |29 |30 | 1 |
| | | | | | | |
| | | | | | | |
| | | | | | | |
+----------+----------+----------+----------+----------+----------+----------+
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| | | | | | | |
| | | | | | | |
| | | | | | | |
+----------+----------+----------+----------+----------+----------+----------+
| 9 |10 |11 |12 |13 |14 |15 |
| | | | | | | |
| | | | | | | |
| | | | | | | |
+----------+----------+----------+----------+----------+----------+----------+
|16 |17 |18 |19 |20 |21 |22 |
| | | | | | | |
| | | | | | | |
| | | | | | | |
+----------+----------+----------+----------+----------+----------+----------+
|23 |24 |25 |26 |27 |28 |29 |
| | | | | | | |
| | | | | | | |
| | | | | | | |
+----------+----------+----------+----------+----------+----------+----------+
|30 |31 | 1 | 2 | 3 | 4 | 5 |
| | | | | | | |
| | | | | | | |
| | | | | | | |
+----------+----------+----------+----------+----------+----------+----------+
Saved to calendar_2029_12.txt
Carrot in a Box
Carrot in a box is a simple and silly bluffing game for two human players. Each player has a box. One box has a carrot in it, and each player wants to have the carrot. The first player looks in their box and then tells the second player they either do or don’t have the carrot. The second player gets to decide whether to swap boxes or not.
I got the idea for this from a comedy sketch by 8 Out Of 10 Cats.
You can draw boxes and carrots using text characters:
___VV____
| VV |
| VV |
|___||____| __________
/ || /| / /|
+---------+ | +---------+ |
| RED | | | GOLD | |
| BOX | / | BOX | /
+---------+/ +---------+/
Your program should:
- Ask the players for their names.
- Explain the rules and show the two closed boxes to the players.
- Ask the second player to close their eyes while the first player presses Enter to view the contents of their box, and then press Enter again to clear the screen.
- Ask the second player if they want to swap boxes or not. The second player can ask the first player any question they want.
- Reveal who has the box with the carrot in it.
For example, when the program runs it could look like this:
Human player 1, enter your name: Alice
Human player 2, enter your name: Bob
HERE ARE TWO BOXES:
__________ __________
/ /| / /|
+---------+ | +---------+ |
| RED | | | GOLD | |
| BOX | / | BOX | /
+---------+/ +---------+/
Alice Bob
Alice, you have a RED box in front of you.
Bob, you have a GOLD box in front of you.
Press Enter to continue...
--snip--
When Bob has closed their eyes, press Enter...
Alice here is the inside of your box:
___VV____
| VV |
| VV |
|___||____| __________
/ || /| / /|
+---------+ | +---------+ |
| RED | | | GOLD | |
| BOX | / | BOX | /
+---------+/ +---------+/
(carrot!)
Alice Bob
Press Enter to continue...
--snip--
Cho-Han
Cho-han is a dice game played in gambling houses of feudal Japan. Two six-sided dice are rolled in a cup, and gamblers must guess if the sum is even (cho) or odd (han). The house takes a small cut of all winnings. The simple random number generation and basic math used to determine odd or even sums make this project especially suitable for beginners.
For example, when the program runs it could look like this:
You have 5000 mon. How much do you bet? (or QUIT)
> 400
The dealer swirls the cup and you hear the rattle of dice.
The dealer slams the cup on the floor, still covering the
dice and asks for your bet.
CHO (even) or HAN (odd)?
> cho
The dealer lifts the cup to reveal:
GO - GO
5 - 5
You won! You take 800 mon.
The house collects a 40 mon fee.
--snip--
You can find more details and a sample Python implementation on the book website.
Clickbait Headline Generator
Our website needs to trick people into looking at advertisements! But coming up with creative, original content is too hard. Luckily, with the clickbait headline generator, we can make a computer come up with millions of outrageous fake headlines. They’re all low quality, but readers don’t seem to mind. This program generates as many headlines as you need from a Mad Libs–style template.
For example, when the program runs it could look like this:
Our website needs to trick people into looking at ads!
Enter the number of clickbait headlines to generate:
> 1000
Big Companies Hate Him! See How This New York Cat Invented a Cheaper Robot
What Telephone Psychics Don't Want You To Know About Avocados
You Won't Believe What This North Carolina Shovel Found in Her Workplace
--snip--
14 Reasons Why Parents Are More Interesting Than You Think (Number 1 Will Surprise You!)
What Robots Don't Want You To Know About Cats
This Florida Telephone Psychic Didn't Think Robots Would Take Her Job. She Was Wrong.
Collatz Sequence
The Collatz sequence, also called the 3n + 1 problem, is the simplest impossible math problem. (But don’t worry, the program itself is easy enough for beginners.) From a starting number, n, follow three rules to get the next number in the sequence:
- If n is even, the next number n is n / 2.
- If n is odd, the next number n is n * 3 + 1.
- If n is 1, stop. Otherwise, repeat.
It is generally thought, but so far not mathematically proven, that every starting number eventually terminates at 1. Write a program that takes a starting number from the user and prints the Collatz sequence from it.
For example, when the program runs it could look like this:
Enter a starting number (greater than 0) or QUIT:
> 26
26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1
--snip--
Enter a starting number (greater than 0) or QUIT:
> 27
27, 82, 41, 124, 62, 31, 94, 47, 142, 71, 214, 107, 322, 161, 484, 242, 121, 364, 182, 91, 274, 137, 412, 206, 103, 310, 155, 466, 233, 700, 350, 175, 526, 263, 790, 395, 1186, 593, 1780, 890, 445, 1336, 668, 334, 167, 502, 251, 754, 377, 1132, 566, 283, 850, 425, 1276, 638, 319, 958, 479, 1438, 719, 2158, 1079, 3238, 1619, 4858, 2429, 7288, 3644, 1822, 911, 2734, 1367, 4102, 2051, 6154, 3077, 9232, 4616, 2308, 1154, 577, 1732, 866, 433, 1300, 650, 325, 976, 488, 244, 122, 61, 184, 92, 46, 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1
Conway's Game of Life
Conway’s Game of Life is a cellular automata simulation that follows simple rules to create interesting patterns. It was invented by mathematician John Conway in 1970 and popularized by Martin Gardner’s “Mathematical Games” column in Scientific American. Today, it’s a favorite among programmers and computer scientists, though it’s more an interesting visualization than a true “game.” The two-dimensional board has a grid of “cells,” each of which follows three simple rules:
- Living cells with two or three neighbors stay alive in the next step of the simulation.
- Dead cells with exactly three neighbors become alive in the next step of the simulation.
- Any other cell dies or stays dead in the next step of the simulation.
Tragically, Professor Conway passed away of complications from COVID-19 in April 2020. More information about Conway’s Game of Life can be found at https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life, and more information about Martin Gardner at https://en.wikipedia.org/wiki/Martin_Gardner.
For example, when the program runs it could look like this:
Countdown
Create a digital display that counts down, using the following "font" of digits made out of underscores and pipe characters:
__ __ __ __ __ __ __ __
| | | __| __| |__| |__ |__ | |__| |__|
|__| | |__ __| | __| |__| | |__| __|
For example, when the program runs it could look like this:
__ __ __ __ __ __
| | | | * | | | | * __| |__|
|__| |__| * |__| |__| * |__ __|
Press Ctrl-C to quit.
Deep Cave / Winding River
This program is a text animation of a deep cave that descends forever into the earth, or a top-down view of a winding river. Although short, this program takes advantage of the scrolling nature of the computer screen to produce an interesting and unending visualization, proof that it doesn’t take much code to produce something fun to watch.
Your program should:
- Track how wide the left bank of the "river" is, along with the width of the "river" itself.
- Randomly increase or decrease the width of the left bank and river.
- Print the left bank using
'#'
characters and print the river using' '
space characters. - Calculate the width of the right bank and print it with
'#'
characters. - Repeat endlessly.
For example, when the program runs it could look like this:
#################### ########################################
#################### #########################################
#################### ########################################
#################### ########################################
##################### #######################################
###################### ######################################
##################### #######################################
#################### ########################################
################### #########################################
If you find this kind of animation interesting, you can find more examples of "scrolling ASCII art" on my other website, The Scroll Art Museum.
Diamonds
This program features a small algorithm for drawing ASCII-art diamonds of various sizes. It contains functions for drawing either an outline or filled-in-style diamond of the size you dictate. These functions are good practice for a beginner; try to understand the pattern behind the diamond drawings as they increase in size.
For example, when the program runs it could look like this:
/\
\/
/\
\/
/\
/ \
\ /
\/
/\
//\\
\\//
\/
/\
/ \
/ \
\ /
\ /
\/
/\
//\\
///\\\
\\\///
\\//
\/
Dice Math
This math quiz program rolls two to six dice whose sides you must add up as quickly as possible. But this program operates as more than just automated flash cards; it draws the faces of the dice to random places on the screen. The ASCII-art aspect adds a fun twist while you practice arithmetic.
For example, when the program runs it could look like this:
Add up the sides of all the dice displayed on the screen. You have
30 seconds to answer as many as possible. You get 4 points for each
correct answer and lose 1 point for each incorrect answer.
Press Enter to begin...
+-------+
| O O |
| O |
| O O |
+-------+
+-------+
+-------+ | O O | +-------+
| O | | | | O |
| | | O O | | |
| O | +-------+ | O |
+-------+ +-------+
Enter the sum: 13
Dice Roller
Dungeons & Dragons and other tabletop role-playing games use special dice that can have 4, 8, 10, 12, or even 20 sides. These games also have a specific notation for indicating which dice to roll. For example, 3d6 means rolling three six-sided dice, while 1d10+2 means rolling one ten-sided die and adding a two-point bonus to the roll. This program simulates this dice rolling, in case you forgot to bring your own. It can also simulate rolling dice that don’t physically exist, such as a 38-sided die.
For example, when the program runs it could look like this:
> 3d6
7 (3, 2, 2)
> 1d10+2
9 (7, +2)
> 2d38-1
32 (20, 13, -1)
> 100d6
364 (3, 3, 2, 4, 2, 1, 4, 2, 4, 6, 4, 5, 4, 3, 3, 3, 2, 5, 1, 5, 6, 6, 6, 4, 5, 5, 1, 5, 2, 2, 2, 5, 1, 1, 2, 1, 4, 5, 6, 2, 4, 3, 4, 3, 5, 2, 2, 1, 1, 5, 1, 3, 6, 6, 6, 6, 5, 2, 6, 5, 4, 4, 5, 1, 6, 6, 6, 4, 2, 6, 2, 6, 2, 2, 4, 3, 6, 4, 6, 4, 2, 4, 3, 3, 1, 6, 3, 3, 4, 4, 5, 5, 5, 6, 2, 3, 6, 1, 1, 1)
Digital Clock
Create a digital clock with the current time, using the following "font" of digits made out of underscores and pipe characters:
__ __ __ __ __ __ __ __
| | | __| __| |__| |__ |__ | |__| |__|
|__| | |__ __| | __| |__| | |__| __|
For example, when the program runs it could look like this:
__ __ __ __ __ __
| | |__| * __| __| * __| |__
|__| __| * __| __| * __| |__|
Press Ctrl-C to quit.
Digital Stream / Matrix Screensaver
This program mimics the “digital stream” visualization from the science fiction movie The Matrix. Random beads of binary “rain” stream up from the bottom of the screen, creating a cool, hacker-like visualization.
For example, when the program runs it could look like this:
0 0
0 0
1 0 0 1 1 0 1
0 0 0 1 0 0 0 0 0
0 1 0 0 0 1 0 0 1 0 1
0 1 0 0 1 011 1 1 0 1 0
0 1 0 0 0 000 11 0 0 1 1 0
1 1 0 1 0 1 1 110 10 1 0 1 0 1 0
1 101 0 0 1 000 11 1 1 11 1 1 1
0 100 1 0 11 00 0 1 01 0
1 1 001 1 1 0 1 10 0 10 0
0 0 010 0 1 1 11 11 0 0
--snip--
DNA Visualization
Let's create a DNA animation program. Deoxyribonucleic acid is a tiny molecule that exists in every cell of our bodies and contains the blueprint for how our bodies grow. It looks like a double helix (a sort of twisted ladder) of pairs of nucleotide molecules: guanine, cytosine, adenine, and thymine. These are represented by the letters G, C, A, and T. DNA is a long molecule; it’s microscopic, but if it were stretched out, its 3 billion base pairs would be 2 meters long! This program is a simple animation of DNA.
For example, when the program runs it could look like this:
#G-C#
#C---G#
#T-----A#
#T------A#
#A------T#
#G-----C#
#G---C#
#C-G#
##
#T-A#
#C---G#
#G-----C#
#G------C#
#T------A#
#A-----T#
#C---G#
#G-C#
##
#T-A#
#T---A#
#A-----T#
--snip--
Ducklings
This program creates a scrolling field of ducklings. Each duckling has slight variations: they can face left or right and have two different body sizes, four types of eyes, two types of mouths, and three positions for their wings. This gives us 96 different possible variations, which the Ducklings program produces endlessly:
>" ) =^^) (``= ("= >") ("=
( >) ( ^) (v ) (^ ) ( >) (v )
^ ^ ^ ^ ^ ^ ^^ ^^ ^^
For example, when the program runs it could look like this:
=" )
=") ( v)=")
( ^) ^ ^ ( v) >'')
^^ ^^ ( ^)
>") ^ ^
( v) =^^)
("< ("< >") ^^ ( >)
(^ ) (< ) ( ^) ^ ^
^^ ^^ ("< ^^ (``<>^^)
(^^= (^ ) (< )( ^)
(v ) ( "< ^^ ^ ^ ^ ^
--snip--
Etching Drawer
When you move a pen point around the screen with the WASD keys, the etching drawer forms a picture by tracing a continuous line, like the Etch A Sketch toy. Let your artistic side break out and see what images you can create! This program also lets you save your drawings to a text file so you can print them out later. Plus, you can copy and paste the WASD movements of other drawings into this program, like the WASD commands for the Hilbert Curve fractal presented on lines 6 to 14 of the source code.
For example, when the program runs it could look like this:
WASD keys to move, H for help, C to clear, F to save, or QUIT.
> DDSAASSDDWDDSDDWWAAWDDDDSDDWDDDDSAASDDSAAAAWAASSSDDWDDDDSAASDDSAAAAWA
──┐ ┌───┐ ┌───┐
┌─┘ └─┐ └─┘ ┌─┘
│ ┌─┐ │ ┌─┐ └─┐
└─┘ └─┘ │ └───┘
│ ┌───┐
└─┘ ┌─┘
#┐ └─┐
└───┘
Factor Finder
A number’s factors are any two other numbers that, when multiplied with each other, produce the number. For example, 2 × 13 = 26, so 2 and 13 are factors of 26. Also, 1 × 26 = 26, so 1 and 26 are also factors of 26. Therefore, we say that 26 has four factors: 1, 2, 13, and 26.
If a number only has two factors (1 and itself), we call that a prime number. Otherwise, we call it a composite number. Use the factor finder to discover some new prime numbers! (Hint: Prime numbers always end with an odd number that isn’t 5.) You can also have the computer calculate them with Project 56, “Prime Numbers.”
The math for this program isn’t too heavy, making it an ideal project for beginners.
For example, when the program runs it could look like this:
Enter a number to factor (or "QUIT" to quit):
> 26
1, 2, 13, 26
Enter a number to factor (or "QUIT" to quit):
> 4352784
1, 2, 3, 4, 6, 8, 12, 16, 24, 29, 48, 53, 58, 59, 87, 106, 116, 118, 159, 174, 177, 212, 232, 236, 318, 348, 354, 424, 464, 472, 636, 696, 708, 848, 944, 1272, 1392, 1416, 1537, 1711, 2544, 2832, 3074, 3127, 3422, 4611, 5133, 6148, 6254, 6844, 9222, 9381, 10266, 12296, 12508, 13688, 18444, 18762, 20532, 24592, 25016, 27376, 36888, 37524, 41064, 50032, 73776, 75048, 82128, 90683, 150096, 181366, 272049, 362732, 544098, 725464, 1088196, 1450928, 2176392, 4352784
Enter a number to factor (or "QUIT" to quit):
> 9787
1, 9787
Fast Draw
This program tests your reaction speed: press Enter as soon as you see the word DRAW. But careful, though. Press it before DRAW appears, and you lose. Are you the fastest keyboard in the west?
This program works because pressing Enter during time.sleep()
will cause the next input()
call to return in less than a millisecond or two, which would be impossibly fast for a human. This is how you can tell if the player pressed Enter too early.
For example, when the program runs it could look like this:
Time to test your reflexes and see if you are the fastest
draw in the west!
When you see "DRAW", you have 0.3 seconds to press Enter.
But you lose if you press Enter before "DRAW" appears.
Press Enter to begin...
It is high noon...
DRAW!
You took 0.3485 seconds to draw. Too slow!
Enter QUIT to stop, or press Enter to play again.
> quit
Fibonacci
The Fibonacci sequence is a famous mathematical pattern credited to Italian mathematician Fibonacci in the 13th century (though others had discovered it even earlier). The sequence begins with 0 and 1, and the next number is always the sum of the previous two numbers. The sequence continues forever:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987 . . .
The Fibonacci sequence has applications in music composition, stock market prediction, the pattern of florets in the head of sunflowers, and many other areas. This program lets you calculate the sequence as high as you are willing to go. More information about the Fibonacci sequence can be found at https://en.wikipedia.org/wiki/Fibonacci_number.
For example, when the program runs it could look like this:
Enter the Nth Fibonacci number you wish to
calculate (such as 5, 50, 1000, 9999), or QUIT to quit:
> 50
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049
Fish Tank
Watch your own virtual fish in a virtual fish tank, complete with air bubblers and kelp plants. Each time you run the program, it randomly generates the fish using different fish types and colors. Take a break and enjoy the calm serenity of this software aquarium, or try programming in some virtual sharks to terrorize its inhabitants! You can’t run this program from your IDE or editor. This program uses the bext module and must be run from the Command Prompt or Terminal in order to display correctly. More information about the bext module can be found at https://pypi.org/project/bext/.
For example, when the program runs it could look like this:
o ( (
) )
o ( ) }-[[[*>
) )
<==-< o (o[[< )
( ) <//<
<=^_.-._.- ( (
) )
) ( <//<
) (
( )
) (
( )
) )
) )
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
Flooder
Flooder is a colorful game where a player tries to fill the board with a single color by changing the color of the tile in the upper-left corner. This new color spreads to all neighboring tiles that matched the original color. It’s similar to the Flood It mobile game. This program also has a colorblind mode, which uses shapes instead of flat colored tiles. It relies on the recursive flood fill algorithm to paint the board and works similarly to the “paint bucket” or “fill” tool in many painting applications.
For example, when the program runs it could look like this:
┌────────────────┐
>♥♥♥♥♥♥♥♥♥♥♥♥♥♥▲▲│
│♥♥♥♥♥♥♥♥♥♦♦♥♥♦♦♦│
│♥♥♥♥♥♥♥♥♥♥♥♦♦♦♦♦│
│♥♥♥♥♥♥♥♥♥♥♥♦♦▲♦♦│
│♥♥♥♥♥♥♥♥♥♣♣♣♣♣♠●│
│♥♥♥♥♦♦♥♥♥♥♠♣♣♣♣♠│
│▲▲▲♥♥♥♥♥♥♥♥♥♦♠♥♠│
│▲▲♣♣●●●♠♥♥●♣♣♣♦♦│
│♣♣♣♠♠♠♠♦♠▲▲▲♠♠▲▲│
│●●♥●●●●●♣▲♠♠♠♥♣♣│
│♥♥♣♣♣♣♣♣▲♥♥♣♦♦♥♥│
│♣♣♦♠♥♥♦♦▲▲♠♠♠♠♠♥│
│▲▲♠●♥♥♥♥♠♠♣●●▲♠♠│
│♥♥●●♣♣♦♣♣♣♥♥♥♥▲▲│
└────────────────┘
Moves left: 12
Choose one of (H)eart, (T)riangle, (D)iamond, (B)all, (C)lub, (S)pade, or QUIT:
>
Forest Fire Sim
This simulation shows a forest whose trees are constantly growing and then being burned down. On each step of the simulation, there is a 1 percent chance that a blank space grows into a tree and a 1 percent chance that a tree is struck by lightning and burns. Fires will spread to adjacent trees, so a densely packed forest is more likely to suffer a larger fire than a sparsely packed one. This simulation was inspired by Nicky Case’s Emoji Sim at https://ncase.me/simulating/model/.
For example, when the program runs it could look like this:
AA A A A A A WA AA A A A AA AA
A A A A A A AA AAA A A A A A
A A A A A A A A WA AA A A A
A A A AAA A WW A A A A A W A
A AA A A A A A A
A A A A A A A A W A
A A A A A A A A A A AA A WAA A A
A A A A A A A AAAA W A
A A A A A A A A A A A
A A AA A A A A A AA AA AA
AA A AA A A A A W A A A A A A
A A A AA A W AA AA A A AA A A A
A A A AAA A W A A WA A AA A A A
A A AA A AA A A A A AA A A A A
A A A AA A A A A A A A A
A AA A A A A A A A A A A
AAA A A AA A A A A A AA A A
A A A A A A W A A
A A A A
A A AA A A A A A A A A A
A A A A A A A AA
A A A A A A A A AA A
Grow chance: 1.0% Lightning chance: 1.0% Press Ctrl-C to quit.
Four in a Row
In this classic tile-dropping board game for two players, you must try to get four of your tiles in a row horizontally, vertically, or diagonally, while preventing your opponent from doing the same. This program is similar to Connect Four.
For example, when the program runs it could look like this:
Player X, enter a column or QUIT:
> 3
1234567
+-------+
|.......|
|.......|
|.......|
|.......|
|.......|
|..X....|
+-------+
Player O, enter a column or QUIT:
> 5
--snip--
Player O, enter a column or QUIT:
> 4
1234567
+-------+
|.......|
|.......|
|XXX.XO.|
|OOOOXO.|
|OOOXOX.|
|OXXXOXX|
+-------+
Player O has won!
Guess the Number
Guess the Number is a game for beginners to practice basic programming techniques. In this game, the computer thinks of a random number between 1 and 100. The player has 10 chances to guess the number. After each guess, the computer tells the player if it was too high or too low.
For example, when the program runs it could look like this:
I am thinking of a number between 1 and 100.
You have 10 guesses left. Take a guess.
> 50
Your guess is too high.
You have 9 guesses left. Take a guess.
> 25
Your guess is too low.
--snip--
You have 5 guesses left. Take a guess.
> 42
Yay! You guessed my number!
Gullible
In this short and simple program, you can learn the secret and subtle art of keeping a gullible person busy for hours. I won’t spoil the punch line here. Copy the code and run it for yourself. This project is great for beginners, whether you’re smart or... not so smart.
For example, when the program runs it could look like this:
Do you want to know how to keep a gullible person busy for hours? Y/N
> y
Do you want to know how to keep a gullible person busy for hours? Y/N
> y
Do you want to know how to keep a gullible person busy for hours? Y/N
> yes
Do you want to know how to keep a gullible person busy for hours? Y/N
> YES
Do you want to know how to keep a gullible person busy for hours? Y/N
> TELL ME HOW TO KEEP A GULLIBLE PERSON BUSY FOR HOURS
"TELL ME HOW TO KEEP A GULLIBLE PERSON BUSY FOR HOURS" is not a valid yes/no response.
Do you want to know how to keep a gullible person busy for hours? Y/N
> y
Do you want to know how to keep a gullible person busy for hours? Y/N
> y
Do you want to know how to keep a gullible person busy for hours? Y/N
> n
Thank you. Have a nice day!
Hacking Minigame
In this game, the player must hack a computer by guessing a seven-letter word used as the secret password. The computer’s memory banks display the possible words, and the player is given hints as to how close each guess was. For example, if the secret password is MONITOR but the player guessed CONTAIN, they are given the hint that two out of seven letters were correct, because both MONITOR and CONTAIN have the letter O and N as their second and third letter. This game is similar to Project 1, “Bagels,” and the hacking minigame in the Fallout series of video games.
Here is a text file of seven letter words.
For example, when the program runs it could look like this:
Hacking Minigame, by Al Sweigart al@inventwithpython.com
Find the password in the computer's memory:
0x1150 $],>@|~~RESOLVE^ 0x1250 {>+)<!?CHICKEN,%
0x1160 }@%_-:;/$^(|<|!( 0x1260 .][})?#@#ADDRESS
0x1170 _;)][#?<&~$~+&}} 0x1270 ,#=)>{-;/DESPITE
0x1180 %[!]{REFUGEE@?~, 0x1280 }/.}!-DISPLAY%%/
0x1190 _[^%[@}^<_+{_@$~ 0x1290 =>>,:*%?_?@+{%#.
0x11a0 )?~/)+PENALTY?-= 0x12a0 >[,?*#IMPROVE@$/
--snip--
Enter password: (4 tries remaining)
> resolve
Access Denied (2/7 correct)
Enter password: (3 tries remaining)
> improve
A C C E S S G R A N T E D
Hangman & Guillotine
This classic word game has the player guess the letters to a secret word. For each incorrect letter, another part of the hangman is drawn. Try to guess the complete word before the hangman completes. The secret words in this version are all animals like RABBIT and PIGEON, but you can replace these with your own set of words.
The HANGMAN_PICS variable contains ASCII-art strings of each step of the hangman’s noose:
+--+ +--+ +--+ +--+ +--+ +--+ +--+
| | | | | | | | | | | | | |
| O | O | O | O | O | O |
| | | | /| | /|\ | /|\ | /|\ |
| | | | | / | / \ |
| | | | | | |
===== ===== ===== ===== ===== ===== =====
For a French twist on the game, you can replace the strings in the HANGMAN_PICS variable with the following strings depicting a guillotine:
| | | |===| |===| |===| |===| |===|
| | | | | | | | | || /| || /|
| | | | | | | | | ||/ | ||/ |
| | | | | | | | | | | | |
| | | | | | | | | | | | |
| | | | | | | |/-\| |/-\| |/-\|
| | | | | |\ /| |\ /| |\ /| |\O/|
|=== |===| |===| |===| |===| |===| |===|
For example, when the program runs it could look like this:
+--+
| |
O |
/| |
|
|
=====
The category is: Animals
Missed letters: A I S
O T T E _
Guess a letter.
> r
Yes! The secret word is: OTTER
You have won!
Hex Grid
This short program produces a tessellated image of a hexagonal grid, similar to chicken wire. It shows that you don’t need a lot of code to make something interesting. A slightly more complicated variation of this program is Project 65, “Shining Carpet.”
For example, when the program runs it could look like this:
/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_
\_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/
/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_
\_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/
/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_
\_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/
/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_
\_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/
/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_
\_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/
/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_
For practice, try re-creating this program with larger hexagon grids, such as the following patterns:
/ \ / \ / \ / \ / \ / \ / \
/ \___/ \___/ \___/ \___/ \___/ \___/ \
\ / \ / \ / \ / \ / \ / \ /
\___/ \___/ \___/ \___/ \___/ \___/ \___/
/ \ / \ / \ / \ / \ / \ / \
/ \___/ \___/ \___/ \___/ \___/ \___/ \
/ \ / \ / \ / \
/ \ / \ / \ / \
/ \_____/ \_____/ \_____/ \_____
\ / \ / \ / \ /
\ / \ / \ / \ /
\_____/ \_____/ \_____/ \_____/
/ \ / \ / \ / \
/ \ / \ / \ / \
/ \_____/ \_____/ \_____/ \_____
Hourglass
This visualization program has a rough physics engine that simulates sand falling through the small aperture of an hourglass. The sand piles up in the bottom half of the hourglass; then the hourglass is turned over so the process repeats.
Each piece of sand moves down (and to the left or right) if the space underneath it is empty.
For example, when the program runs it could look like this:
███████████████████
█ █
█ █
█░░ ░░░░█
█░░ ░░░░░█
█░░░ ░░░░░█
█░░░ ░░░░░░░█
█░░░░░░░░░█
█░░ ░░░░█
█░░░░░█
█░░░█
█░█
█ ░ █
█ █
█ ░ █
█ █
█ ░ █
█ █
█ ░ ░ █
█ ░░░░ █
█ ░░░░░░ █
█ ░░░░░░░░░ ░ █
███████████████████
Hungry Robots
You are trapped in a maze with hungry robots! You don’t know why robots need to eat, but you don’t want to find out. The robots are badly programmed and will move directly toward you, even if blocked by walls. You must trick the robots into crashing into each other (or dead robots) without being caught.
You are represented by an @
while the robots are R
. Destroyed robots are X
. For example, when the program runs it could look like this:
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░ ░ R R ░ ░ ░
░ ░ ░░░ R░ ░░ ░
░ ░ ░ ░ ░ ░ ░ ░░░ ░
░ R░ ░ ░ ░░ ░░ ░ ░
░ ░░ ░ ░ ░░░ ░ ░ ░
░ ░░ ░ RX░░░ ░ ░ ░ ░ ░
░ ░ R R R ░ ░ ░
░ ░ ░ ░ ░ R ░ ░
░ ░ R R ░ R ░ R ░
░ ░ ░ ░ ░ ░ ░ ░ ░
░ @ ░ ░ R░░░ ░ ░
░ ░ ░░ ░░ ░ ░
░ ░ ░░ ░ ░ R ░░
░░X ░ ░ ░ R ░░RR ░ R ░
░RR R R ░ ░ ░ R░
░ ░░ RRR R ░
░ ░░R ░ ░
░ R ░ ░ ░ ░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
(T)eleports remaining: 2
(Q) (W) ( )
(A) (S) (D)
Enter move or QUIT: (Z) (X) ( )
J'Accuse!
You are the world-famous detective Mathilde Camus. Zophie the cat has gone missing, and you must sift through the clues. Suspects either always tell lies or always tell the truth. Will you find Zophie the cat in time and accuse the guilty party?
In this game, you take a taxi to different locations around the city. At each location is a suspect and an item. You can ask suspects about other suspects and items, compare their answers with your own exploration notes, and determine if they are lying or telling the truth. Some will know who has catnapped Zophie (or where she is, or what item is found at the location of the kidnapper), but you must determine if you can believe them. You have five minutes to find the criminal but will lose if you make three wrong accusations. This game is inspired by Homestar Runner’s “Where’s an Egg?” game.
For example, when the program runs it could look like this:
Time left: 5 min, 0 sec
You are in your TAXI. Where do you want to go?
(A)LBINO ALLIGATOR PIT
(B)OWLING ALLEY
(C)ITY HALL
(D)UCK POND
(H)IPSTER CAFE
(O)LD BARN
(U)NIVERSITY LIBRARY
(V)IDEO GAME MUSEUM
(Z)OO
> a
Time left: 4 min, 48 sec
You are at the ALBINO ALLIGATOR PIT.
ESPRESSA TOFFEEPOT with the ONE COWBOY BOOT is here.
(J) "J'ACCUSE!" (3 accusations left)
(Z) Ask if they know where ZOPHIE THE CAT is.
(T) Go back to the TAXI.
(1) Ask about ESPRESSA TOFFEEPOT
(2) Ask about ONE COWBOY BOOT
> z
They give you this clue: "DUKE HAUTDOG"
Press Enter to continue...
Langton's Ant
Langton’s Ant is a cellular automata simulation on a two-dimensional grid, similar to Project 13, “Conway’s Game of Life.” In the simulation, an “ant” begins on a square that is one of two colors. If the space is the first color, the ant switches it to the second color, turns 90 degrees to the right, and moves forward one space. If the space is the second color, the ant switches it to the first color, turns 90 degrees to the left, and moves forward one space. Despite the very simple set of rules, the simulation displays complex emergent behavior. Simulations can feature multiple ants in the same space, causing interesting interactions when they cross paths with each other. Langton’s Ant was invented by computer scientist Chris Langton in 1986. More information about Langton’s Ant can be found at https://en.wikipedia.org/wiki/Langton%27s_ant.
Leetspeak
There’s no better way to demonstrate your mad hacker skills than by replacing letters in your text with numbers: m4d h4x0r 5k1llz!!! This word program automatically converts plain English into leetspeak, the coolest way to talk online. Or at least it was in 1993.
It takes a while to get used to, but with some practice, you’ll eventually be able to read leetspeak fluently. For example, 1t +@]<3s 4 w|-|1le +o g37 ||s3|) 70, b||+ y0u (an 3\/3nt||/-\lly r3a|) l33t$peak phl||3n+ly. Leetspeak may be hard to read at first, but the program itself is simple and good for beginners. More information about leetspeak can be found at https://en.wikipedia.org/wiki/Leet.
For example, when the program runs it could look like this:
Enter your leet message:
> I am a leet hacker. Fear my mad skills. The 90s were over two decades ago.
! @m a l33t h@(]<er. ph3@r my m4|) $k|ll$. +h3 90s w3r3 0ver tw0 d3(ad3$ 4g0.
(Copied leetspeak to clipboard.)
Lucky Stars
In this push-your-luck game, you roll dice to collect stars. The more you roll, the more stars you can get, but if you get three skulls you lose everything! This quick multiplayer game can support as many players as you want, making it ideal for parties. Inspired by the Zombie Dice game from Steve Jackson Games.
On your turn, you pull three random dice from the dice cup and roll them. You can roll Stars, Skulls, and Question Marks. If you end your turn, you get one point per Star. If you choose to roll again, you keep the Question Marks and pull new dice to replace the Stars and Skulls. If you collect three Skulls, you lose all your Stars and end your turn.
When a player gets 13 points, everyone else gets one more turn before the game ends. Whoever has the most points wins.
There are six gold dice, four silver dice, and three bronze dice in the cup. Gold dice have more Stars, bronze dice have more Skulls, and silver is even.
For example, when the program runs it could look like this:
SCORES: Alice=0, Bob=0
It is Alice's turn.
+-----------+ +-----------+ +-----------+
| | | . | | |
| | | ,O, | | |
| ? | | 'ooOOOoo' | | ? |
| | | `OOO` | | |
| | | O' 'O | | |
+-----------+ +-----------+ +-----------+
GOLD GOLD BRONZE
Stars collected: 1 Skulls collected: 0
Do you want to roll again? Y/N
> y
+-----------+ +-----------+ +-----------+
| . | | ___ | | |
| ,O, | | / \ | | |
| 'ooOOOoo' | | |() ()| | | ? |
| `OOO` | | \ ^ / | | |
| O' 'O | | VVV | | |
+-----------+ +-----------+ +-----------+
GOLD BRONZE BRONZE
Stars collected: 2 Skulls collected: 1
Do you want to roll again? Y/N
--snip--
Magic Fortune Ball
The Magic Fortune Ball can predict the future and answer your yes/no questions with 100 percent accuracy using the power of Python’s random number module. This program is similar to a Magic 8 Ball toy, except you don’t have to shake it. It also features a function for slowly printing text strings with spaces in between each character, giving the messages a spooky, mysterious effect.
Most of the code is dedicated to setting the eerie atmosphere. The program itself simply selects a message to display in response to a random number.
For example, when the program runs it could look like this:
M A G i C F O R T U N E B A L L , B Y A L S W E i G A R T
A S K M E Y O U R Y E S / N O Q U E S T i O N .
> Isn't fortune telling just a scam to trick money out of gullible people?
L E T M E T H i N K O N T H i S . . .
. . . . . . . .
i H A V E A N A N S W E R . . .
A F F i R M A T i V E
Mancala
The board game Mancala is at least 2,000 years old, making it almost as old as Project 63, “Royal Game of Ur.” It is a “seed-sowing” game in which two players select pockets of seeds to spread across the other pockets on the board while trying to collect as many in their store as possible. There are several variants of this game across different cultures. The name comes from the Arab word naqala, meaning “to move.”
To play, grab the seeds from a pit on your side of the board and place one in each subsequent pit, going counterclockwise and skipping your opponent’s store. If your last seed lands in an empty pit of yours, move the opposite pit’s seeds into that pit. If the last placed seed is in your store, you get a free turn.
The game ends when all of one player’s pits are empty. The other player claims the remaining seeds for their store, and the winner is the one with the most seeds. More information about Mancala and its variants can be found at https://en.wikipedia.org/wiki/Mancala.
For example, when the program runs it could look like this:
+------+------+--<<<<<-Player 2----+------+------+------+
2 |G |H |I |J |K |L | 1
| 4 | 4 | 4 | 4 | 4 | 4 |
S | | | | | | | S
T 0 +------+------+------+------+------+------+ 0 T
O |A |B |C |D |E |F | O
R | 4 | 4 | 4 | 4 | 4 | 4 | R
E | | | | | | | E
+------+------+------+-Player 1->>>>>-----+------+------+
Player 1, choose move: A-F (or QUIT)
> f
+------+------+--<<<<<-Player 2----+------+------+------+
2 |G |H |I |J |K |L | 1
| 4 | 4 | 4 | 5 | 5 | 5 |
S | | | | | | | S
T 0 +------+------+------+------+------+------+ 1 T
O |A |B |C |D |E |F | O
R | 4 | 4 | 4 | 4 | 4 | 0 | R
E | | | | | | | E
+------+------+------+-Player 1->>>>>-----+------+------+
Player 2, choose move: G-L (or QUIT)
Maze Runner 2D
This two-dimensional maze runner shows the player a top-down, bird’s-eye view of a maze file you create in a text editor, such as the IDE you use to write your .py files. Using the WASD keys, the player can move up, left, down, and right, respectively, to navigate the @ symbol toward the exit marked by the X character.
To make a maze file, open a text editor and create the following pattern. Don’t type the numbers along the top and left side; they are only there for reference:
123456789
1#########
2#S# # # #
3#########
4# # # # #
5#########
6# # # # #
7#########
8# # # #E#
9#########
The # characters represent walls, the S marks the start, and the E marks the exit. The # characters in bold represent walls that you can remove to form your maze. Don’t remove the walls at odd-numbered columns and odd-numbered rows, and don’t remove the borders of the maze. When you’re done, save the maze as a .txt (text) file. It could look something like this:
#########
#S # #
# ### # #
# # # #
# ##### #
<a id="#-#-#" />
# # #
### # # #
# #E#
#########
Of course, this is a simple maze. You can make maze files of any size as long as they have an odd number of rows and columns. Be sure it’ll still fit on the screen, though! You can also download maze files from https://invpy.com/mazes/.
For example, when the program runs it could look like this:
Enter the filename of the maze (or LIST or QUIT):
> maze65x11s1.txt
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░@░ ░ ░ ░ ░ ░ ░
░ ░░░░░ ░ ░░░ ░ ░ ░░░░░░░ ░░░░░ ░░░░░░░░░░░░░░░░░░░░░ ░░░ ░ ░ ░ ░
░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░
░ ░ ░ ░░░░░ ░ ░ ░░░░░ ░ ░░░░░ ░░░ ░ ░░░░░░░░░ ░ ░░░ ░░░ ░ ░░░░░ ░
░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░
░░░░░░░░░ ░░░ ░░░ ░ ░░░░░░░░░░░ ░░░░░ ░ ░░░░░ ░ ░ ░░░ ░░░░░ ░░░░░
░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░
░ ░ ░ ░░░ ░ ░░░ ░ ░ ░ ░░░░░░░░░░░ ░░░░░░░░░░░░░ ░ ░░░░░ ░ ░░░░░ ░
░ ░ ░ ░ ░ ░ X░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
W
Enter direction, or QUIT: ASD
Maze Runner 3D
This three-dimensional maze runner provides the player with a first-person view from inside a maze. Try to find your way out! You can generate maze files by following the instructions in Project 44, “Maze Runner 2D,” or by downloading maze files from https://invpy.com/mazes/.
For example, when the program runs it could look like this:
Enter the filename of the maze (or LIST or QUIT):
> maze75x11s1.txt
░░░░░░░░░░░░░░░░░░░
░ \ / ░
░ \_________/ ░
░ | | ░
░ | | ░
░ | | ░
░ | | ░
░ | | ░
░ | | ░
░ | | ░
░ | | ░
░ |_______| ░
░ / \ ░
░ / \ ░
░░░░░░░░░░░░░░░░░░░
Location (1, 1) Direction: NORTH
(W)
Enter direction: (A) (D) or QUIT.
> d
░░░░░░░░░░░░░░░░░░░
░ \ ░
░ \_____________░
░ | ░
░ | ░
░ | ░
░ | ░
░ | ░
░ | ░
░ | ░
░ | ░
░ |____________░
░ / ░
░ / ░
░░░░░░░░░░░░░░░░░░░
Location (1, 1) Direction: EAST
Million Dice Statistics
When you roll two six-sided dice, there’s a 17 percent chance you’ll roll a 7. That’s much better than the odds of rolling a 2: just 3 percent. That’s because there’s only one combination of dice rolls that gives you 2 (the one that occurs when both dice roll a 1), but many combinations add up to seven: 1 and 6, 2 and 5, 3 and 4, and so on.
But what about when you roll three dice? Or four? Or 1,000? You could mathematically calculate the theoretical probabilities, or you can have the computer roll a number of dice one million times to empirically figure them out. This program takes that latter approach. In this program, you tell the computer to roll N dice one million times and remember the results. It then displays the percentage chance of each sum.
For example, when the program runs it could look like this:
Enter how many six-sided dice you want to roll:
> 2
Simulating 1,000,000 rolls of 2 dice...
36.2% done...
73.4% done...
TOTAL - ROLLS - PERCENTAGE
2 - 27590 rolls - 2.8%
3 - 55730 rolls - 5.6%
4 - 83517 rolls - 8.4%
5 - 111526 rolls - 11.2%
6 - 139015 rolls - 13.9%
7 - 166327 rolls - 16.6%
8 - 139477 rolls - 13.9%
9 - 110268 rolls - 11.0%
10 - 83272 rolls - 8.3%
11 - 55255 rolls - 5.5%
12 - 28023 rolls - 2.8%
Mondrian Art Generator
Piet Mondrian was a 20th-century Dutch painter and one of the founders of neoplasticism, an abstract art movement. His most iconic paintings relied on blocks of primary colors (blue, yellow, red), black, and white. Using a minimalist approach, he separated these colors with horizontal and vertical elements.
This program generates random paintings that follow Mondrian’s style. You can find out more about Piet Mondrian at https://en.wikipedia.org/wiki/Piet_Mondrian. An implementation of this algorithm with examples is in this git repo.
Monty Hall
The Monty Hall Problem illustrates a surprising fact of probability. The problem is loosely based on the old game show Let’s Make a Deal and its host, Monty Hall. In the Monty Hall Problem, you can pick one of three doors. Behind one door is a prize: a new car. Each of the other two doors opens onto a worthless goat. Say you pick Door #1. Before the door you choose is opened, the host opens another door (either #2 or #3), which leads to a goat. You can choose to either open the door you originally picked or switch to the other unopened door.
It may seem like it doesn’t matter if you switch or not, but your odds do improve if you switch doors! This program demonstrates the Monty Hall problem by letting you do repeated experiments.
For example, when the program runs it could look like this:
+------+ +------+ +------+
| | | | | |
| 1 | | 2 | | 3 |
| | | | | |
| | | | | |
| | | | | |
+------+ +------+ +------+
Pick a door 1, 2, or 3 (or "quit" to stop):
> 1
+------+ +------+ +------+
| | | | | (( |
| 1 | | 2 | | oo |
| | | | | /_/|_|
| | | | | | |
| | | | |GOAT|||
+------+ +------+ +------+
Door 3 contains a goat!
Do you want to swap doors? Y/N
> y
+------+ +------+ +------+
| (( | | CAR! | | (( |
| oo | | __| | oo |
| /_/|_| | _/ | | /_/|_|
| | | | /_ __| | | |
|GOAT||| | O | |GOAT|||
+------+ +------+ +------+
Door 2 has the car!
You won!
Swapping: 1 wins, 0 losses, success rate 100.0%
Not swapping: 0 wins, 0 losses, success rate 0.0%
Press Enter to repeat the experiment...
Multiplication Table
This program generates a multiplication table from 0 × 0 to 12 × 12. While simple, it provides a useful demonstration of nested loops.
For example, when the program runs it could look like this:
| 0 1 2 3 4 5 6 7 8 9 10 11 12
--+---------------------------------------------------
0| 0 0 0 0 0 0 0 0 0 0 0 0 0
1| 0 1 2 3 4 5 6 7 8 9 10 11 12
2| 0 2 4 6 8 10 12 14 16 18 20 22 24
3| 0 3 6 9 12 15 18 21 24 27 30 33 36
4| 0 4 8 12 16 20 24 28 32 36 40 44 48
5| 0 5 10 15 20 25 30 35 40 45 50 55 60
6| 0 6 12 18 24 30 36 42 48 54 60 66 72
7| 0 7 14 21 28 35 42 49 56 63 70 77 84
8| 0 8 16 24 32 40 48 56 64 72 80 88 96
9| 0 9 18 27 36 45 54 63 72 81 90 99 108
10| 0 10 20 30 40 50 60 70 80 90 100 110 120
11| 0 11 22 33 44 55 66 77 88 99 110 121 132
12| 0 12 24 36 48 60 72 84 96 108 120 132 144
Ninety Nine Bottles
“Ninety-Nine Bottles” is a folk song of undetermined origin known for its length and repetitiveness. The lyrics go, “Ninety-nine bottles of milk on the wall, ninety-nine bottles of milk. Take one down, pass it around, ninety-eight bottles of milk on the wall.” As the lyrics repeat, the number of bottles falls from ninety-eight to ninety-seven, then from ninety-seven to ninety-six, until it reaches zero: “One bottle of milk on the wall, one bottle of milk. Take it down, pass it around, no more bottles of milk on the wall!”
For example, when the program runs it could look like this:
99 bottles of milk on the wall,
99 bottles of milk,
Take one down, pass it around,
98 bottles of milk on the wall!
98 bottles of milk on the wall,
98 bottles of milk,
Take one down, pass it around,
97 bottles of milk on the wall!
--snip--
niNety nniinE BoOttels
In this version of the song “Ninety-Nine Bottles,” the program introduces small imperfections in each stanza by either removing a letter, swapping the casing of a letter, transposing two letters, or doubling a letter. As the song continues to play, these mutations add up, resulting in a very silly song.
For example, when the program runs it could look like this:
99 bottles of milk on the wall,
99 bottles of milk,
Take one down, pass it around,
98 bottles of milk on the wall!
98 bottles of milk on the wall,
98 bottles of milk,
Take one d wn, pass it around,
97 bottles of milk on the wall!
97 bottles of milk on the wall,
97 bottels of milk,
Take one d wn, pass it around,
96 bottles of milk on the wall!
--snip--
75b otlte of mIl on teh wall,
75 ottels f miLk,
Take one d wn, pass it ar und,
74 bbOttles of milk on t e wall!
--snip--
1 otlE t of iml oo nteh lall,
1 o Tle FF FmMLIIkk,
Taake on d wn, pAasSs itt au nn d,
No more bottles of milk on the wall!
Numeral Systems
This program displays numbers in decimal, hexadecimal, and binary.
We’re used to counting in the decimal numeral system, which uses 10 digits: 0 through 9. This system likely developed because humans counted on their fingers, and most people have 10 fingers. But other number systems exist. Computers make use of binary, a numeral system with only two digits, 0 and 1. Programmers also sometimes use hexadecimal, which is a base-16 numeral system that uses the digits 0 to 9 but also extends into the letters A to F.
For example, when the program runs it could look like this:
Enter the starting number (e.g. 0) > 0
Enter how many numbers to display (e.g. 1000) > 20
DEC: 0 HEX: 0 BIN: 0
DEC: 1 HEX: 1 BIN: 1
DEC: 2 HEX: 2 BIN: 10
DEC: 3 HEX: 3 BIN: 11
DEC: 4 HEX: 4 BIN: 100
DEC: 5 HEX: 5 BIN: 101
DEC: 6 HEX: 6 BIN: 110
DEC: 7 HEX: 7 BIN: 111
DEC: 8 HEX: 8 BIN: 1000
DEC: 9 HEX: 9 BIN: 1001
DEC: 10 HEX: A BIN: 1010
DEC: 11 HEX: B BIN: 1011
DEC: 12 HEX: C BIN: 1100
DEC: 13 HEX: D BIN: 1101
DEC: 14 HEX: E BIN: 1110
DEC: 15 HEX: F BIN: 1111
DEC: 16 HEX: 10 BIN: 10000
DEC: 17 HEX: 11 BIN: 10001
DEC: 18 HEX: 12 BIN: 10010
DEC: 19 HEX: 13 BIN: 10011
Periodic Table of the Elements
The periodic table of the elements organizes all known chemical elements into a single table. This program presents this table and lets the player access additional information about each element, such as its atomic number, symbol, melting point, and so on. I compiled this information from Wikipedia and stored it in a file called periodictable.csv that you can download from https://inventwithpython.com/periodictable.csv.
For example, when the program runs it could look like this:
Periodic Table of Elements
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
1 H He
2 Li Be B C N O F Ne
3 Na Mg Al Si P S Cl Ar
4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr
5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe
6 Cs Ba La Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn
7 Fr Ra Ac Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og
Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu
Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr
Enter a symbol or atomic number to examine, or QUIT to quit.
> 42
Atomic Number: 42
Symbol: Mo
Element: Molybdenum
Origin of name: Greek molýbdaina, 'piece of lead', from mólybdos, 'lead'
Group: 6
Period: 5
Atomic weight: 95.95(1) u
Density: 10.22 g/cm^3
Melting point: 2896 K
Boiling point: 4912 K
Specific heat capacity: 0.251 J/(g*K)
Electronegativity: 2.16
Abundance in earth's crust: 1.2 mg/kg
Press Enter to continue...
--snip--
Pig Latin
Pig Latin is a word game that transforms English words into a parody of Latin. In Pig Latin, if a word begins with a consonant, the speaker removes this letter and puts it at the end, followed by “ay.” For example, “pig” becomes “igpay” and “latin” becomes “atinlay.” Otherwise, if the word begins with a vowel, the speaker simply adds “yay” to the end of it. For example, “elephant” becomes “elephantyay” and “umbrella” becomes “umbrellayay.”
For example, when the program runs it could look like this:
Enter your message:
> This is a very serious message.
Isthay isyay ayay eryvay erioussay essagemay.
(Copied pig latin to clipboard.)
Powerball Lottery
The Powerball Lottery is an exciting way to lose small amounts of money. If you purchase a $2 ticket, you can pick six numbers: five drawn from 1 to 69, and a sixth “Powerball” number drawn from 1 to 26. The order of the numbers doesn’t matter. If the lottery selects your six numbers, you win $1.586 billion dollars! Except you won’t win, because your odds are 1 in 292,201,338. But if you spent $200 on 100 tickets, your odds would be . . . 1 in 2,922,013. You won’t win that either, but at least you’ll lose 100 times as much money. The more you like losing money, the more fun the lottery is!
For example, when the program runs it could look like this:
Enter 5 different numbers from 1 to 69, with spaces between
each number. (For example: 5 17 23 42 50 51)
> 1 2 3 4 5
Enter the powerball number from 1 to 26.
> 6
How many times do you want to play? (Max: 1000000)
> 1000000
It costs $2000000 to play 1000000 times, but don't
worry. I'm sure you'll win it all back.
Press Enter to start...
The winning numbers are: 12 29 48 11 4 and 13 You lost.
The winning numbers are: 54 39 3 42 16 and 12 You lost.
The winning numbers are: 56 4 63 23 38 and 24 You lost.
--snip--
The winning numbers are: 46 29 10 62 17 and 21 You lost.
The winning numbers are: 5 20 18 65 30 and 10 You lost.
The winning numbers are: 54 30 58 10 1 and 18 You lost.
You have wasted $2000000
Thanks for playing!
Prime Numbers
A prime number is a number that is evenly divisible only by one and itself. Prime numbers have a variety of practical applications, but no algorithm can predict them; we must calculate them one at a time. However, we do know that there is an infinite number of prime numbers to be discovered.
This program finds prime numbers through brute-force calculation. Its code is similar to Project 24, “Factor Finder.” (Another way to describe a prime number is that one and the number itself are its only factors.) You can find out more about prime numbers from https://en.wikipedia.org/wiki/Prime_number.
For example, when the program runs it could look like this:
Enter a number to start searching for primes from:
(Try 0 or 1000000000000 (12 zeros) or another number.)
> 0
Press Ctrl-C at any time to quit. Press Enter to begin...
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, --snip--
Progress Bar
A progress bar is a visual element that shows how much of a task has been completed. Progress bars are often used alongside downloading files or software installations. This project creates a getProgressBar() function that returns a progress bar string based on the arguments passed to it. It simulates a downloading file, but you can reuse the progress bar code in your own projects.
You can animate the text by printing \b
backspace characters to erase text you've already printed and then print a new progress bar.
For example, when the program runs it could look like this:
Progress Bar Simulation, by Al Sweigart
[█████████ ] 24.6% 1007/4098
Rainbow
Rainbow is a simple program that shows a colorful rainbow traveling back and forth across the screen. The program makes use of the fact that when new lines of text appear, the existing text scrolls up, causing it to look like it’s moving.
If you find this kind of animation interesting, you can find more examples of "scrolling ASCII art" on my other website, The Scroll Art Museum.
Rock Paper Scissors
In this version of the two-player hand game also known as Rochambeau or jan-ken-pon, the player faces off against the computer. You can pick either rock, paper, or scissors. Rock beats scissors, scissors beats paper, and paper beats rock. This program adds some brief pauses for suspense.
For example, when the program runs it could look like this:
Enter your move: (R)ock (P)aper (S)cissors or (Q)uit
> r
ROCK versus...
1...
2...
3...
SCISSORS
You win!
1 Wins, 0 Losses, 0 Ties
Enter your move: (R)ock (P)aper (S)cissors or (Q)uit
--snip--
Rock Paper Scissors (Always-Win Version)
This variant of Rock Paper Scissors is identical to “Rock Paper Scissors,” except the player will always win. The code selecting the computer’s move is set so that it always chooses the losing move. You can offer this game to your friends, who may be excited when they win... at first. See how long it takes before they catch on to the fact that the game is rigged in their favor.
For example, when the program runs it could look like this:
0 Wins, 0 Losses, 0 Ties
Enter your move: (R)ock (P)aper (S)cissors or (Q)uit
> p
PAPER versus...
1...
2...
3...
ROCK
You win!
1 Wins, 0 Losses, 0 Ties
Enter your move: (R)ock (P)aper (S)cissors or (Q)uit
> s
SCISSORS versus...
1...
2...
3...
PAPER
You win!
2 Wins, 0 Losses, 0 Ties
--snip--
SCISSORS versus...
1...
2...
3...
PAPER
You win!
413 Wins, 0 Losses, 0 Ties
Enter your move: (R)ock (P)aper (S)cissors or (Q)uit
--snip--
ROT 13 Cipher
The ROT13 cipher, one of the simplest encryption algorithms, stands for “rotate 13 spaces.” The cypher represents the letters A to Z as the numbers 0 to 25 in such a way that the encrypted letter is 13 spaces from the plaintext letter: A becomes N, B becomes O, and so on. The encryption process is identical to the decryption process, making it trivial to program. However, the encryption is also trivial to break. Because of this, you’ll most often find ROT13 used to conceal non-sensitive information, such as spoilers or trivia answers, so it’s not read unintentionally. More information about the ROT13 cipher can be found at https://en.wikipedia.org/wiki/ROT13. If you’d like to learn about ciphers and code breaking more generally, you can read my book Cracking Codes with Python (No Starch Press, 2018; https://nostarch.com/crackingcodes/).
For example, when the program runs it could look like this:
Enter a message to encrypt/decrypt (or QUIT):
> Meet me by the rose bushes tonight.
The translated message is:
Zrrg zr ol gur ebfr ohfurf gbavtug.
(Copied to clipboard.)
Rotating Cube
This project features an animation of a 3D cube rotating using trigonometric functions. You can adapt the 3D point rotation math and the line() function in your own animation programs.
Although the block text characters we’ll use to draw the cube don’t look like thin, straight lines, this kind of drawing is called a wireframe model because it renders only the edges of an object’s surfaces.
For example, when the program runs it could look like this:
██
█ ███
█ █ ██
█ █ ██
█ █ ██
█ █ ██
█ █ ██
█ █ █
█ █ █ █
█ █ █ █
█ █ █ █
█ ██ █
█ ██ █
█ █ █ █
█ █ █ █
█ █ █ █
█ █ █ █
█ █ █ █
█ █ █ █
█ █ █ ██ █
██ █ █ ██ █
█ ██ █ █ █ █
█ █ █ █ ██ █
█ ██ █ █ █ █
█ ██ █ █ ███
█ █ █ █ ██
█ ██ █ █ █
█ █ █ █
█ █ █ █
█ █ █ █
█ █ █ █
█ █ █ █
█ █ █ █
█ ██ █
█ ██ █
█ █ █ █
█ █ █ █
█ █ █ █
██ █ █
██ █ █
██ █ █
██ █ █
██ █ █
███ █
██ █
█
Royal Game of Ur
The Royal Game of Ur is a 5,000-year-old game from Mesopotamia. Archeologists rediscovered the game in the Royal Cemetery at Ur, in modern-day southern Iraq, during excavations between 1922 and 1934. The rules were reconstructed from the game board and a Babylonian clay tablet, and they’re similar to Parcheesi. You’ll need both luck and skill to win.
A video featuring YouTuber Tom Scott and British Museum curator Irving Finkel discussing the Royal Game of Ur can be found at https://www.youtube.com/watch?v=WZskjLq040I.
For example, when the program runs it could look like this:
--snip--
XXXXXXX .......
Home Goal
v ^
+-----+-----+-----+--v--+ +--^--+-----+
|*****| | | | |*****| |
|* *< < < | |* *< |
|****h| g| f| e| |****t| s|
+--v--+-----+-----+-----+-----+-----+-----+--^--+
| | | |*****| | | | |
| > > >* *> > > > |
| i| j| k|****l| m| n| o| p|
+--^--+-----+-----+-----+-----+-----+-----+--v--+
|*****| | | | |*****| |
|* *< < < | |* *< |
|****d| c| b| a| |****r| q|
+-----+-----+-----+--^--+ +--v--+-----+
^ v
Home Goal
OOOOOOO .......
It is O's turn. Press Enter to flip...
Flips: H-H-H-H Select token to move 4 spaces: home quit
> home
O landed on a flower space and gets to go again.
Press Enter to continue...
--snip--
Shining Carpet
The Shining, a 1980 psychological horror film directed by Stanley Kubrick, takes place at the haunted Overlook Hotel. The hotel carpet’s hexagonal design became an iconic part of this famous movie. The carpet features alternating and interlocking hexagons whose mesmerizing effect is well-suited for such an unnerving film. The short program in this project, similar to Project 35, “Hex Grid,” prints this repetitive pattern on the screen.
For example, when the program runs it could look like this:
_ \ \ \_/ ___ \ \ \_/ ___ \ \ \_/ ___ \ \ \_/ ___ \ \ \_/ ___ \ \ \_/ __
\ \ \___/ _ \ \ \___/ _ \ \ \___/ _ \ \ \___/ _ \ \ \___/ _ \ \ \___/ _
\ \ \_____/ \ \ \_____/ \ \ \_____/ \ \ \_____/ \ \ \_____/ \ \ \_____/
/ / / ___ \_/ / / ___ \_/ / / ___ \_/ / / ___ \_/ / / ___ \_/ / / ___ \_
_/ / / _ \___/ / / _ \___/ / / _ \___/ / / _ \___/ / / _ \___/ / / _ \__
__/ / / \_____/ / / \_____/ / / \_____/ / / \_____/ / / \_____/ / / \___
_ \ \ \_/ ___ \ \ \_/ ___ \ \ \_/ ___ \ \ \_/ ___ \ \ \_/ ___ \ \ \_/ __
\ \ \___/ _ \ \ \___/ _ \ \ \___/ _ \ \ \___/ _ \ \ \___/ _ \ \ \___/ _
\ \ \_____/ \ \ \_____/ \ \ \_____/ \ \ \_____/ \ \ \_____/ \ \ \_____/
/ / / ___ \_/ / / ___ \_/ / / ___ \_/ / / ___ \_/ / / ___ \_/ / / ___ \_
_/ / / _ \___/ / / _ \___/ / / _ \___/ / / _ \___/ / / _ \___/ / / _ \__
__/ / / \_____/ / / \_____/ / / \_____/ / / \_____/ / / \_____/ / / \___
_ \ \ \_/ ___ \ \ \_/ ___ \ \ \_/ ___ \ \ \_/ ___ \ \ \_/ ___ \ \ \_/ __
\ \ \___/ _ \ \ \___/ _ \ \ \___/ _ \ \ \___/ _ \ \ \___/ _ \ \ \___/ _
\ \ \_____/ \ \ \_____/ \ \ \_____/ \ \ \_____/ \ \ \_____/ \ \ \_____/
/ / / ___ \_/ / / ___ \_/ / / ___ \_/ / / ___ \_/ / / ___ \_/ / / ___ \_
_/ / / _ \___/ / / _ \___/ / / _ \___/ / / _ \___/ / / _ \___/ / / _ \__
__/ / / \_____/ / / \_____/ / / \_____/ / / \_____/ / / \_____/ / / \___
If you find this kind of animation interesting, you can find more examples of "scrolling ASCII art" on my other website, The Scroll Art Museum.
Simple Substitution Cipher
The Simple Substitution Cipher substitutes one letter for another. Since there are 26 possible substitutions for the letter A, 25 possible substitutions for B, 24 for C, and so on, the total number of possible keys is 26 × 25 × 24 × 23 × . . . × 1, or 403,291,461,126,605,635,584,000,000 keys! That’s far too many keys for even a supercomputer to brute force, so the code-breaking method used in Project 7, “Caesar Hacker,” can’t be used against the simple cipher. Unfortunately, devious attackers can take advantage of known weakness to break the code. If you’d like to learn more about ciphers and code breaking, you can read my book Cracking Codes with Python (No Starch Press, 2018; https://nostarch.com/crackingcodes/).
For example, when the program runs it could look like this:
Do you want to (e)ncrypt or (d)ecrypt?
> e
Please specify the key to use.
Or enter RANDOM to have one generated for you.
> random
The key is WNOMTRCEHDXBFVSLKAGZIPYJQU. KEEP THIS SECRET!
Enter the message to encrypt.
> Meet me by the rose bushes tonight.
The encrypted message is:
Fttz ft nq zet asgt nigetg zsvhcez.
Full encrypted text copied to clipboard.
--snip--
Do you want to (e)ncrypt or (d)ecrypt?
> d
Please specify the key to use.
> WNOMTRCEHDXBFVSLKAGZIPYJQU
Enter the message to decrypt.
> Fttz ft nq zet asgt nigetg zsvhcez.
The decrypted message is:
Meet me by the rose bushes tonight.
Full decrypted text copied to clipboard.
Sine Message
This program displays a message of the user’s choice in a wavy pattern as the text scrolls up. It accomplishes this effect with math.sin()
, which implements the trigonometric sine wave function. But even if you don’t understand the math, this program is rather short and easy to copy.
For example, when the program runs it could look like this:
What message do you want to display? (Max 39 chars.)
> I <3 Programming!
I <3 Programming!
I <3 Programming!
I <3 Programming!
I <3 Programming!
I <3 Programming!
I <3 Programming!
I <3 Programming!
I <3 Programming!
I <3 Programming!
I <3 Programming!
I <3 Programming!
I <3 Programming!
I <3 Programming!
I <3 Programming!
I <3 Programming!
I <3 Programming!
I <3 Programming!
I <3 Programming!
I <3 Programming!
I <3 Programming!
I <3 Programming!
I <3 Programming!
I <3 Programming!
--snip--
Sliding Tile Puzzle
This classic puzzle relies on a 4 × 4 board with 15 numbered tiles and one free space. The objective is to slide the tiles until the numbers are in the correct order, going left to right and top to bottom. Tiles can only slide; you’re not allowed to directly pick them up and rearrange them. Some versions of this puzzle toy feature scrambled images that form a complete picture once solved.
For example, when the program runs it could look like this:
+------+------+------+------+
| | | | |
| 5 | 10 | | 11 |
| | | | |
+------+------+------+------+
| | | | |
| 6 | 3 | 7 | 2 |
| | | | |
+------+------+------+------+
| | | | |
| 14 | 1 | 15 | 8 |
| | | | |
+------+------+------+------+
| | | | |
| 9 | 13 | 4 | 12 |
| | | | |
+------+------+------+------+
(W)
Enter WASD (or QUIT): (A) ( ) (D)
> w
+------+------+------+------+
| | | | |
| 5 | 10 | 7 | 11 |
| | | | |
+------+------+------+------+
| | | | |
| 6 | 3 | | 2 |
| | | | |
+------+------+------+------+
| | | | |
| 14 | 1 | 15 | 8 |
| | | | |
+------+------+------+------+
| | | | |
| 9 | 13 | 4 | 12 |
| | | | |
+------+------+------+------+
(W)
Enter WASD (or QUIT): (A) (S) (D)
--snip--
Snail Race
You won’t be able to handle the fast-paced excitement of these racing... snails. But what they lack in speed they make up for in ASCII-art cuteness. Each snail (represented by an @
character for the shell and v
for the two eyestalks) moves slowly but surely toward the finish line. Up to eight snails, each with a custom name, can race each other, leaving a slime trail in their wake. This program is good for beginners.
For example, when the program runs it could look like this:
Snail Race
@v <-- snail
How many snails will race? Max: 8
> 3
Enter snail #1's name:
> Alice
Enter snail #2's name:
> Bob
Enter snail #3's name:
> Carol
START FINISH
| |
Alice
......@v
Bob
.....@v
Carol
.......@v
--snip--
Soroban Japanese Abacus
An abacus, also called a counting frame, is a calculating tool used in many cultures long before electronic calculators were invented. The Japanese form of the abacus is called a soroban. Each wire represents a place in a positional numeral system, and the beads on the wire represent the digit at that place. For example, a soroban with two beads moved over on the rightmost wire and three beads moved over on the second-to-rightmost wire would represent the number 32. This program simulates a soroban. (The irony of using a computer to simulate a pre-computer computing tool is not lost on me.)
Each column in the soroban represents a different digit. The rightmost column is the ones place, the column to its left is the tens place, the column to the left of that is the hundreds place, and so on. The Q, W, E, R, T, Y, U, I, O, and P keys along the top of your keyboard can increase the digit at their respective positions, while the A, S, D, F, G, H, J, K, L, and ; keys will decrease them. The beads on the virtual soroban will slide to reflect the current number. You can also enter numbers directly.
The four beads below the horizontal divider are “earth” beads, and lifting them up against the divider counts as 1 for that digit. The bead above the horizontal divider is a “heaven” bead, and pulling it down against the divider counts as 5 for that digit, so pulling down one heaven bead and pulling up three earth beads in the tens column represents the number 80. More information about abacuses and how to use them can be found at https://en.wikipedia.org/wiki/Abacus.
For example, when the program runs it could look like this:
+================================+
I O O O O O O O O O O I
I | | | | | | | | | | I
I | | | | | | | | | | I
+================================+
I | | | | | | | | | | I
I | | | | | | | | | | I
I O O O O O O O O O O I
I O O O O O O O O O O I
I O O O O O O O O O O I
I O O O O O O O O O O I
+==0==0==0==0==0==0==0==0==0==0==+
+q w e r t y u i o p
-a s d f g h j k l ;
(Enter a number, "quit", or a stream of up/down letters.)
> pppiiiii
+================================+
I O O O O O O O | O O I
I | | | | | | | | | | I
I | | | | | | | O | | I
+================================+
I | | | | | | | | | O I
I | | | | | | | | | O I
I O O O O O O O O O O I
I O O O O O O O O O | I
I O O O O O O O O O | I
I O O O O O O O O O O I
+==0==0==0==0==0==0==0==5==0==3==+
+q w e r t y u i o p
-a s d f g h j k l ;
(Enter a number, "quit", or a stream of up/down letters.)
--snip--
Sound Mimic
Similar to the Simon electronic toy, this memorization game uses the third-party playsound module to play four different sounds, which correspond to the A, S, D, and F keys on the keyboard. As you successfully repeat the pattern the game gives you, the patterns get longer and longer. How many sounds can you hold in your short-term memory?
If you look at the code, you’ll see that the playsound.playsound() function is passed the filename of the sound to play. You can download the sound files from these URLs:
https://inventwithpython.com/soundA.wav
https://inventwithpython.com/soundS.wav
https://inventwithpython.com/soundD.wav
https://inventwithpython.com/soundF.wav
For example, when the program runs it could look like this:
Try to memorize a pattern of A S D F letters (each with its own sound)
as it gets longer and longer.
Press Enter to begin...
<screen clears>
Pattern: S
<screen clears>
Enter the pattern:
> s
Correct!
<screen clears>
Pattern: S F
<screen clears>
Enter the pattern:
> sf
Correct!
<screen clears>
Pattern: S F F
<screen clears>
Enter the pattern:
> sff
Correct!
<screen clears>
Pattern: S F F D
--snip--
sPoNgEcAsE
You’ve probably seen the “Mocking SpongeBob” meme: a picture of SpongeBob SquarePants, with a caption whose text alternates between upper- and lowercase letters to indicate sarcasm, like this: uSiNg SpOnGeBoB MeMeS dOeS NoT mAkE YoU wItTy. For some randomness, the text sometimes doesn’t alternate capitalization.
For example, when the program runs it could look like this:
eNtEr YoUr MeSsAgE:
> Using SpongeBob memes does not make you witty.
uSiNg SpOnGeBoB MeMeS dOeS NoT mAkE YoU wItTy.
(cOpIed SpOnGeTexT to ClIpbOaRd.)
Sudoku Puzzle
Sudoku is a popular puzzle game in newspapers and mobile apps. The Sudoku board is a 9 × 9 grid in which the player must place the digits 1 to 9 once, and only once, in each row, column, and 3 × 3 subgrid. The game begins with a few spaces already filled in with digits, called givens. A well-formed Sudoku puzzle will have only one possible valid solution.
For example, when the program runs it could look like this:
--snip--
A B C D E F G H I
1 . . . | . . . | . . .
2 . 7 9 | . 5 . | 1 8 .
3 8 . . | . . . | . . 7
------+-------+------
4 . . 7 | 3 . 6 | 8 . .
5 4 5 . | 7 . 8 | . 9 6
6 . . 3 | 5 . 2 | 7 . .
------+-------+------
7 7 . . | . . . | . . 5
8 . 1 6 | . 3 . | 4 2 .
9 . . . | . . . | . . .
Enter a move, or RESET, NEW, UNDO, ORIGINAL, or QUIT:
(For example, a move looks like "B4 9".)
--snip--
Text To Speech Talker
This program demonstrates the use of the pyttsx3 third-party module. Any message you enter will be spoken out loud by your operating system’s text-to-speech capabilities. Although computer-generated speech is an incredibly complex branch of computer science, the pyttsx3 module provides an easy interface for it, making this small program suitable for beginners. Once you’ve learned how to use the module, you can add generated speech to your own programs.
More information about the pyttsx3 module can be found at https://pypi.org/project/pyttsx3/.
For example, when the program runs it could look like this:
Text-to-speech using the pyttsx3 module, which in turn uses
the NSSpeechSynthesizer (on macOS), SAPI5 (on Windows), or
eSpeak (on Linux) speech engines.
Enter the text to speak, or QUIT to quit.
> Hello. My name is Guido van Robot.
<computer speaks text out loud>
> quit
Thanks for playing!
Three-Card Monte
Three-card monte is a common scam played on gullible tourists and other easy marks. Three playing cards, one of which is the “red lady” Queen of Hearts, are put facedown on a cardboard box. The dealer quickly rearranges the cards and then asks the mark to pick the Queen of Hearts. But the dealer can use all sorts of tricks to hide the card or otherwise cheat, guaranteeing that the victim never wins. It’s also common for the dealer to have shills in the crowd who secretly work with the dealer but pretend to win the game (to make the victim think they too could win) or purposefully lose badly (to make the victim think they could do much better).
This program shows the three cards and then quickly describes a series of swaps. At the end, it clears the screen, and the player must pick a card. Can you keep up with the “red lady”? For the authentic three-card monte experience, you can enable the cheat feature, which causes the player to always lose, even if they select the correct card.
For example, when the program runs it could look like this:
Find the red lady (the Queen of Hearts)! Keep an eye on how
the cards move.
Here are the cards:
___ ___ ___
|J | |Q | |8 |
| ♦ | | ♥ | | ♣ |
|__J| |__Q| |__8|
Press Enter when you are ready to begin...
swapping left and middle...
swapping right and middle...
swapping middle and left...
swapping right and left...
swapping left and middle...
--snip--
<screen clears>
Which card has the Queen of Hearts? (LEFT MIDDLE RIGHT)
> middle
___ ___ ___
|Q | |8 | |J |
| ♥ | | ♣ | | ♦ |
|__Q| |__8| |__J|
You lost!
Thanks for playing, sucker!
Tic-Tac-Toe
Tic-tac-toe is a classic pencil-and-paper game played on a 3 × 3 grid. Players take turns placing their X or O marks, trying to get three in a row. Most games of tic-tac-toe end in a tie, but it is possible to outsmart your opponent if they’re not careful.
For example, when the program runs it could look like this:
Welcome to Tic-Tac-Toe!
| | 1 2 3
-+-+-
| | 4 5 6
-+-+-
| | 7 8 9
What is X's move? (1-9)
> 1
X| | 1 2 3
-+-+-
| | 4 5 6
-+-+-
| | 7 8 9
What is O's move? (1-9)
--snip--
X|O|X 1 2 3
-+-+-
X|O|O 4 5 6
-+-+-
O|X|X 7 8 9
The game is a tie!
Thanks for playing!
Tower of Hanoi Puzzle
The Tower of Hanoi is a stack-moving puzzle game that features three poles on which you can stack various-sized disks. The object of the game is to move one tower of disks to another pole. However, only one disk can be moved at a time, and larger disks cannot be placed on top of smaller ones. Figuring out a certain pattern will help you solve this puzzle. Can you discover it? (Hint: Try setting the TOTAL_DISKS
variable to 3 or 4 to solve an easier version first.)
For example, when the program runs it could look like this:
The Tower of Hanoi
Move the tower of disks, one disk at a time, to another tower. Larger
disks cannot rest on top of a smaller disk.
More info at https://en.wikipedia.org/wiki/Tower_of_Hanoi
|| || ||
@_1@ || ||
@@_2@@ || ||
@@@_3@@@ || ||
@@@@_4@@@@ || ||
@@@@@_5@@@@@ || ||
A B C
Enter the letters of "from" and "to" towers, or QUIT.
(e.g. AB to moves a disk from tower A to tower B.)
> ab
|| || ||
|| || ||
@@_2@@ || ||
@@@_3@@@ || ||
@@@@_4@@@@ || ||
@@@@@_5@@@@@ @_1@ ||
A B C
Enter the letters of "from" and "to" towers, or QUIT.
(e.g. AB to moves a disk from tower A to tower B.)
--snip--
Twenty Forty Eight
Gabriele Cirulli, a web developer, invented the game 2048 in one weekend. It was inspired by Veewo Studios’ 1024 game, which in turn was inspired by Threes!, a game by the development team Sirvo. In 2048, you must merge numbers on a 4 × 4 board to clear them from the screen. Two 2s merge into a 4, two 4s merge into an 8, and so on. The game adds a new 2 to the board on each merging. The objective is to reach 2048 before the entire board fills up.
For example, when the program runs it could look like this:
--snip--
+-----+-----+-----+-----+
| | | | |
| | | 2 | 16 |
| | | | |
+-----+-----+-----+-----+
| | | | |
| | 16 | 4 | 2 |
| | | | |
+-----+-----+-----+-----+
| | | | |
| 2 | | 4 | 32 |
| | | | |
+-----+-----+-----+-----+
| | | | |
| | | | 2 |
| | | | |
+-----+-----+-----+-----+
Score: 80
Enter move: (WASD or Q to quit)
--snip--
Vigenère Cipher
The Vigenère cipher, misattributed to 19th-century cryptographer Blaise de Vigenère (others had independently invented it earlier), was impossible to crack for hundreds of years. It is essentially the Caesar cipher, except it makes use of a multipart key. The so-called Vigenère key is a word, or even a random series of letters. Each letter represents a number by which to shift the letter in the message: A represents shifting a letter in the message by 0, B represents 1, C represents 2, and so on.
For example, if a Vigenère key is the word “CAT,” the C represents a shift of 2, the A represents 0, and the T represents 19. The first letter of the message gets shifted by 2, the second letter by 0, and the third letter by 19. For the fourth letter, we repeat the key of 2.
For example, when the program runs it could look like this:
The Vigenère cipher is a polyalphabetic substitution cipher that was
powerful enough to remain unbroken for centuries.
Do you want to (e)ncrypt or (d)ecrypt?
> e
Please specify the key to use.
It can be a word or any combination of letters:
> PIZZA
Enter the message to encrypt.
> Meet me by the rose bushes tonight.
Encrypted message:
Bmds mt jx sht znre qcrgeh bnmivps.
Full encrypted text copied to clipboard.
If you’d like to learn more about ciphers and code breaking, you can read my book Cracking Codes with Python (No Starch Press, 2018; https://nostarch.com/crackingcodes/).
Water Bucket Puzzle
In this solitaire puzzle game, you must use three buckets (three-liter, five-liter, and eight-liter buckets) to collect exactly four liters of water in one of the buckets. Buckets can only be emptied, completely filled, or poured into another bucket. For example, you can fill the five-liter bucket and then pour its contents into the three-liter bucket, leaving you with a full three-liter bucket and two liters of water in the five-liter bucket.
With some effort, you should be able to solve the puzzle. But can you figure out how to solve it with the minimal number of moves?
For example, when the program runs it could look like this:
Try to get 4L of water into one of these
buckets:
8| |
7| |
6| |
5| | 5| |
4| | 4| |
3| | 3| | 3| |
2| | 2| | 2| |
1| | 1| | 1| |
+------+ +------+ +------+
8L 5L 3L
You can:
(F)ill the bucket
(E)mpty the bucket
(P)our one bucket into another
(Q)uit
> f
Select a bucket 8, 5, 3, or QUIT:
> 5
Try to get 4L of water into one of these
buckets:
8| |
7| |
6| |
5| | 5|WWWWWW|
4| | 4|WWWWWW|
3| | 3|WWWWWW| 3| |
2| | 2|WWWWWW| 2| |
1| | 1|WWWWWW| 1| |
+------+ +------+ +------+
8L 5L 3L
--snip--
Sonar Treasure Hunt
In Sonar Treasure Hunt, the player tries to discover the position of 3 treasure chests in the sea, and the player has only 20 sonar devices to use to find them. When placed, they give the distance to the closest chest.
For example, when the program runs it could look like this:
1 2 3 4 5
012345678901234567890123456789012345678901234567890123456789
0 ~`~``~``~``~`~`~```~`~``````~```~`~~~`~~```~~`~~~~~`~~`~~~~` 0
1 ~~~~~`~~~~~````~``~~```~``~`~`~`~``~~```~~~`~`~```~~~~`~`~~` 1
2 ```~````~``~`~`~~~``~~`````~~``~``~``~~```~~``~~`~~~````~~`~ 2
3 `````~~``````~`~~~~~```~~``~~~`~`~~~~~~`````~`~```~~~``~``~` 3
4 ~~~`~~~`~`~~~``~~~`~`~``~~~~``~~~~``~~~~`~`~``~~```~``~~`~`~ 4
5 `~``~````~`~`~~``~~~~``````~```~~~~````````~``~~~`~~``~~```` 5
6 ~`~```~~`~~```~````````~~```~```~~~~``~~~`~`~~`~``~~~`~~`~`` 6
7 ~`~~~```~``~```~`~```~~~~~~~`~~`~`~~~~``~```~~~`~```~``~``~` 7
8 `~``~~`~`~~`~~`~~``~```~````~`~```~``~````~~~````~~``~~``~~` 8
9 ~`~``~~````~~```~`~~```~~`~``~`~~``~`~`~~~~`~`~~`~`~```~~``` 9
10 `~~~~~~`~``~``~~~``~``~~~~`~``~```~`~~``~~~~~~``````~~`~``~~ 10
11 ~``~~~````~`~~`~~~`~~~``~``````~`~``~~~~`````~~~``````~`~`~~ 11
12 ~~~~~``~`~````~```~`~`~`~~`~~`~``~~~~~~~`~~```~~``~~`~~~~``` 12
13 `~~```~~````````~~~`~~~```~~~~~~~~`~~``~~`~```~`~~````~~~``~ 13
14 ```~``~`~`~``~```~`~``~`~``~~```~`~~~``~~``~```~`~~`~``````~ 14
012345678901234567890123456789012345678901234567890123456789
1 2 3 4 5
You have 20 sonar device(s) left. 3 treasure chest(s) remaining.
Where do you want to drop the next sonar device? (0-59 0-14) (or type quit)
25 5
1 2 3 4 5
012345678901234567890123456789012345678901234567890123456789
0 ~`~``~``~``~`~`~```~`~``````~```~`~~~`~~```~~`~~~~~`~~`~~~~` 0
1 ~~~~~`~~~~~````~``~~```~``~`~`~`~``~~```~~~`~`~```~~~~`~`~~` 1
2 ```~````~``~`~`~~~``~~`````~~``~``~``~~```~~``~~`~~~````~~`~ 2
3 `````~~``````~`~~~~~```~~``~~~`~`~~~~~~`````~`~```~~~``~``~` 3
4 ~~~`~~~`~`~~~``~~~`~`~``~~~~``~~~~``~~~~`~`~``~~```~``~~`~`~ 4
5 `~``~````~`~`~~``~~~~````5`~```~~~~````````~``~~~`~~``~~```` 5
6 ~`~```~~`~~```~````````~~```~```~~~~``~~~`~`~~`~``~~~`~~`~`` 6
7 ~`~~~```~``~```~`~```~~~~~~~`~~`~`~~~~``~```~~~`~```~``~``~` 7
8 `~``~~`~`~~`~~`~~``~```~````~`~```~``~````~~~````~~``~~``~~` 8
9 ~`~``~~````~~```~`~~```~~`~``~`~~``~`~`~~~~`~`~~`~`~```~~``` 9
10 `~~~~~~`~``~``~~~``~``~~~~`~``~```~`~~``~~~~~~``````~~`~``~~ 10
11 ~``~~~````~`~~`~~~`~~~``~``````~`~``~~~~`````~~~``````~`~`~~ 11
12 ~~~~~``~`~````~```~`~`~`~~`~~`~``~~~~~~~`~~```~~``~~`~~~~``` 12
13 `~~```~~````````~~~`~~~```~~~~~~~~`~~``~~`~```~`~~````~~~``~ 13
14 ```~``~`~`~``~```~`~``~`~``~~```~`~~~``~~``~```~`~~`~``````~ 14
This program is from Invent Your Own Computer Games with Python.
Reversegam / Reversi / Othello
Reversegam, also known as Reversi or Othello. This two-player board game is played on a grid, so we’ll use a Cartesian coordinate system with x- and y-coordinates. This AI is so good that it will probably beat you almost every time you play. (I lose whenever I play against it!)
For example, when the program runs it could look like this:
Do you want to be X or O?
x
The player will go first.
12345678
+--------+
1| |1
2| |2
3| |3
4| XO |4
5| OX |5
6| |6
7| |7
8| |8
+--------+
12345678
You: 2 points. Computer: 2 points.
Enter your move, "quit" to end the game, or "hints" to toggle hints.
53
12345678
+--------+
1| |1
2| |2
3| X |3
4| XX |4
5| OX |5
6| |6
7| |7
8| |8
+--------+
12345678
You: 4 points. Computer: 1 points.
Press Enter to see the computer's move.
--snip--
This program is from Invent Your Own Computer Games with Python.
Transposition Cipher
The transposition cipher is more difficult to brute-force because the number of possible keys depends on the message’s length. There are many different types of transposition ciphers, including the rail fence cipher, route cipher, Myszkowski transposition cipher, and disrupted transposition cipher. This program is the columnar transposition cipher.
The transposition cipher doesn't replace characters when it encrypts them, but rather scrambles their order in such a way that can only be decrypted if you have the right key.
This program is from Cracking Codes with Python.
Transposition Cipher Hacker / English Detection
Hacking the transposition cipher is a matter of running through the many keys and finding the key that decrypts to detectable English. You'll need a program that uses a dictionary file (which you can download from the No Starch Press page for my book)
This program is from Cracking Codes with Python.
Affine Cipher
Once you learned the basics of modular arithmetic, you can create an affine cipher program. The affine cipher is similar to the Caesar cipher, but it's more complicated key generation makes it more secure. Still, it is possible to hack the affine cipher
This program is from Cracking Codes with Python.
Frequency Analysis / Vigenere Cipher Hacker
Writing programs that can determine the letter frequencies in messages is the first step towards hacking the Vigenere cipher. This approach was used by 19th-century mathematician Charles Babbage to break the previously-thought unbreakable Vigenere cipher.
This program is from Cracking Codes with Python.
Public Key Cryptography / Large Prime Number Generation
Public-key cryptography uses pairs of encryption keys. Each key pair consists of a public key and a corresponding private key. Security of public-key cryptography depends on keeping the private key secret; the public key can be openly distributed without compromising security.
You'll need to generate large prime numbers to use during key generation. While the math is a little tricky, this is how real-world cryptography works. (Though the programs you make are not suitable for actual use; they're great for a learning exercise though.)
For example, running the public key encryption keys could look like this:
Making key files...
Generating p prime...
Generating q prime...
Generating e that is relatively prime to (p-1)*(q-1)...
Calculating d that is mod inverse of e...
Public key: (210902406316700502401968491406579417405090396754616926135810621
2161161913380865678407459875355468897928072386270510720443827324671435893274
8583937496850624116776147241821152026946322876869404394483922202407821672864
2424789208131826990008473526711744296548563866768454251404951960805224682425
498975230488955908086491852116348777849536270685085446970952915640050522212
204221803744494065881010331486468305317449607027884787770315729959789994713
265311327663776167710077018340036668306612665759417207845823479903440572724
068125211002329298338718615859542093721097258263595617482450199200740185492
04468791300114315056117093, 17460230769175161021731845459236833553832403910869
129054954200373678580935247606622265764388235752176654737805849023006544732896
308685513669509917451195822611398098951306676600958889189564599581456460070270
393693277683404354811575681605990659145317074127084557233537504102479937142530
0216777273298110097435989)
Private key: (21090240631670050240196849140657941740509039675461692613581062
1216116191338086567840745987535546889792807238627051072044382732467143589327
4858393749685062411677614724182115202694632287686940439448392220240782167286
4242478920813182699000847352671174429654856386676845425140495196080522468242
5498975230488955908086491852116348777849536270685085446970952915640050522212
204221803744494065881010331486468305317449607027884787770315729959789994713
265311327663776167710077018340036668306612665759417207845823479903440572724
068125211002329298338718615859542093721097258263595617482450199200740185492
04468791300114315056117093, 47676735798137710412166884916983765043173120289416
904341295971552286870991874666099933371008075948549008551224760695942666962465
968168995404993934508399014283053710676760835948902312888639938402686187075052
360773062364162664276144965652558545331166681735980981384493349313058750259417
68372702963348445191139635826000818122373486213256488077192893119257248107794
25681884603640028673273135292831170178614206817165802812291528319562200625082
55726168047084560706359601833919317974375031636011432177696164717000025430368
26990539739057474642785416933878499897014777481407371328053001838085314443545
845219087249544663398589)
The public key is a 617 and a 309 digit number.
Writing public key to file al_sweigart_pubkey.txt...
The private key is a 617 and a 309 digit number.
Writing private key to file al_sweigart_privkey.txt...
This program is from Cracking Codes with Python.