Invent Your Own Computer Games with Python 2nd Edition Al Sweigart Copyright © 2008, 2009, 2010 by Albert Sweigart Some Rights Reserved. "Invent Your Own Computer Games with Python" ("Invent with Python") is licensed under a Creative Commons Attribution-Noncommercial- Share Alike 3.0 United States License. You are free: To Share — to copy, distribute, display, and perform the work To Remix — to make derivative works Under the following conditions: Attribution — You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). (Visibly include the title and author's name in any excerpts of this work.) Noncommercial — You may not use this work for commercial purposes. Share Alike — If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or similar license to this one. This summary is located here: http://creativecommons.org/licenses/by-nc-sa/3.0/us/ Your fair use and other rights are in no way affected by the above. There is a human-readable summary of the Legal Code (the full license), located here: http://creativecommons.org/licenses/by-nc-sa/3.0/us/legalcode Book Version 13 ISBN 978-0-9821060-1-3 2nd Edition For Caro, with more love than I ever knew I had. A Note to Parents and Fellow Programmers Thank your for reading this book. My motivation for writing this book comes from a gap I saw in today's literature for kids interested in learning to program. I started programming when I was 9 years old in the BASIC language with a book similar to this one. During the course of writing this, I've realized how a modern language like Python has made programming far easier and versatile for a new generation of programmers. Python has a gentle learning curve while still being a serious language that is used by programmers professionally. The current crop of programming books for kids that I've seen fell into two categories. First, books that did not teach programming so much as "game creation software" or a dumbed-down languages to make programming "easy" (to the point that it is no longer programming). Or second, they taught programming like a mathematics textbook: all principles and concepts with little application given to the reader. This book takes a different approach: show the source code for games right up front and explain programming principles from the examples. I have also made this book available under the Creative Commons license, which allows you to make copies and distribute this book (or excerpts) with my full permission, as long as attribution to me is left intact and it is used for noncommercial purposes. (See the copyright page.) I want to make this book a gift to a world that has given me so much. Thank you again for reading this book, and feel free to email me any questions or comments. Al Sweigart al@inventwithpython.com The full text of this book is available in HTML or PDF format at: http://inventwithpython.com Dinosaur Comics reproduced with permission. Thanks Ryan! Who is this book for? Programming isn't hard. But it is hard to find learning materials that teach you to do interesting things with programming. Other computer books go over many topics that most newbie coders don't need. This book will teach you how to program your own computer games. You will learn a useful skill and have fun games to show for it! This book is for: Complete beginners who wants to teach themselves computer programming, even if they have no previous experience programming. Kids and teenagers who want to learn computer programming by creating games. Kids as young as 9 or 10 years old should be able to follow along. Adults and teachers who wish to teach others programming. Anyone, young or old, who wants to learn how to program by learning a professional programming language. Table of Contents Source Code Listing hello.py 21 guess.py 30 jokes.py 51 dragon.py 58 buggy.py 83 coinFlips.py 87 hangman.py 103 tictactoe.py 150 truefalsefizz.py 172 bagels.py 184 sonar.py 213 cipher.py 244 reversi.py 261 aisim1.py 292 aisim2.py 294 aisim3.py 299 pygameHelloWorld.py 309 animation.py 324 collisionDetection.py 338 pygameInput.py 348 spritesAndSounds.py 360 dodger.py 371 1 Installing Python 1 Downloading and Installing Python 2 Starting Python 4 How to Use This Book 4 The Featured Programs 5 Line Numbers and Spaces 5 Summary 7 2 The Interactive Shell 8 Some Simple Math Stuff 8 Evaluating Expressions 11 Storing Values in Variables 12 Using More Than One Variable 15 Summary 16 3 Strings, and Your First Program 18 Strings 18 String Concatenation 19 Writing Programs in IDLE's File Editor 20 Hello World! 20 How the "Hello World" Program Works 23 Summary 26 4 Guess the Number 28 The "Guess the Number" Game 28 Sample Run of "Guess the Number" 29 Guess the Number's Source Code 29 The import Statement 31 The random.randint() Function 32 Passing Arguments to Functions 34 Blocks 36 The Boolean Data Type 37 Comparison Operators 37 Conditions 38 Experiment with Booleans, Comparison Operators, and Conditions 38 Looping with While Statements 41 The Player Guesses 41 if Statements 44 Leaving Loops Early with the break Statement 45 Check if the Player Won 46 Summary: What Exactly is Programming? 47 A Web Page for Program Tracing 48 5 Jokes 50 Make the Most of print() 50 Sample Run of Jokes 50 Joke's Source Code 51 Escape Characters 52 Quotes and Double Quotes 53 The end Keyword Argument 54 Summary 55 6 Dragon Realm 56 Introducing Functions 56 Sample Run of Dragon Realm 57 Dragon Realm's Source Code 57 def Statements 60 Boolean Operators 61 Return Values 65 Variable Scope 65 Parameters 68 Where to Put Function Definitions 70 Displaying the Game Results 71 The Colon : 73 Where the Program Really Begins 73 Designing the Program 75 Summary 76 7 Using the Debugger 77 Bugs! 77 Starting the Debugger 78 Stepping 80 The Go and Quit Buttons 81 Stepping Over and Stepping Out 81 Find the Bug 83 Break Points 86 Summary 88 8 Flow Charts 89 How to Play "Hangman" 89 Sample Run of "Hangman" 89 ASCII Art 91 Designing a Program with a Flowchart 92 Creating the Flow Chart 93 Summary: The Importance of Planning Out the Game 100 9 Hangman 102 Hangman's Source Code 103 Multi-line Strings 107 Constant Variables 108 Lists 108 Changing the Values of List Items with Index Assignment 110 List Concatenation 110 The in Operator 111 Removing Items from Lists with del Statements 112 Lists of Lists 113 Methods 114 The reverse() and append() List Methods 115 The Difference Between Methods and Functions 116 The split() Function 116 The range() and list() Functions 120 for Loops 121 elif ("Else If") Statements 127 Review of the Functions We Defined 131 Making New Changes to the Hangman Program 132 Dictionaries 139 Sets of Words for Hangman 142 The random.choice() Function 143 Multiple Assignment 145 Summary 147 10 Tic Tac Toe 148 Sample Run of Tic Tac Toe 149 Source Code of Tic Tac Toe 150 Designing the Program 154 Game AI 156 List References 162 Short-Circuit Evaluation 170 The None Value 175 Summary: Creating Game-Playing Artificial Intelligences 182 11 Bagels 183 Sample Run 184 Bagel's Source Code 184 Designing the Program 186 The random.shuffle() Function 188 Augmented Assignment Operators 190 The sort() List Method 192 The join() String Method 192 String Interpolation 194 Summary: Getting Good at Bagels 198 12 Cartesian Coordinates 200 Grids and Cartesian Coordinates 201 Negative Numbers 202 Math Tricks 204 Absolute Values and the abs() Function 206 Coordinate System of a Computer Monitor 207 Summary: Using this Math in Games 208 13 Sonar Treasure Hunt 209 Sample Run 210 Sonar's Source Code 213 Designing the Program 218 The remove() List Method 229 Summary: Review of our Sonar Game 238 14 Caesar Cipher 239 About Cryptography 239 The Caesar Cipher 240 ASCII, and Using Numbers for Letters 241 The chr() and ord() Functions 242 Sample Run of Caesar Cipher 243 Caesar Cipher's Source Code 244 The isalpha() String Method 247 The isupper() and islower() String Methods 248 [...]... installed at the same time.) To download Python 3, go to http:/ /python. org/download/releases/3.1.1/ and install this version hello.py This code can be downloaded from http://inventwithpython.com/hello.py If you get errors after typing this code in, compare it to the book's code with the online diff tool at http://inventwithpython.com/diff or email the author at al@inventwithpython.com 1 # This program says... "installing Python on Programs > Python 3.1 > IDLE (Python GUI)... useful computer skill, especially for computer programming There is a video tutorial on copying and pasting at this book's website at http://inventwithpython.com/videos/ The online diff tool is at this web page: http://inventwithpython.com/diff A video 6 1 - Installing Python tutorial of how to use the diff tool is available from this book's website at http://inventwithpython.com/videos/ Summary This chapter... and not Python 2 The programs in this book use Python 3, and you'll get errors if you try to run them with Python 2 The installation for Mac OS is similar Instead of downloading the msi file from the Python website, download the dmg Mac Installer Disk Image file instead The link to this file will look something like "Mac Installer disk image (3.1.1)" on the "Download Python Software" web page If your. .. showing you how to create computer games Once you learn how the games in this book work, you'll be able to create your own games All you'll need is a computer, some software called the Python Interpreter, and this book The software you'll need is free and you can download it from the Internet When I was a kid, I found a book like this that taught me how to write my first programs and games It was fun and... specifically the Python interpreter (You may need to ask an adult for help here.) The interpreter is a program that understands the instructions that you'll write in the Python language Without the interpreter, your computer won't understand these instructions and your programs won't work (We'll just refer to "the Python interpreter" as "Python" from now on.) Because we'll be writing our games in the Python. .. to python. org, you should see a list of links on the left (About, News, Documentation, Download, and so on.) Click on the Download link to go to the download 2 1 - Installing Python page, then look for the file called Python 3.1 Windows Installer (Windows binary -does not include source) and click on its link to download Python for Windows Figure 1-1: Click the Windows installer link to download Python. .. need to download Python first, from the official website of the Python programming language, http://www .python. org I'm going to give you instructions for installing Python on Microsoft Windows, not because that's my favorite operating system but because chances are that's the operating system that your computer is running You might want the help of someone else to download and install the Python software... Methods Reference 403 Appendix C Running Python Programs without Python Installed 404 Appendix D Common Error Messages in Python 407 Glossary About the Author 411 421 Topics Covered In This Chapter: Downloading and installing the Python interpreter Using IDLE's interactive shell to run instructions How to use this book The book's website at http://inventwithpython.com Hello! This is a book that will... to use Python' s interactive shell Some Simple Math Stuff To open IDLE on Windows, click on Start > Programs > Python 3.1 > IDLE (Python GUI) With IDLE open, let's do some simple math with Python The interactive shell can work just like a calculator Type 2+2 into the shell and press the Enter key on your keyboard (On some keyboards, this is the RETURN key.) As you can see in Figure 2-1, the computer . Albert Sweigart Some Rights Reserved. " ;Invent Your Own Computer Games with Python& quot; (" ;Invent with Python& quot;) is licensed under a Creative. Invent Your Own Computer Games with Python 2nd Edition