X
Other programming books by Al Sweigart:

Use this link to get 80% off the Automate the Boring Stuff online video course.
Support me on Patreon
Next: Chapter 1: The Interactive Shell
image

When I first played video games as a kid, I was hooked. But I didn’t just want to play video games, I wanted to make them. I found a book like this one that taught me how to write my first programs and games. It was fun and easy. The first games I made were like the ones in this book. They weren’t as fancy as the Nintendo games my parents bought for me, but they were games I had made myself.

Now, as an adult, I still have fun programming and I get paid for it. But even if you don’t want to become a computer programmer, programming is a useful and fun skill to have. It trains your brain to think logically, make plans, and reconsider your ideas whenever you find mistakes in your code.

Many programming books for beginners fall into two categories. The first category includes books that don’t teach programming so much as “game creation software” or languages that simplify so much that what is taught is no longer programming. The other category consists of books that teach programming like a mathematics textbook—all principles and concepts, with few real-life applications for the reader. This book takes a different approach and teaches you how to program by making video games. I show the source code for the games right up front and explain programming principles from the examples. This approach was the key for me when I was learning to program. The more I learned how other people’s programs worked, the more ideas I had for my own programs.

All you’ll need is a computer, some free software called the Python interpreter, and this book. Once you learn how to create the games in this book, you’ll be able to develop games on your own.

Computers are incredible machines, and learning to program them isn’t as hard as people think. A computer program is a bunch of instructions that the computer can understand, just like a storybook is a bunch of sentences that the reader can understand. To instruct a computer, you write a program in a language the computer understands. This book will teach you a programming language called Python. There are many other programming languages you can learn, like BASIC, Java, JavaScript, PHP, and C++.

When I was a kid, I learned BASIC, but newer programming languages like Python are even easier to learn. Python is also used by professional programmers in their work and when programming for fun. Plus it’s totally free to install and use—you’ll just need an internet connection to download it.

Because video games are nothing but computer programs, they are also made up of instructions. The games you’ll create from this book seem simple compared to the games for Xbox, PlayStation, or Nintendo. These games don’t have fancy graphics because they’re meant to teach you coding basics. They’re purposely simple so you can focus on learning to program. Games don’t have to be complicated to be fun!

Programming isn’t hard, but it is hard to find materials that teach you to do interesting things with programming. Other computer books go over many topics most new coders don’t need. This book will teach you how to program your own games; you’ll learn a useful skill and have fun games to show for it! This book is for:

• Complete beginners who want to teach themselves programming, even if they have no previous experience.

• Kids and teenagers who want to learn programming by creating games.

• 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.

In most of the chapters in this book, a single new game project is introduced and explained. A few of the chapters cover additional useful topics, like debugging. New programming concepts are explained as games make use of them, and the chapters are meant to be read in order. Here’s a brief rundown of what you’ll find in each chapter:

Chapter 1: The Interactive Shell explains how Python’s interactive shell can be used to experiment with code one line at a time.

Chapter 2: Writing Programs covers how to write complete programs in Python’s file editor.

• In Chapter 3: Guess the Number, you’ll program the first game in the book, Guess the Number, which asks the player to guess a secret number and then provides hints as to whether the guess is too high or too low.

• In Chapter 4: A Joke-Telling Program, you’ll write a simple program that tells the user several jokes.

• In Chapter 5: Dragon Realm, you’ll program a guessing game in which the player must choose between two caves: one has a friendly dragon, and the other has a hungry dragon.

Chapter 6: Using the Debugger covers how to use the debugger to fix problems in your code.

Chapter 7: Designing Hangman with Flowcharts explains how flowcharts can be used to plan longer programs, such as the Hangman game.

• In Chapter 8: Writing the Hangman Code, you’ll write the Hangman game, following the flowchart from Chapter 7.

Chapter 9: Extending Hangman extends the Hangman game with new features by making use of Python’s dictionary data type.

• In Chapter 10: Tic-Tac-Toe, you’ll learn how to write a human-versus-computer Tic-Tac-Toe game that uses artificial intelligence.

• In Chapter 11: The Bagels Deduction Game, you’ll learn how to make a deduction game called Bagels in which the player must guess secret numbers based on clues.

Chapter 12: The Cartesian Coordinate System explains the Cartesian coordinate system, which you’ll use in later games.

• In Chapter 13: Sonar Treasure Hunt, you’ll learn how to write a treasure hunting game in which the player searches the ocean for lost treasure chests.

• In Chapter 14: Caesar Cipher, you’ll create a simple encryption program that lets you write and decode secret messages.

• In Chapter 15: The Reversegam Game, you’ll program an advanced human-versus-computer Reversi-type game that has a nearly unbeatable artificial intelligence opponent.

Chapter 16: Reversegam AI Simulation expands on the Reversegam game in Chapter 15 to make multiple AIs that compete in computer-versus-computer games.

Chapter 17: Creating Graphics introduces Python’s pygame module and shows you how to use it to draw 2D graphics.

Chapter 18: Animating Graphics shows you how to animate graphics with pygame.

• In Chapter 19: Collision Detection, you’ll learn how to detect when objects collide with each other in 2D games.

• In Chapter 20: Using Sounds and Images, you’ll improve your simple pygame games by adding sounds and images.

Chapter 21: A Dodger Game with Sounds and Images combines the concepts in Chapters 17 to 20 to make an animated game called Dodger.

Most chapters in this book will begin with a sample run of the chapter’s featured program. This sample run shows you what the program looks like when you run it. The parts the user types are shown in bold.

