Creating Games In C - A Step-by-Step Guide

Transcription

Creating Games in C : A Step-by-Step GuideBy David Conger, Ron Little.Publisher: New RidersPub Date: February 21, 2006Print ISBN-10: 0-7357-1434-7Print ISBN-13: 978-0-7357-1434-2Pages: 464Table of Contents IndexDo you love video games? Ever wondered if you could create one of your own, with all the bells and whistles?It's not as complicated as you'd think, and you don't need to be a math whiz or a programming genius to do it.In fact, everything you need to create your first game, "Invasion of the Slugwroths," is included in this book andCD-ROM. Author David Conger starts at square one, introducing the tools of the trade and all the basicconcepts for getting started programming with C , the language that powers most current commercial games.Plus, he's put a wealth of top-notch (and free) tools on the CD-ROM, including the Dev-C compiler, linker,and debugger--and his own LlamaWorks2D game engine. Step-by-step instructions and ample illustrations takeyou through game program structure, integrating sound and music into games, floating-point math, C arrays, and much more. Using the sample programs and the source code to run them, you can follow along asyou learn. Bio: David Conger has been programming professionally for over 23 years. Along with countlesscustom business applications, he has written several PC and online games. Conger also worked on graphicsfirmware for military aircraft, and taught computer science at the university level for four years. Conger haswritten numerous books on C, C , and other computer-related topics. He lives in western Washington Stateand has also published a collection of Indian folk tales.

Creating Games in C : A Step-by-Step GuideBy David Conger, Ron Little.Publisher: New RidersPub Date: February 21, 2006Print ISBN-10: 0-7357-1434-7Print ISBN-13: 978-0-7357-1434-2Pages: 464Table of Contents IndexCopyrightAcknowledgmentsIntroductionWhat's Different About This BookWhat's in This Book?System RequirementsFree Stuff on the CDWho Am I?Part 1: The Really Basic StuffChapter 1. What it Takes to be a Game ProgrammerProgramming SkillsComputer Graphics SkillsGame Design SkillsArt SkillsSound and Music SkillsSummaryChapter 2. Writing C ProgramsIntroducing the Dev-C CompilerProgramming in C Essential Math OperatorsLoopsWhile LoopsDo-while loopsWindows ProgrammingGame ProgrammingSummaryPart 2: ObjectOriented Programming in GamesChapter 3. Introducing Object-Oriented ProgrammingSoftware ObjectsClasses

Logical OperatorsThe If-Else StatementNamespaces and Scope ResolutionA Brief Word About StructuresSummaryChapter 4. Introducing the LlamaWorks2D Game EngineA Step-by-Step OverviewHow Does Llamaworks2D Work?A Stationary BallA Bouncing BallGetting Good ResultsSummaryChapter 5. Function and Operator OverloadingWhat Is Overloading?Implementing a Vector Class with OverloadingSummaryChapter 6. Inheritance: Getting a Lot for a LittleWhat Is Inheritance?Deriving ClassesProtected MembersOverriding Base Class FunctionsCustomizing Your Game with InheritanceSummaryPart 3: The Essentials of Game DevelopmentChapter 7. Program StructureProgram StructureFile StructureA Game Called PingSummaryChapter 8. Sound Effects and MusicSound Effects and Music Are EmotionStoring Sound DataSound Effects in LlamaWorks2DNoise, Sweet NoisePlay That Funky Music, Geek BoySummaryPart 4: Graduating to Better C Chapter 9. Floating-Point Math in C Getting into the Guts of Floating-Point NumbersCase Study: Floating-Point Numbers and GamespacesSummaryChapter 10. ArraysWhat Are Arrays?Declaring and Using ArraysInitializing Arrays

