Transcription

Making Games withPython & PygameBy Al Sweigart

Copyright 2012 by Albert SweigartSome Rights Reserved. ―Making Games with Python & Pygame‖) is licensed under a CreativeCommons Attribution-Noncommercial-Share Alike 3.0 United States License.You are free:To Share — to copy, distribute, display, and perform the workTo Remix — to make derivative worksUnder the following conditions:Attribution — You must attribute the work in the manner specified by the author orlicensor (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 distributethe resulting work only under the same or similar license to this one.This summary is located here: s/Your fair use and other rights are in no way affected by the above. There is a human-readablesummary of the Legal Code (the full license), located 3.0/us/legalcodeBook Version 2If you've downloaded this book from a torrent, it’s probably out of date. Goto http://inventwithpython.com/pygame to download the latest version.ISBN (978-1469901732)1st EditionEmail questions to the author: [email protected]

For Calvin Chaos

Email questions to the author: [email protected]

Who is this book for?iWHO IS THIS BOOK FOR?When you get down to it, programming video games is just about lighting up pixels to makepretty 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 programminglanguage using the Pygame library. This book assumes you know a little bit about Python orprogramming in general. If you don’t know how to program, you can learn by downloading thefree 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, butnow wants to know, ―What do actual game programs look like?‖ There was a long gap after I firstlearned programming but didn’t really know how to use that skill to make something cool. It’smy hope that the games in this book will give you enough ideas about how programs work toprovide a foundation to implement your own games.The full text of this book is available in HTML or PDF format athttp://inventwithpython.com/pygame.-Al Sweigart

iihttp://inventwithpython.com/pygameABOUT THIS BOOKHello! This book will teach you how to make graphical computer games with the Pygameframework (also called the Pygame library) in the Python programming language. Pygame makesit easy to create programs with 2D graphics. Both Python and the Pygame framework can bedownloaded for free from http://python.org and http://pygame.org. All you need is a computerand 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 programmingworks. However, it might be easier to learn how to program in Python first. ―Invent Your OwnComputer Games with Python‖ is a book that is available completely for free fromhttp://inventwithpython.com. That book teaches programming by making non-graphical, textbased 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, sincePython is so easy to pick up) and want to start making games beyond just text, then this is thebook for you. The book starts with a short introduction to how the Pygame library works and thefunctions it provides. Then it provides the complete source code for some actual games andexplains how the code works, so you can understand how actual game programs make use ofPygame.This book features seven different games that are clones of popular games that you’ve probablyalready played. The games are a lot more fun and interactive than the text-based games in ―Inventwith Python‖, but are still fairly short. All of the programs are less than 600 lines long. This ispretty small when you consider that professional games you download or buy in a store can behundreds of thousands of lines long. These games require an entire team of programmers andartists working with each other for months or years to make.The website for this book is http://inventwithpython.com/pygame. All the programs and filesmentioned 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. TheCreative Commons license that this book is released under gives you the right to copy andduplicate 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 [email protected] questions to the author: [email protected]

About This BookiiiTABLE OF CONTENTSWho is this book for? . iAbout This Book . iiChapter 1 – Installing Python and Pygame . 1What You Should Know Before You Begin . 1Downloading and Installing Python . 1Windows Instructions . 1Mac OS X Instructions. 2Ubuntu and Linux Instructions . 2Starting Python. 2Installing Pygame. 3How to Use This Book. 4The Featured Programs . 4Downloading Graphics and Sound Files . 4Line Numbers and Spaces . 4Text Wrapping in This Book . 5Checking Your Code Online . 6More Info Links on http://invpy.com . 6Chapter 2 – Pygame Basics. 7GUI vs. CLI . 7Source Code for Hello World with Pygame . 7Setting Up a Pygame Program . 8Game Loops and Game States . 10pygame.event.Event Objects . 11The QUIT Event and pygame.quit() Function . 12Pixel Coordinates . 13

iv http://inventwithpython.com/pygameA Reminder About Functions, Methods, Constructor Functions, and Functions in Modules (andthe Difference Between Them) . 14Surface Objects and The Window . 15Colors . 16Transparent Colors . 17pygame.Color Objects. 18Rect Objects . 18Primitive Drawing Functions . 20pygame.PixelArray Objects. 23The pygame.display.update() Function . 24Animation . 24Frames Per Second and pygame.time.Clock Objects . 27Drawing Images with pygame.image.load() and blit() . 28Fonts. 28Anti-Aliasing. 30Playing Sounds. 31Summary . 32Chapter 3 – Memory Puzzle . 33How to Play Memory Puzzle . 33Nested for Loops . 33Source Code of Memory Puzzle . 34Credits and Imports . 42Magic Numbers are Bad . 42Sanity Checks with assert Statements. 43Telling If a Number is Even or Odd . 44Crash Early and Crash Often! . 44Making the Source Code Look Pretty . 45Using Constant Variables Instead of Strings . 46Making Sure We Have Enough Icons . 47Tuples vs. Lists, Immutable vs. Mutable . 47Email questions to the author: [email protected]

About This BookvOne Item Tuples Need a Trailing Comma . 48Converting Between Lists and Tuples . 49The global statement, and Why Global Variables are Evil. 49Data Structures and 2D Lists . 51The ―Start Game‖ Animation. 52The Game Loop . 52The Event Handling Loop . 53Checking Which Box The Mouse Cursor is Over . 54Handling the First Clicked Box . 55Handling a Mismatched Pair of Icons . 56Handling If the Player Won .