I recommend that you enter the code for each program into IDLE’s file editor yourself rather than downloading or copying and pasting it. You’ll remember more if you take the time to type the code.

When typing the source code from this book, do not type the line numbers at the start of each line. For example, if you saw the following line of code, you would not need to type the 9. on the left side, or the one space immediately following it:

9. number = random.randint(1, 20)

You’d enter only this:

number = random.randint(1, 20)

Those numbers are there just so this book can refer to specific lines in the program. They are not part of the actual program’s source code.

Aside from the line numbers, enter the code exactly as it appears in this book. Notice that some of the lines of code are indented by four or eight (or more) spaces. The spaces at the beginning of the line change how Python interprets instructions, so they are very important to include.

Let’s look at an example. The indented spaces here are marked with black circles (•) so you can see them.

while guesses < 10:
••••if number == 42:
••••••••print('Hello')

The first line is not indented, the second line is indented four spaces, and the third line is indented eight spaces. Although the examples in this book don’t have black circles to mark the spaces, each character in IDLE is the same width, so you can count the number of spaces by counting the number of characters on the line above or below.

Some code instructions are too long to fit on one line in the book and will wrap around to the next line. But the line will fit on your computer screen, so type it all on one line without pressing ENTER. You can tell when a new instruction starts by looking at the line numbers on the left. This example has only two instructions:

1. print('This is the first instruction!xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
     xxxxxxxxxxxx')
2. print('This is the second instruction, not the third instruction.')

The first instruction wraps around to a second line on the page, but the second line does not have a line number, so you can see that it’s still line 1 of the code.

You’ll need to install software called the Python interpreter. The interpreter program understands the instructions you write in Python. I’ll refer to the Python interpreter software as just Python from now on.

In this section, I’ll show you how to download and install Python 3—specifically, Python 3.4—for Windows, OS X, or Ubuntu. There are newer versions of Python than 3.4, but the pygame module, which is used in Chapters 17 to 21, currently only supports up to 3.4.

It’s important to know that there are some significant differences between Python 2 and Python 3. The programs in this book use Python 3, and you’ll get errors if you try to run them with Python 2. This is so important, in fact, that I’ve added a cartoon penguin to remind you about it.

image

On Windows, download the Windows x86-64 MSI installer from https://www.python.org/downloads/release/python-344/ and then double-click it. You may have to enter the administrator password for your computer. Follow the instructions the installer displays on the screen to install Python, as listed here:

  1. Select Install for All Users and then click Next.

  2. Install to the C:\Python34 folder by clicking Next.

  3. Click Next to skip the Customize Python section.

On OS X, download the Mac OS X 64-bit/32-bit installer from https://www.python.org/downloads/release/python-344/ and then double-click it. Follow the instructions the installer displays on the screen to install Python, as listed here:

  1. If you get the warning “‘Python.mpkg’ can’t be opened because it is from an unidentified developer,” hold down CONTROL while right-clicking the Python.mpkg file and then select Open from the menu that appears. You may have to enter the administrator password for your computer.

  2. Click Continue through the Welcome section and click Agree to accept the license.

  3. Select Macintosh HD (or whatever your hard drive is named) and click Install.

If you’re running Ubuntu, you can install Python from the Ubuntu Software Center by following these steps:

  1. Open the Ubuntu Software Center.

  2. Enter Python in the search box in the top-right corner of the window.

  3. Select IDLE (Python 3.4 GUI 64 bit).

  4. Click Install. You may have to enter the administrator password to complete the installation.

If the above steps do not work, you can find alternative Python 3.4 install instructions at https://www.nostarch.com/inventwithpython/.

IDLE stands for Interactive DeveLopment Environment. IDLE is like a word processor for writing Python programs. Starting IDLE is different on each operating system:

• On Windows, click the Start menu in the lower-left corner of the screen, type IDLE, and select IDLE (Python GUI).

• On OS X, open Finder and click Applications. Double-click Python 3.x and then double-click the IDLE icon.

• On Ubuntu or other Linux distros, open a terminal window and enter idle3. You may also be able to click Applications at the top of the screen. Then click Programming and IDLE 3.

The window that appears when you first run IDLE is the interactive shell, as shown in Figure 1. You can enter Python instructions into the interactive shell at the >>> prompt and Python will perform them. After the computer performs the instructions, a new >>> prompt will wait for your next instruction.

image

Figure 1: The IDLE program’s interactive shell

You can find the source code files and other resources for this book at https://www.nostarch.com/inventwithpython/. If you want to ask programming questions related to this book, visit https://reddit.com/r/inventwithpython/, or you can email your programming questions to me at [email protected].

Before you ask any questions, make sure you do the following:

• If you are typing out a program in this book but are getting an error, check for typos with the online diff tool at https://www.nostarch.com/inventwithpython#diff before asking your question. Copy and paste your code into the diff tool to find any differences between the book’s code and yours.

• Search the web to see whether someone else has already asked (and answered) your question.

Keep in mind that the better you phrase your programming questions, the better others will be able to help you. When asking programming questions, do the following:

• Explain what you are trying to do when you get the error. This will let your helper know if you are on the wrong path entirely.

• Copy and paste the entire error message and your code.

• Provide your operating system and version.

• Explain what you’ve already tried to do to solve your problem. This tells people you’ve already put in some work to try to figure things out on your own.

• Be polite. Don’t demand help or pressure your helpers to respond quickly.

Now that you know how to ask for help, you’ll be learning to program your own computer games in no time!

Next: Chapter 1: The Interactive Shell