Problems with Array BoundariesSummaryChapter 11. PointersWhy Are Pointers Important to Games?Declaring and Using PointersPointers and Dynamic Memory AllocationPointers and InheritanceArrays Are Pointers in DisguiseSummaryChapter 12. File Input and OutputGames and File I/OTypes of FilesSummaryChapter 13. Moving into Real Game DevelopmentSprites that Come AliveHigh-Speed InputSummaryPart 5: The Big PayoffChapter 14. No Slime Allowed: Invasion of the SlugwrothsWhat It Takes to Make a Real GameEssential Game DesignDesigning Invasion of the SlugwrothsSummaryChapter 15. Captain Chloride Gets GoingIntroducing Captain ChloridePulling It Together In The Game ClassSummaryChapter 16. The World of Captain ChlorideThe New Captain ChlorideLevels in LlamaWorks2DSummaryChapter 17. Captain Chloride Encounters Solid ObjectsBumping into a Solid DoorPicking Up a KeyMaking the Door Open and CloseSummaryChapter 18. That's a Wrap!Time for ConsolidationEnter villains, Stage LeftAdditions to the GameEpilogue: Not the EndGlossaryIndex

CopyrightCreating Games in C : A Step-by-Step GuideDavid Conger with Ron LittleNew Riders1249 Eighth StreetBerkeley, CA 94710510/524-2178800/283-9444510/524-2221 (fax)Find us on the Web at: www.newriders.comTo report errors, please send a note to errata@peachpit.comNew Riders is an imprint of Peachpit, a division of Pearson EducationCopyright 2006 by David CongerProject Editors: Davina Baum, Kristin KalningDevelopment Editors: Davina Baum, Denise Santoro LincolnProduction Editor: Myrna VladicCopyeditor: Liz WelchTech Editor: Ron LittleCompositor: WolfsonDesignIndexer: Karin ArrigoniCover design: Aren HowellInterior design: WolfsonDesignNotice of RightsAll rights reserved. No part of this book may be reproduced or transmitted inany form by any means, electronic, mechanical, photocopying, recording, orotherwise, without the prior written permission of the publisher. Forinformation on getting permission for reprints and excerpts, contactpermissions@peachpit.com.Notice of Liability

The information in this book is distributed on an "As Is" basis withoutwarranty. While every precaution has been taken in the preparation of thebook, neither the author nor Peachpit shall have any liability to any person orentity with respect to any loss or damage caused or alleged to be causeddirectly or indirectly by the instructions contained in this book or by thecomputer software and hardware products described in it.TrademarksMany of the designations used by manufacturers and sellers to distinguishtheir products are claimed as trademarks. Where those designations appear inthis book, and Peachpit was aware of a trademark claim, the designationsappear as requested by the owner of the trademark. All other product namesand services identified throughout this book are used in editorial fashion onlyand for the benefit of such companies with no intention of infringement of thetrademark. No such use, or the use of any trade name, is intended to conveyendorsement or other affiliation with this book.987654321Printed and bound in the United States of AmericaDedicationThis book is dedicated to my mother, Jan Conger, for all the good that she hasdone and still does.Thanks, Mom.

AcknowledgmentsThis book has been one of the hardest projects I've ever worked on. Notbecause the book itself was hard to write, but because of three majorcomputer crashes (and two replacement motherboards), two serious illnesses,two surgeries, having to change compilers after the third chapter, and havingto entirely rewrite the game engine after the fourth. I can honestly say that Icould not have got through this book without the support of all those whoworked on it. I especially want to thank Kristin Kalning, who is simply the bestproject editor I've ever worked with. Thanks also to Davina Baum, Liz Welch,Myrna Vladic, Owen Wolfson, Eric Geoffroy, Aren Howell, and Denise Lincoln.I especially want to thank Ron Little. His technical edits were excellent. Andwithout his help on the sample programs for the last five chapters, I'd probablystill be working on this book.

IntroductionThe first video game I ever played (at age 13) was Pong. It was a very simpleping-pong simulation. During my teenage years, a few, more advanced gamesappeared on the market. Most notable were the Atari games such as MissileCommand, a nuclear warfare simulator. When I was 19, I went to live for acouple of years in Japan. There I discovered a whole new worldseveral, in fact.Around the time I arrived in Japan, the game Space Invaders had just crestedits phenomenal wave of popularity. I had never seen anything so cool. By thetime I returned to the United States, video games were everywhere.In the fall of 1981, I started college. Keith, a longtime friend and roommate,pointed to a class in the university's catalog and told me, "You have to takethis programming class. I know you'll love it." He was right. By the time twoweeks had passed, I knew I would be working with computers for the rest ofmy life.And what did I specialize in? Graphics and games, of course.When I started writing games in college, it was a long and difficult task. Theonly people who had a prayer of writing decent games were complete geeks(like me).A lot has changed since then. With the tools available now, nearly anyone canwrite an original and inventive game.

