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

3y ago
34 Views
2 Downloads
2.79 MB
602 Pages
Last View : 12d ago
Last Download : 3m ago
Upload by : Esmeralda Toy
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 explains the terms andideas it uses. It provides you with a lot of the essential program code(programs are built from program code) you need to write games. It teachesprogramming, computer graphics, and games. It's one-stop shopping.

What's in This Book?This book is divided into five main parts.Part 1 gives an overview of the tools and skills you'll need to write games.It also covers the most basic programming concepts.Part 2 dives into object-oriented programming, which is a style ofprogramming used by all professional game programmers.Part 3 shows how game programs are constructed. Here, you'll write yourfirst gamePing, a clone of the ancient Pong game. You'll also learn to addsounds to your games.Part 4 raises your C skills to a level that enables you to write realgames.Part 5 enables you to pull everything you've learned together to write thegame Invasion of the Slugwroths, and leaves you fully equipped to go onand write your own games.In addition, I provide you with a glossary that explains all of the technicalterms presented in the book. I've also compiled an extensive list of books thatI recommend you read after you finish reading this one. That will help youmove forward into topics like 3D graphics. You'll find the list of recommendedreading on the CD that comes with this book.

System RequirementsTo use the tools included with this book and to run the sample programs youcompile as you read the chapters, you'll need a computer with at least thefollowing:500 MHz Pentium III computer.Minimum 128 MB of system RAM.Windows 98 Second Edition or later operating system.OpenGL-compatible video adapter card. Virtually all video cards todayare compatible with OpenGL.300MB of free space on your computer's hard drive so that you caninstall all of the tools and source code. You might not need this muchspace if you choose not to install some of the tools.

Free Stuff on the CDNoteIf the HTML page is not displayed when you insert the CD, click theWindows Start button in your Taskbar and select Run. In the dialogbox that appears, type d :\AutorunPro.exe, where d is the letter ofyour CD/DVD-ROM drive.On the CD, you'll find an assortment of essential tools for game programmers.Although I list them here, you can get more information on them by insertingthe CD into your CD- or DVD-ROM drive. When you do, an HTML page willautomatically display. That page contains a list of everything on the CD. Inthat list is an item called Tools, Tools, Tools. That item provides a link to apage in the CD that explains what the tools are and how to install them.LlamaWorks2D This is the game engine you'll use to write your games.I wrote this version of LlamaWorks2D especially for this book. Buildinggames with LlamaWorks2D will save you many hours of programming. Inaddition, it handles many of the repetitive and tedious tasks you have todo in order to get a game up and running. Using LlamaWorks2D, you'llspend less time with the mechanics of Windows programs and more timeon games.Dev-CPP The free Dev-C compiler is a combination of a compiler,linker, debugger, and program editor. You need all of these tools in orderto write games. Therefore, you must install this program first.Audacity Audacity is an excellent sound editor that is available for free.With Audacity, you'll be able to record sound effects and edit them foryour games.GIMP You'll need a program for drawing the images and animations yourgames use. Windows Paint, which is a free program that comes withWindows, just doesn't have enough features for you to produceprofessional graphics. Therefore, I've provided a program called GNUImage Manipulation Program (GIMP). With this powerful program, you'llhave what you need to draw everything that appears on the screen when

