A L S W E I G A R T T H E B I G B O O K O F S M A L L P Y T H O N P R O J E C T S 8 1 E A S Y P R A C T I C E P R O G R A M S
(This page has no text content)
THE BIG BOOK OF SMALL PYTHON PROJECTS
(This page has no text content)
San Francisco Al Sweigar t T H E B I G B O O K O F S M A L L P Y T H O N P R O J E C T S 8 1 E a s y P r a c t i c e P r o g r a m s
THE BIG BOOK OF SMALL PYTHON PROJECTS. Copyright © 2021 by Al Sweigart. All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN-13: 978-1-7185-0124-9 (print) ISBN-13: 978-1-7185-0125-6 (ebook) Publisher: William Pollock Production Manager: Rachel Monaghan Production Editor: Paula Williamson Developmental Editor: Frances Saux Technical Reviewer: Sarah Kuchinsky Cover and Interior Design: Octopod Studios Cover Illustrator: Josh Ellingson Copyeditor: Bart Reed Compositor: Maureen Forys, Happenstance Type-O-Rama Proofreader: Scout Festa For information on book distributors or translations, please contact No Starch Press, Inc. directly: No Starch Press, Inc. 245 8th Street, San Francisco, CA 94103 phone: 1-415-863-9900; info@nostarch.com www.nostarch.com Library of Congress Control Number: 2021936413 No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other product and company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of this work, neither the author nor No Starch Press, Inc. shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it.
About the Author Al Sweigart is a software developer, author, and Fellow of the Python Software Foundation. He was previously the education director at Oakland, California’s video game museum, The Museum of Art and Digital Enter- tainment. He has written several programming books, including Automate the Boring Stuff with Python and Invent Your Own Computer Games with Python. His books are freely available under a Creative Commons license at his website https://inventwithpython.com. His cat Zophie loves eating nori seaweed snacks. About the Technical Reviewer Sarah Kuchinsky, MS, is a corporate trainer and consultant. She uses Python for a variety of applications, including health systems modeling, game development, and task automation. Sarah is a co-founder of the North Bay Python conference, tutorials chair for PyCon US, and lead organizer for PyLadies Silicon Valley. She holds degrees in Management Science & Engineering and Mathematics.
(This page has no text content)
C O N T E N T S I N D E T A I L Introduction xv Project 1, Bagels: Deduce a secret three-digit number based on clues. 1 Practice using constants. Project 2, Birthday Paradox: Determine the probability that two people share the same birthday in groups of different sizes. 6 Use Python’s datetime module. Project 3, Bitmap Message: Display a message on the screen configured by a 2D bitmap image. 11 Work with multiline strings. Project 4, Blackjack: A classic card game played against an AI dealer. 15 Learn about Unicode characters and code points. Project 5, Bouncing DVD Logo: Simulates the colorful bouncing DVD logo of decades past. 23 Work with coordinates and colorful text. Project 6, Caesar Cipher: A simple encryption scheme used thousands of years ago. 29 Convert between letters and numbers to perform math on text. Project 7, Caesar Hacker: A program to decrypt Caesar cipher messages without the encryption key. 33 Implement a brute-force cryptanalysis algorithm. Project 8, Calendar Maker: Create calendar pages for a given year and month. 36 Use Python’s datetime module and the timedelta data type. Project 9, Carrot in a Box: A silly bluffing game between two players. 41 Create ASCII art. Project 10, Cho-Han: A gambling dice game from feudal Japan. 47 Practice using random numbers and dictionary data structures.
viii Contents in Detail Project 11, Clickbait Headline Generator: A humorous headline generator for your content farm. 51 Practice string manipulation and text generation. Project 12, Collatz Sequence: Explore the simplest impossible conjecture in mathematics. 56 Learn about the modulus operator. Project 13, Conway’s Game of Life: The classic cellular automata whose simple rules produce complex emergent behavior. 59 Use dictionary data structures and screen coordinates. Project 14, Countdown: A countdown timer with a seven-segment display. 63 Practice importing modules you create. Project 15, Deep Cave: A tunnel animation that descends endlessly into the earth. 66 Use string replication and simple math. Project 16, Diamonds: An algorithm for drawing diamonds of various sizes. 69 Practice your pattern recognition skills to create drawing algorithms. Project 17, Dice Math: A visual dice-rolling math game. 73 Use dictionary data structures for screen coordinates. Project 18, Dice Roller: A tool for reading Dungeons & Dragons dice notation to generate random numbers. 79 Parse text to identify key strings. Project 19, Digital Clock: A clock with a calculator-like display. 83 Generate numbers that match information from the datetime module. Project 20, Digital Stream: A scrolling screensaver that resembles The Matrix. 86 Experiment with different animation speeds. Project 21, DNA Visualization: An endless ASCII-art double helix that demonstrates the structure of DNA. 90 Work with string templates and randomly generated text. Project 22, Ducklings: Mix and match strings to create a variety of ASCII-art ducks. 94 Use object-oriented programming to create a data model for duck drawings.
Contents in Detail ix Project 23, Etching Drawer: Move the cursor to create line drawings. 100 Work with screen coordinates and relative directional movements. Project 24, Factor Finder: Find all the multiplicative factors of a number. 106 Use the modulus operator and Python’s math module. Project 25, Fast Draw: Test your reflexes to see if you’re the fastest keyboard in the West. 110 Learn about the keyboard buffer. Project 26, Fibonacci: Generate numbers in the famous Fibonacci sequence. 113 Implement a rudimentary mathematics algorithm. Project 27, Fish Tank: A colorful, animated ASCII-art fish tank. 117 Use screen coordinates, text colors, and data structures. Project 28, Flooder: Attempt to fill the entire puzzle board with one color. 125 Implement the flood fill algorithm. Project 29, Forest Fire Sim: Simulate the spread of wildfires through a forest. 132 Create a simulation with adjustable parameters. Project 30, Four in a Row: A board game where two players try to connect four tiles in a row. 137 Create a data structure that mimics gravity. Project 31, Guess the Number: The classic number guessing game. 143 Program basic concepts for beginners. Project 32, Gullible: A humorous program to keep gullible people busy for hours. 147 Use input validation and loops. Project 33, Hacking Minigame: Deduce a password based on clues. 150 Add cosmetic features to make a basic game more interesting. Project 34, Hangman and Guillotine: The classic word guessing game. 156 Use string manipulation and ASCII art. Project 35, Hex Grid: Programmatically generate tiled ASCII art. 162 Use loops to make repeating text patterns.
x Contents in Detail Project 36, Hourglass: A simple physics engine for falling sand. 165 Simulate gravity and use collision detection. Project 37, Hungry Robots: Avoid killer robots in a maze. 171 Create a simple AI for robot movements. Project 38, J’Accuse!: A detective game to determine liars and truth-tellers. 178 Use data structures to generate relationships between suspects, places, and item clues. Project 39, Langton’s Ant: A cellular automata whose ants move according to simple rules. 186 Explore how simple rules create complex graphical patterns. Project 40, Leetspeak: Translate English messages into l33t5p34]<. 192 Use text parsing and string manipulation. Project 41, Lucky Stars: A push-your-luck dice game. 195 Practice ASCII art and probability. Project 42, Magic Fortune Ball: A program to answer your yes/no questions about the future. 202 Add cosmetic features to make basic text appear more interesting. Project 43, Mancala: The ancient two-player board game from Mesopotamia. 206 Use ASCII art and string templates to draw a board game. Project 44, Maze Runner 2D: Try to escape a maze. 213 Read maze data from text files. Project 45, Maze Runner 3D: Try to escape a maze . . . in 3D! 219 Modify multiline strings to display a 3D view. Project 46, Million Dice Roll Statistics Simulator: Explore the probability results of rolling a set of dice one million times. 228 Learn how computers crunch large quantities of numbers. Project 47, Mondrian Art Generator: Create geometric drawings in the style of Piet Mondrian. 231 Implement an art-generating algorithm. Project 48, Monty Hall Problem: A simulation of the Monty Hall game show problem. 238 Examine probability with ASCII-art goats.
Contents in Detail xi Project 49, Multiplication Table: Display the multiplication table up to 12 × 12. 245 Practice spacing text. Project 50, Ninety-Nine Bottles: Display the lyrics to a repetitive song. 248 Use loops and string templates to produce text. Project 51, niNety-nniinE BoOttels: Display the lyrics to a repetitive song that get more distorted with each verse. 251 Manipulate strings to introduce distortions. Project 52, Numeral Systems Counters: Examine binary and hexadecimal numbers. 255 Use Python’s number conversion functions. Project 53, Periodic Table of the Elements: An interactive database of chemical elements. 259 Parse CSV files to load data into a program. Project 54, Pig Latin: Translates English messages into Igpay Atinlay. 263 Use text parsing and string manipulation. Project 55, Powerball Lottery: Simulate losing at the lottery thousands of times. 267 Explore probability using random numbers. Project 56, Prime Numbers: Calculate prime numbers. 272 Learn math concepts and use Python’s math module. Project 57, Progress Bar: A sample progress bar animation to use in other programs. 275 Use the backspace-printing technique to create animations. Project 58, Rainbow: A simple rainbow animation. 279 Create animation for beginners. Project 59, Rock Paper Scissors: The classic hand game for two players. 282 Implement basic game rules as a program. Project 60, Rock Paper Scissors (Always-Win Version): A version of the game where the player cannot lose. 286 Create the illusion of randomness in a program.
xii Contents in Detail Project 61, ROT13 Cipher: The simplest cipher for encrypting and decrypting text. 290 Convert between letters and numbers to perform math on text. Project 62, Rotating Cube: A rotating cube animation. 293 Learn 3D rotation and line drawing algorithms. Project 63, Royal Game of Ur: A 5,000-year-old game from Mesopotamia. 300 Use ASCII art and string templates to draw a board game. Project 64, Seven-Segment Display Module: A display like those used in calculators and microwave ovens. 308 Create modules for use in other programs. Project 65, Shining Carpet: Programmatically generate the carpet from The Shining. 312 Use loops to make repeating text patterns. Project 66, Simple Substitution Cipher: An encryption scheme more advanced than the Caesar cipher. 315 Perform intermediate math on text. Project 67, Sine Message: Display a scrolling wave message. 320 Use a trigonometry function for animation. Project 68, Sliding Tile Puzzle: The classic four-by-four tile puzzle. 323 Employ a data structure to reflect the state of a game board. Project 69, Snail Race: Fast-paced snail racing action! 329 Calculate spacing for ASCII art snails. Project 70, Soroban Japanese Abacus: A computer simulation of a pre-computer calculating tool. 333 Use string templates to create an ASCII-art counting tool. Project 71, Sound Mimic: Memorize an increasingly long pattern of sounds. 339 Play sound files from a Python program. Project 72, sPoNgEcAsE: Translates English messages into sPOnGEcAsE. 343 Change the casing of letters in strings.
Contents in Detail xiii Project 73, Sudoku Puzzle: The classic nine-by-nine newspaper deduction puzzle. 346 Model a puzzle with a data structure. Project 74, Text-to-Speech Talker: Make your computer talk to you! 353 Use your operating system’s text-to-speech engine. Project 75, Three-Card Monte: The tricky fast-swapping card game that scammers play on tourists. 356 Manipulate a data structure based on random movements. Project 76, Tic-Tac-Toe: The classic two-player board game of Xs and Os. 361 Create a data structure and helper functions. Project 77, Tower of Hanoi: The classic disk- stacking puzzle. 365 Use stack data structures to simulate a puzzle state. Project 78, Trick Questions: A quiz of simple questions with misleading answers. 370 Parse the user’s text to recognize keywords. Project 79, Twenty Forty-Eight: A casual tile matching game. 377 Simulate gravity to make tiles “fall” in arbitrary directions. Project 80, Vigenère Cipher: An encryption scheme so advanced it remained unbreakable for hundreds of years until computers were invented. 385 Perform more advanced math on text. Project 81, Water Bucket Puzzle: Obtain exactly four liters of water by filling and emptying three buckets. 390 Use string templates to generate ASCII art. Appendix A: Tag Index 395 Appendix B: Character Map 398
(This page has no text content)
I N T R O D U C T I O N Programming was so easy when it was just following print('Hello, world!') tutorials. Perhaps you’ve followed a well-structured book or online course for beginners, worked through the exercises, and nodded along with its tech- nical jargon that you (mostly) understood. However, when it came time to leave the nest to write your own programs, maybe you found it hard to fly on your own. You found yourself staring at a blank editor window and unsure of how to get started writing Python programs of your own. The problem is that following a tutorial is great for learning concepts, but that isn’t necessarily the same thing as learning to create original pro- grams from scratch. The common advice given at this stage is to examine the source code of open source software or to work on your own projects, but open source projects aren’t always well documented or especially acces- sible to newcomers. And while it’s motivating to work on your own project, you’re left completely without guidance or structure.
xvi Introduction This book provides you with practice examples of how programming concepts are applied, with a collection of over 80 games, simulations, and dig- ital art programs. These aren’t code snippets; they’re full, runnable Python programs. You can copy their code to become familiar with how they work, experiment with your own changes, and then attempt to re-create them on your own as practice. After a while, you’ll start to get ideas for your own pro- grams and, more importantly, know how to go about creating them. How to Design Small Programs Programming has proven to be a powerful skill, creating billion-dollar tech companies and amazing technological advances. It’s easy to want to aim high with your own software creations, but biting off more than you can chew can leave you with half-finished programs and frustration. However, you don’t need to be a computer genius to code fun and creative programs. The Python programs in this book follow several design principles to aid new programmers in understanding their source code: Small Most of these programs are limited to 256 lines of code and are often significantly shorter. This size limit makes them easier to compre- hend. The choice of 256 is arbitrary, but 256 is also 28, and powers of 2 are lucky programmer numbers. Text based Text is simpler than graphics. Since the source code and program output are both text, it’s easy to trace the cause and effect between print('Thanks for playing!') in the code and Thanks for playing! appearing on the screen. No installation needed Each program is self-contained in a single Python source file with the .py file extension, like tictactoe.py. You don’t need to run an installer program, and you can easily post these pro- grams online to share with others. Numerous There are 81 programs in this book. Between board games, card games, digital artwork, simulations, mathematical puzzles, mazes, and humor programs, you’re bound to find many things you’ll love. Simple The programs have been written to be easy to understand by beginners. Whenever I had to choose between writing code using sophisticated, high-performance algorithms or writing plain, straight- forward code, I’ve chosen the latter every time. The text-based programs may seem old school, but this style of pro- gramming cuts out the distractions and potholes that downloading graph- ics, installing additional libraries, and managing project folders bring. Instead, you can just focus on the code. Who Is This Book For? This book is written for two groups of people. The people in the first group are those who have already learned the basics of Python and programming
Introduction xvii but are still unsure of how to write programs on their own. They may feel that programming hasn’t “clicked” for them. They may be able to solve the practice exercises from their tutorials but still struggle to picture what a complete program “looks like.” By first copying and then later re-creating the games in this book, they’ll be exposed to how the programming con- cepts they’ve learned are assembled into a variety of real programs. The people in the second group are those who are new to program- ming but are excited and a bit adventurous. They want to dive right in and get started making games, simulations, and number-crunching programs right away. They’re fine with copying the code and learning along the way. Or perhaps they already know how to program in another language but are new to Python. While it’s no substitute for a complete introductory Python course, this book contains a brief introduction to Python basics and how to use the debugger to examine the inner workings of a program as it runs. Experienced programmers might have fun with the programs in this book as well, but keep in mind that this book was written for beginners. About This Book While the bulk of this book is dedicated to the featured programs, there are also extra resources with general programming and Python informa- tion. Here’s what’s contained in this book: Projects The 81 projects are too numerous to list here, but each one is a self-contained mini-chapter that includes the project’s name, a description, a sample run of the program’s output, and the source code of the program. There are also suggestions for experimental edits you can make to the code to customize the program. Appendix A: Tag Index Lists all of the projects categorized by their project tags. Appendix B: Character Map A list of character codes for symbols such as hearts, lines, arrows, and blocks that your programs can print. How to Learn from the Programs in This Book This book doesn’t teach Python or programming concepts like a traditional tutorial. It has a learn-by-doing approach, where you’re encouraged to man- ually copy the programs, play with them, and inspect their inner workings by running them under a debugger. The point of this book isn’t to give a detailed explanation of pro- gramming language syntax, but to show solid examples of programs that perform an actual activity, whether it’s a card game, an animation, or explo- ration of a mathematical puzzle. As such, I recommend the following steps: 1. Download the program and run it to see what the program does for yourself.
xviii Introduction 2. Starting from a blank file, copy the code of the game from this book by manually typing it yourself. (Don’t use copy and paste!) 3. Run the program again, and go back and fix any typos or bugs you may have introduced. 4. Run the program under a debugger, so you can carefully execute each line of code one at a time to understand what it does. 5. Find the comments marked with (!) to find code that you can modify and then see how this affects the program the next time you run it. 6. Finally, try to re-create the program yourself from scratch. It doesn’t have to be an exact copy; you can put your own spin on the program. When copying the code from this book, you don’t necessarily have to type the comments (the text at the end of a line following the # symbol), as these are notes for human programmers and are ignored by Python. However, try to write your Python code on the same line numbers as the programs in this book to make comparison between the two easier. If you have trouble finding typos in your program, you can compare your code to the code in this book with the online diff tool at https://inventwithpython.com/ bigbookpython/diff/. Each program has been given a set of tags to describe it, such as board game, simulation, artistic, and two-player. An explanation of each of these tags and a cross-index of tags and projects can be found in Appendix A. The projects are listed in alphabetical order, however. Downloading and Installing Python Python is the name of both the programming language and the inter- preter software that runs your Python code. The Python software is com- pletely free to download and use. You can check if you already have Python installed from a command line window. On Windows, open the Command Prompt program and then enter py --version. If you see output like the fol- lowing, then Python is installed: C:\Users\Al>py --version Python 3.9.1 On macOS and Linux, open the Terminal program and then enter python3 --version. If you see output like the following, then Python is installed: $ python3 --version Python 3.9.1 This book uses Python version 3. Several backward-incompatible changes were made between Python 2 and 3, and the programs in this book require at least Python version 3.1.1 (released in 2009) to run. If you see an error message telling you that Python cannot be found or the version reports Python 2, you can download the latest Python installer for your
Comments 0
Loading comments...
Reply to Comment
Edit Comment