What's Different About This BookThere are lots of beginning game programming books. In the end, the questioneveryone asks is, "What's special about this book in particular?"I'm glad you asked.The short answer to your question is that this book is unlike 99 percent of allbeginning game programming books in several respects.It Doesn't Assume You Know How to Program ComputersMost people who want to get started in game programming don't know how toprogram at all. They are bright, creative, and innovativeand they like games.But they can't yet write computer programs.Virtually every beginning game programming book I've ever seen assumes youknow a programming language like C or C . That means that most beginninggame programmers have to spend months or years learning to program beforethey can even start a game.What a waste.If you want to be a game programmer, but you have little or no programmingexperience, this book is for you. As I mentioned earlier, the tools available forwriting games make the whole experience much easier than when I started inthe industry more than 25 years ago. There's no reason that a bright andcreative person like you should have to jump through a lot of silly hoopslearning to program before you learn to write games. You can learn toprogram computers and write games at the same time. Unfortunately,that thought hasn't occurred to most authors of beginning game programmingbooks.It Teaches You Real Game Programming SkillsThere are a few, very rare, beginning game programming books that arewritten for nonprogrammers. To try and make things easy, they teach you towrite games in a programming language called Basic. Unfortunately, no gamesare written in Basic. It's far too slow for real games. Instead, gameprogrammers use a language called C (pronounced see-plus-plus). So if you

read one of these books, you'll have to start from scratch in a newprogramming language if you want to write a real game.Unlike any other book on the market, this book teaches nonprogrammers howto write games in C . When you finish reading this book, you'll bereasonably proficient with the programming language that real gameprogrammers use.Also, I explain and demonstrate the techniques used by professional gameprogrammers for animation and sound. In addition, I demonstrate that it issurprisingly easy to add essential physics to your games.It Teaches You How to Build A Real GameMany beginning programming books give you lots of nifty little sampleprograms that demonstrate the concepts they're teaching. However, very fewshow you how to pull all of those concepts into a complete game. That's a skillin itself. And the process of building a complete game often stumps people whoclearly understand how to write the individual pieces.By the end of this book, you'll see how to write a complete game. The gamewe'll be building is called "Invasion of the Slugwroths." It's a simple sidescroller (I'll explain that term later) similar to many games that were popularin the 1980s and '90s.Aren't most games today written in 3D?Well, yes. But writing 3D games is much harder. If you start with a sidescroller like Invasion of the Slugwroths, you'll learn fundamentals of gameprogramming before you have to deal with 3D concepts. It makes the learningprocess much easier and much more fun.It Provides Everything You Need to Write GamesNot only does this book teach you everything you need to get started in gameprogramming, it provides you with all of the tools as well. To write computerprograms, you need a compiler, linker, and debugger. These can easily cost 500. Have no fear. You don't need to cough up your hard-earned cash. You'llfind them all on the CD that comes with this book, at no extra cost.To save themselves from having to write program code that nearly every game

uses, many game programmers use a game engine. A game engine suppliesprogram code that performs the most common tasks in games. Professionalgame engines typically start at about 100. But don't go out and buy one. I'vesupplied one for you for free on the CD.In addition, I've provided programs for making music, creating a game'sgraphics, and testing your animations. With the development tools and thegame engine you get on the CD, the CD alone is well worth the cost of thebook.Both Teens and Adults Can Use This BookI have been asked for years by parents what book they should buy to get theirteenaged son or daughter started in game programming. Adults in theirtwenties and thirties also often ask me how they can get started. I havedifficulty recommending most books because they are really too technical.They're often too hard to understand for people who don't have a collegedegree in math, engineering, or computers.Although this book is not written specifically for teens, it is usable byeveryone. If you're 15 or over, you can use this book. Both teens and adultswill find everything they need right here. This book

Virtually every beginning game programming book I've ever seen assumes you know a programming language like C or C . That means that most beginning game programmers have to spend months or years learning to program before they can even start a game. What a waste. If you want to be a game programmer, but you have little or no programming experience, this book is for you. As I