your game runs.And Much More In addition to the tools mentioned here, you'll finddocumentation for important graphics and sound technologies, anoutstanding music production program, a graphics file format conversiontool, a 3D image production program, and an animation tester. Pleasesee the CD for more details.Installation InstructionsI've made installing the programs in the CD extremely straightforward. On themain page that is displayed when you insert the CD, there is an entry calledTools, Tools, Tools. In that item is a link. When you click the link, you'll see apage called Installing the Free Tools. Find the tool you want to install on thatpage. For most of the tools, there is an installation link. Clicking this link runsthe install program automatically. A few of the tools must be copied to yourhard drive. The Installation section for that tool contains instructions on howto do that.Compiling The Sample ProgramsThis book contains numerous sample programs that demonstrate the conceptsit teaches. In order to view the programs, you must first compile them. Theinstructions for compiling them are slightly different for each program. Tomake things more convenient for you, I've written instructions for how tocompile every program. You'll find the compilation instructions on the CD. Tosee them, insert the CD into your CD/DVD-ROM drive. On the HTML page thatappears, you'll find a list item called Compilation Instructions. Click that link.At this point, an HTML page appears called Compiling the Sample Programs.This page contains a list of all of the sample programs grouped by chapter. Tosee how to compile a particular program, click on its link in the list. Thecompilation instructions for that program will appear.In addition, I've provided a compiled version of each program. They're in theBin (short for binary) folder for their respective chapters. You'll see a link foreach Bin folder on the Compiling the Sample Programs page.

Who Am I?Hi, I'm David Conger. I've been in the computer industry since 1981, when Itook my first professional programming contract shortly after entering college.Most of my career has been focused on graphics, games, and networkprogramming. After graduati

Customizing Your Game with Inheritance Summary Part 3: The Essentials of Game Development Chapter 7. Program Structure Program Structure File Structure A Game Called Ping Summary Chapter 8. Sound Effects and Music Sound Effects and Music Are Emotion Storing Sound Data Sound Effects in LlamaWorks2D Noise, Sweet Noise Play That Funky Music, Geek .

Related Documents:

The Games organised at Olympia led to the development of the Panhellenic Games. These included: - The Games at Olympia (Olympic Games): every four years - The Games at Delphi (Pythian Games), 582 B.C.: every four years (third year of each Olympiad) - The Games at the Isthmus of Corinth (Isthmian Games), from 580 B.C.:

Section 3: Playground Markings Games 16 Section 4: Skipping, Hula Hoop & Elastics 25 Section 5: Catching games 32 Section 6: Relay games 41 Section 7: Ball games 48 Section 8: Fun games 59 Section 9: Frisbee games 66 Section 10: Parachute games 70 Section 11: Clapping and rhyming games 74 Useful websites 79

Olympic Winter Games medals Olympic Winter Games posters Olympic Summer Games posters Olympic Summer Games mascots Olympic Winter Games mascots The sports pictograms of the Olympic Summer Games The sports pictograms of the Olympic Winter Games The IOC, the Olympic Movement and the Olympic Games The Olympic programme evolution Torches and torch .

Regional Games and Multi-Sport Games (such as Pan American Games, African Games, European Games, Commonwealth Games, Mediterranean Games, Francophone Games, Youth Olympic Games) International Tournaments organised by the IJF (Grand Prix, Grand Slam, Masters) or under its auspices (continental open and cups),

Olympic Summer Games posters Olympic Summer Games mascots Olympic Winter Games mascots The IOC, the Olympic Movement and the Olympic Games The Olympic programme evolution The Olympic stadiums of the Summer Games The sports pictograms of the Olympic Summer Games The sports pictograms of the Olympic Winter Games .

Zero-Sum Games vs. Non-Zero-Sum Games 29 Static vs. Dynamic Games; Repeated Games 30 Cooperative vs. Non-Cooperative Games 30 Other Key Game Theory Concepts 31 Threats and Rewards (Promises) 31 Credibility 31 Sample Game with Threats 31 The Threat as a Strategy 32 Games of Chance: Uncertainty and Risk 32 Chapter 3 Modeling Games with Computer .

music (Guitar Hero), to first-person shooter games (Halo), to more civically oriented games (Civilization). Some games have violent content, but by no means all. Almost all youth who play games that contain violent content also play games that do not.2 Youth play these games on computers,

gaming platform. According to [17] games can be divided into four di erent cate-gories; singleplayer games, pseudo multiplayer games, turn-based multiplayer games and real-time multiplayer games. The article rules out real-time multiplayer games for mobiles, since they require a lot of bandwidth and a stable connection; this is