i Invent Your Own Computer Games with Python, 2 nd Edition By Al Sweigart ii Copyright © 2008-2012 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 31 If you've downloaded this book from a torrent, it’s probably out of date. Go to http://inventwithpython.com to download the latest version instead. ISBN 978-0-9821060-1-3 2.1 Edition iii iv For Caro, with more love than I ever knew I had. v 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 vi 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. vii TABLE OF CONTENTS Installing Python 1 Downloading and Installing Python 2 Windows Instructions 3 Mac OS X Instructions 4 Ubuntu and Linux Instructions 4 Starting Python 4 How to Use This Book 5 The Featured Programs 5 Line Numbers and Spaces 6 Text Wrapping in This Book 6 Tracing the Program Online 7 Checking Your Code Online 7 Summary 7 The Interactive Shell 8 Some Simple Math Stuff 8 Integers and Floating Point Numbers 9 Expressions 10 Evaluating Expressions 11 Expressions Inside Other Expressions 12 Storing Values in Variables 12 Using More Than One Variable 15 Overwriting Variables 16 Summary 17 Strings 18 Strings 18 String Concatenation 19 viii Writing Programs in IDLE's File Editor 20 Hello World! 20 hello.py 21 Saving Your Program 22 Opening The Programs You've Saved 23 How the “Hello World” Program Works 24 Comments 24 Functions 25 The print() function 25 The input() function 25 Ending the Program 26 Variable Names 27 Summary 27 Guess the Number 29 The “Guess the Number” Game 29 Sample Run of “Guess the Number” 30 Guess the Number's Source Code 30 The import statement 32 The random.randint() function 33 Calling Functions that are Inside Modules 35 Passing Arguments to Functions 35 Welcoming the Player 36 Loops 37 Blocks 37 The Boolean Data Type 38 Comparison Operators 38 Conditions 39 Experiment with Booleans, Comparison Operators, and Conditions 39 Looping with while statements 41 ix The Player Guesses 43 Converting Strings to Integers with the int() function 43 Incrementing Variables 45 if statements 45 Is the Player's Guess Too Low? 45 Is the Player's Guess Too High? 47 Leaving Loops Early with the break statement 47 Check if the Player Won 48 Check if the Player Lost 48 Summary: What Exactly is Programming? 49 A Web Page for Program Tracing 50 Jokes 52 Making the Most of print() 52 Sample Run of Jokes 52 Joke's Source Code 53 How the Code Works 53 Escape Characters 54 Some Other Escape Characters 54 Quotes and Double Quotes 55 The end Keyword Argument 56 Summary 56 Dragon Realm 58 Introducing Functions 58 How to Play “Dragon Realm” 59 Sample Run of Dragon Realm 59 Dragon Realm's Source Code 59 How the Code Works 61 Defining the displayIntro() Function 61 def Statements 62 x Defining the chooseCave() Function 62 Boolean Operators 63 Evaluating an Expression That Contains Boolean Operators 63 Experimenting with the and and or Operators 64 Experimenting with the not Operator 65 Truth Tables 66 Getting the Player's Input 66 Return Values 67 Variable Scope 67 Global Scope and Local Scope 68 Defining the checkCave() Function 69 Parameters 70 Where to Put Function Definitions 71 Displaying the Game Results 72 Deciding Which Cave has the Friendly Dragon 72 The Colon : 74 Where the Program Really Begins 74 Calling the Functions in Our Program 74 Asking the Player to Play Again 75 Designing the Program 76 Summary 77 Using the Debugger 78 Bugs! 78 The Debugger 80 Starting the Debugger 80 Stepping 82 Click the Step button twice to run the two import lines. 82 Click the Step button three more times to execute the three def statements. 82 Click the Step button again to define the playAgain variable. 82 [...]... 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 language we need to download Python first, from the official website of the Python programming language, http://www .python. org Important Note!... Documentation, Download, and so on.) Click on the Download link to go to the download page, then look for the file called Python 3.2 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 for Windows from http://www .python. org Double-click on the python- 3.2.msi file that you've just downloaded... INSTALLING PYTHON 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 teach you how to program by 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. .. Note! Be sure to install Python 3, 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 It is so important, I am adding a cartoon penguin telling you to install Python 3 so that you do not miss this message: 3 “Be sure to install Python 3, not Python 2!”, says the incongruous penguin Windows Instructions When you get to python. org, you should... image (3.2)" on the "Download Python Software" web page Ubuntu and Linux Instructions If your operating system is Ubuntu, you can install Python by opening a terminal window (click on Applications > Accessories > Terminal) and entering sudo apt-get install python3 .2 then pressing Enter You will need to enter the root password to install Python, so ask the person who owns the computer to type in this... use Python' s interactive shell Some Simple Math Stuff To open IDLE on Windows, click on Start, then Programs, then Python 3.2, then 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. .. 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 easy Now as an adult, I still have fun programming computers, and I get paid for it But even if you don't become a computer. .. the Start button, then selecting Programs, Python 3.2, IDLE (Python GUI) For Windows Vista or Windows 7, just click the Windows button in the lower left corner, type “IDLE” and select IDLE (Python GUI) If your operating system is Mac OS X, start IDLE by opening the Finder window and click on Applications, then click Python 3.2, then click the IDLE icon If your operating system is Ubuntu or Linux, start... interactive shell A shell is a program that lets you type instructions into the computer The Python shell lets you type Python instructions, and the shell sends these instructions to software called the Python interpreter to perform We can type Python instructions into the shell and, because the shell is interactive, the computer will read our instructions and respond in some way (Ideally in a way that... should understand about this book before you get started “Invent with Python is different from other programming books because it focuses on the complete source code for different games Instead of teaching you programming concepts and leaving it up to you to figure out how to make fun games with those concepts, this book shows you fun games and then explains how they are put together The http://invpy.com . Your Own Computer Games with Python, 2 nd Edition By Al Sweigart ii Copyright © 2008-2012 by Albert Sweigart Some Rights Reserved. "Invent Your Own Computer Games with. if the Player Has Won 174 Duplicating the Board Data 177 Checking if a Space on the Board is Free 177 Letting the Player Enter Their Move 177 Short-Circuit Evaluation 178 An Example of Short-Circuit. Begins 74 Calling the Functions in Our Program 74 Asking the Player to Play Again 75 Designing the Program 76 Summary 77 Using the Debugger 78 Bugs! 78 The Debugger 80 Starting the Debugger