Making Games With Python & Pygame

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: al@inventwithpython.com

For Calvin Chaos

Email questions to the author: al@inventwithpython.com

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 atal@inventwithpython.com.Email questions to the author: al@inventwithpython.com

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: al@inventwithpython.com

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 . 56Drawing the Game State to the Screen . 57Creating the ―Revealed Boxes‖ Data Structure . 58Creating the Board Data Structure: Step 1 – Get All Possible Icons . 58Step 2 – Shuffling and Truncating the List of All Icons . 59Step 3 – Placing the Icons on the Board . 59Splitting a List into a List of Lists. 60Different Coordinate Systems . 61Converting from Pixel Coordinates to Box Coordinates . 62Drawing the Icon, and Syntactic Sugar . 63Syntactic Sugar with Getting a Board Space’s Icon’s Shape and Color . 64Drawing the Box Cover . 64Handling the Revealing and Covering Animation . 65Drawing the Entire Board . 66Drawing the Highlight . 67The ―Start Game‖ Animation. 67Revealing and Covering the Groups of Boxes . 68The ―Game Won‖ Animation . 68Telling if the Player Has Won . 69

vihttp://inventwithpython.com/pygameWhy Bother Having a main() Function? . 69Why Bother With Readability? . 70Summary, and a Hacking Suggestion . 74Chapter 4 – Slide Puzzle . 77How to Play Slide Puzzle . 77Source Code to Slide Puzzle . 77Second Verse, Same as the First . 85Setting Up the Buttons . 86Being Smart By Using Stupid Code . 87The Main Game Loop . 88Clicking on the Buttons . 89Sliding Tiles with the Mouse . 90Sliding Tiles with the Keyboard . 90―Equal To One Of‖ Trick with the in Operator . 91WASD and Arrow Keys . 91Actually Performing the Tile Slide . 92IDLE and Terminating Pygame Programs . 92Checking for a Specific Event, and Posting Events to Pygame’s Event Queue . 92Creating the Board Data Structure . 93Not Tracking the Blank Position. 94Making a Move by Updating the Board Data Structure . 94When NOT to Use an Assertion . 95Getting a Not-So-Random Move . 96Converting Tile Coordinates to Pixel Coordinates . 97Converting from Pixel Coordinates to Board Coordinates . 97Drawing a Tile . 97The Making Text Appear on the Screen . 98Drawing the Board . 99Drawing the Border of the Board. 99Email questions to the author: al@inventwithpython.com

About This BookviiDrawing the Buttons . 100Animating the Tile Slides . 100The copy() Surface Method . 101Creating a New Puzzle . 103Animating the Board Reset . 104Time vs. Memory Tradeoffs . 105Nobody Cares About a Few Bytes . 106Nobody Cares About a Few Million Nanoseconds . 107Summary . 107Chapter 5 – Simulate. 108How to Play Simulate . 108Source Code to Simulate . 108The Usual Starting Stuff . 114Setting Up the Buttons . 115The main() Function . 115Some Local Variables Used in This Program . 116Drawing the Board and Handling Input . 117Checking for Mouse Clicks . 118Checking for Keyboard Presses . 118The Two States of the Game Loop . 119Figuring Out if the Player Pressed the Right Buttons . 119Epoch Time . 121Drawing the Board to the Screen . 122Same Old terminate() Function . 122Reusing The Constant Variables . 123Animating the Button Flash . 123Drawing the Buttons . 126Animating the Background Change . 126The Game Over Animation . 127

viiihttp://inventwithpython.com/pygameConverting from Pixel Coordinates to Buttons . 129Explicit is Better Than Implicit. 129Chapter 6 – Wormy . 131How to Play Wormy . 131Source Code to Wormy . 131The Grid . 137The Setup Code . 137The main() Function . 138A Separate runGame() Function . 139The Event Handling Loop . 139Collision Detection . 140Detecting Collisions with the Apple . 141Moving the Worm . 142The insert() List Method. 142Drawing the Screen . 143Drawing ―Press a key‖ Text to the Screen . 143The checkForKeyPress() Function . 143The Start Screen . 144Rotating the Start Screen Text . 145Rotations Are Not Perfect . 146Deciding Where the Apple Appears . 147Game Over Screens. 147Drawing Functions . 148Don’t Reuse Variable Names . 151Chapter 7 - Tetromino . 153How to Play Tetromino . 153Some Tetromino Nomenclature . 153Source Code to Tetromino . 154The Usual Setup Code . 166Email questions to the author: al@inventwithpython.com

About This BookixSetting up Timing Constants for Holding Down Keys . 166More Setup Code . 166Setting Up the Piece Templates . 168Splitting a ―Line of Code‖ Across Multiple Lines . 171The main() Function . 172The Start of a New Game. 173The Game Loop . 174The Event Handling Loop . 174Pausing the Game . 174Using Movement Variables to Handle User Input . 175Checking if a Slide or Rotation is Valid . 175Finding the Bottom . 178Moving by Holding Down the Key. 179Letting the Piece ―Naturally‖ Fall . 182Drawing Everything on the Screen . 182makeTextObjs(), A Shortcut Function for Making Text . 183The Same Old terminate() Function .

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 p