Making Games with Python & Pygame By Al Sweigart Email questions to the author: al@inventwithpython.com Copyright © 2012 by Albert Sweigart Some Rights Reserved. ―Making Games with Python & Pygame‖) 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 2 If you've downloaded this book from a torrent, it’s probably out of date. Go to http://inventwithpython.com/pygame to download the latest version. ISBN (978-1469901732) 1st Edition For Calvin Chaos Email questions to the author: al@inventwithpython.com Who is this book for? i WHO IS THIS BOOK FOR? When you get down to it, programming video games is just about lighting up pixels to make pretty pictures appear on the screen in response to keyboard and mouse input. And there are very few things that are as fun. This book will teach you how to make graphical computer games in the Python programming language using the Pygame library. This book assumes you know a little bit about Python or programming in general. If you don’t know how to program, you can learn by downloading the free book ―Invent Your Own Computer Games with Python‖ from http://inventwithpython.com. Or you can jump right into this book and mostly pick it up along the way. This book is for the intermediate programmer who has learned what variables and loops are, but now wants to know, ―What do actual game programs look like?‖ There was a long gap after I first learned programming but didn’t really know how to use that skill to make something cool. It’s my hope that the games in this book will give you enough ideas about how programs work to provide a foundation to implement your own games. The full text of this book is available in HTML or PDF format at http://inventwithpython.com/pygame. -Al Sweigart ii http://inventwithpython.com/pygame Email questions to the author: al@inventwithpython.com ABOUT THIS BOOK Hello! This book will teach you how to make graphical computer games with the Pygame framework (also called the Pygame library) in the Python programming language. Pygame makes it easy to create programs with 2D graphics. Both Python and the Pygame framework can be downloaded for free from http://python.org and http://pygame.org. All you need is a computer and this book to begin making your own games. This book is an intermediate programming book. If you are completely new to programming, you can still try to follow along with the source code examples and figure out how programming works. However, it might be easier to learn how to program in Python first. ―Invent Your Own Computer Games with Python‖ is a book that is available completely for free from http://inventwithpython.com. That book teaches programming by making non-graphical, text- based games for complete beginners, and also has a few chapters about using the Pygame library. However, if you already know how to program in Python (or even some other language, since Python is so easy to pick up) and want to start making games beyond just text, then this is the book for you. The book starts with a short introduction to how the Pygame library works and the functions it provides. Then it provides the complete source code for some actual games and explains how the code works, so you can understand how actual game programs make use of Pygame. This book features seven different games that are clones of popular games that you’ve probably already played. The games are a lot more fun and interactive than the text-based games in ―Invent with Python‖, but are still fairly short. All of the programs are less than 600 lines long. This is pretty small when you consider that professional games you download or buy in a store can be hundreds of thousands of lines long. These games require an entire team of programmers and artists working with each other for months or years to make. The website for this book is http://inventwithpython.com/pygame. All the programs and files mentioned in this book can be downloaded for free from this website, including this book itself. Programming is a great creative activity, so please share this book as widely as possible. The Creative Commons license that this book is released under gives you the right to copy and duplicate this book as much as you want (as long as you don’t charge money for it). If you ever have questions about how these programs work, feel free to email me at al@inventwithpython.com. About This Book iii TABLE OF CONTENTS Who is this book for? i About This Book ii Chapter 1 – Installing Python and Pygame 1 What You Should Know Before You Begin 1 Downloading and Installing Python 1 Windows Instructions 1 Mac OS X Instructions 2 Ubuntu and Linux Instructions 2 Starting Python 2 Installing Pygame 3 How to Use This Book 4 The Featured Programs 4 Downloading Graphics and Sound Files 4 Line Numbers and Spaces 4 Text Wrapping in This Book 5 Checking Your Code Online 6 More Info Links on http://invpy.com 6 Chapter 2 – Pygame Basics 7 GUI vs. CLI 7 Source Code for Hello World with Pygame 7 Setting Up a Pygame Program 8 Game Loops and Game States 10 pygame.event.Event Objects 11 The QUIT Event and pygame.quit() Function 12 Pixel Coordinates 13 iv http://inventwithpython.com/pygame Email questions to the author: al@inventwithpython.com A Reminder About Functions, Methods, Constructor Functions, and Functions in Modules (and the Difference Between Them) 14 Surface Objects and The Window 15 Colors 16 Transparent Colors 17 pygame.Color Objects 18 Rect Objects 18 Primitive Drawing Functions 20 pygame.PixelArray Objects 23 The pygame.display.update() Function 24 Animation 24 Frames Per Second and pygame.time.Clock Objects 27 Drawing Images with pygame.image.load() and blit() 28 Fonts 28 Anti-Aliasing 30 Playing Sounds 31 Summary 32 Chapter 3 – Memory Puzzle 33 How to Play Memory Puzzle 33 Nested for Loops 33 Source Code of Memory Puzzle 34 Credits and Imports 42 Magic Numbers are Bad 42 Sanity Checks with assert Statements 43 Telling If a Number is Even or Odd 44 Crash Early and Crash Often! 44 Making the Source Code Look Pretty 45 Using Constant Variables Instead of Strings 46 Making Sure We Have Enough Icons 47 Tuples vs. Lists, Immutable vs. Mutable 47 About This Book v One Item Tuples Need a Trailing Comma 48 Converting Between Lists and Tuples 49 The global statement, and Why Global Variables are Evil 49 Data Structures and 2D Lists 51 The ―Start Game‖ Animation 52 The Game Loop 52 The Event Handling Loop 53 Checking Which Box The Mouse Cursor is Over 54 Handling the First Clicked Box 55 Handling a Mismatched Pair of Icons 56 Handling If the Player Won 56 Drawing the Game State to the Screen 57 Creating the ―Revealed Boxes‖ Data Structure 58 Creating the Board Data Structure: Step 1 – Get All Possible Icons 58 Step 2 – Shuffling and Truncating the List of All Icons 59 Step 3 – Placing the Icons on the Board 59 Splitting a List into a List of Lists 60 Different Coordinate Systems 61 Converting from Pixel Coordinates to Box Coordinates 62 Drawing the Icon, and Syntactic Sugar 63 Syntactic Sugar with Getting a Board Space’s Icon’s Shape and Color 64 Drawing the Box Cover 64 Handling the Revealing and Covering Animation 65 Drawing the Entire Board 66 Drawing the Highlight 67 The ―Start Game‖ Animation 67 Revealing and Covering the Groups of Boxes 68 The ―Game Won‖ Animation 68 Telling if the Player Has Won 69 vi http://inventwithpython.com/pygame Email questions to the author: al@inventwithpython.com Why Bother Having a main() Function? 69 Why Bother With Readability? 70 Summary, and a Hacking Suggestion 74 Chapter 4 – Slide Puzzle 77 How to Play Slide Puzzle 77 Source Code to Slide Puzzle 77 Second Verse, Same as the First 85 Setting Up the Buttons 86 Being Smart By Using Stupid Code 87 The Main Game Loop 88 Clicking on the Buttons 89 Sliding Tiles with the Mouse 90 Sliding Tiles with the Keyboard 90 ―Equal To One Of‖ Trick with the in Operator 91 WASD and Arrow Keys 91 Actually Performing the Tile Slide 92 IDLE and Terminating Pygame Programs 92 Checking for a Specific Event, and Posting Events to Pygame’s Event Queue 92 Creating the Board Data Structure 93 Not Tracking the Blank Position 94 Making a Move by Updating the Board Data Structure 94 When NOT to Use an Assertion 95 Getting a Not-So-Random Move 96 Converting Tile Coordinates to Pixel Coordinates 97 Converting from Pixel Coordinates to Board Coordinates 97 Drawing a Tile 97 The Making Text Appear on the Screen 98 Drawing the Board 99 Drawing the Border of the Board 99 [...]... OS X 10.5 comes with Python 2.5.1 pre-installed by Apple Currently, Pygame only supports Python 2 and not Python 3 However, the programs in this book work with both Python 2 and 3 The Python website also has some additional information about using Python on a Mac at http://docs .python. org/dev/using/mac.html Ubuntu and Linux Instructions Pygame for Linux also only supports Python 2, not Python 3 If your... Computer Games with Python online at http://inventwithpython.com or look up a topic that you find confusing on the Invent with Python wiki at http://inventwithpython.com/wiki You don’t need to know how to use the Pygame library before reading this book The next chapter is a brief tutorial on all of Pygame s major features and functions Just in case you haven’t read the first book and already installed Python. .. maximum recursion depth exceeded xiv http://inventwithpython.com /pygame Email questions to the author: al@inventwithpython.com Chapter 1 – Installing Python and Pygame 1 CHAPTER 1 – INSTALLING PYTHON AND PYGAME What You Should Know Before You Begin It might help if you know a bit about Python programming (or how to program in another language besides Python) before you read through this book; however... The Python shell lets you type Python instructions, and the shell sends these instructions to the Python interpreter to perform Installing Pygame Pygame does not come with Python Like Python, Pygame is available for free You will have to download and install Pygame, which is as easy as downloading and installing the Python interpreter In a web browser, go to the URL http:/ /pygame. org and click on the... programs that demonstrate how to use the different features that Pygame provides In the last chapter, you will use these features for a complete game written in Python with Pygame A video tutorial of how to install Pygame is available from this book's website at http://invpy.com/videos How to Use This Book Making Games with Python & Pygame is different from other programming books because it focuses... file to install Pygame To check that Pygame is install correctly, type the following into the interactive shell: >>> import pygame 4 http://inventwithpython.com /pygame If nothing appears after you hit the Enter key, then you know Pygame has successfully been installed If the error ImportError: No module named pygame appears, then try to install Pygame again (and make sure you typed import pygame correctly)... beginners to programming The ―Invent with Python book also has a few chapters covering Pygame You can read them online at http://invpy.com/chap17 Once you learn more about Pygame, you can view the other modules that Pygame provides from the online documentation at http:/ /pygame. org/docs GUI vs CLI The Python programs that you can write with Python s built-in functions only deal with text through the print()... type out) in the Python language Without the interpreter, your computer won't be able to run your Python programs We'll just refer to ―the Python interpreter‖ as Python from now on The Python interpreter software can be downloaded from the official website of the Python programming language, http://www .python. org You might want the help of someone else to download and install the Python software The... Pygame functions dealing with graphics, sound, and other features that Pygame provides are in the pygame module Note that when you import the pygame module you automatically import all the modules that are in the pygame module as well, such as pygame. images and pygame. mixer.music There’s no need to import these modules-inside-modules with additional import statements 2 from pygame. locals import * Line... programs, the Pygame framework includes several modules with functions for drawing graphics, playing sounds, handling mouse input, and other things This chapter will cover the basic modules and functions that Pygame provides and assumes you already know basic Python programming If you have trouble with some of the programming concepts, you can read through the ―Invent Your Own Computer Games with Python . Making Games with Python & Pygame By Al Sweigart Email questions to the author: al@inventwithpython.com. http://inventwithpython.com /pygame. -Al Sweigart ii http://inventwithpython.com /pygame Email questions to the author: al@inventwithpython.com ABOUT