Docsity

Beginning C++ Game Programming, Manuais, Projetos, Pesquisas de Cultura

Pré-visualização parcial do texto

Baixe Beginning C++ Game Programming e outras Manuais, Projetos, Pesquisas em PDF para Cultura, somente na Docsity!

BEGINNING C++ GAME PROGRAMMING MICHAEL DAWSON & 2004 by Thomson Course Technology PTR. All rights reserved. No part of this book may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, record- ing, or by any information storage or retrieval system without written permission from Thomson Course Technology PTR, except for the inclusion of brief quotations in a review. The Premier Press and Thomson Course Technology PTR logo and related trade dress are trademarks of Thomson Course Technology PTR and may not be used without written permission. All trademarks are the property of their respective owners. Important; Thomson Course Technology PTR cannot provide software support. Please contact the appropriate software manufacturer's techni- cal support line or Web site for assistance. Thomson Course Technology PTR and the author have attempted throughout this book to distinguish proprietary trademarks from descriptive terms by following the capitalization style used by the man- ufacturer. Information contained in this book has been obtained by Thomson Course Technology PTR from sources believed to be reliable. However, because of the possibility of human or mechanical error by our sources, Thomson Course Technology PTR, or others, the Publisher does not guarantee the accuracy, adequacy, or completeness of any information and is not responsible for any errors or omissions or the results obtained from use of such information. Readers should be particularly aware of the fact that the Internet is an ever-changing entity. Some facts may have changed since this book went to press. Educational facilities, companies, and organizations interested in multiple copies or licensing of this book should contact the publisher for quantity discount information. Training manuals, CD-ROMs, and portions of this book are also available individually or can be tailored for specific needs. ISBN: 1-59200-205-6 Library of Congress Catalog Card Number: 2004105652 Printed in the United States of America 0405060708BH10987654321 THOMSONM ab em COURSE TECHNOLOGY Professional m Trade m Reference Thomson Course Technology PTR, a division of Thomson Course Technology 25 Thomson Place Boston, MA 02210 http://www.courseptr.com TeamLRN SVP, Thomson Course Technology PTR: Andy Shafran Publisher: Stacy L. Hiquet Senior Marketing Manager: Sarah O'Donnell Marketing Manager: Heather Hurley Manager of Editorial Services: Heather Talbot Acquisitions Editor: Mitzi Koontz Associate Marketing Managers: Kristin Eisenzopf and Sarah Dubois Project Editor/Copy Editor: Cathleen D. Snyder Technical Reviewer: Shawn Holmes Thomson Course Technology PTR Market Coordinator: Amanda Weaver Interior Layout Tech: Susan Honeywell Cover Designer: Steve Deschene CD-ROM Producer: Arlie Hartman Indexer: Katherine Stimson Proofreader: Gene Redding iv ACKNOWLEDGMENTS | q lishing industry's dirty little secret—books are not “by” only one person. Yes, you see only one name on book covers (including this one), but it takes a team of ded- icated people to pull off the final product. Authors could not do it alone; I certainly could not have done it alone. So 1 want to thank all those who helped make this book a reality. E: book you've ever read perpetuates a big fat lie. And Im here to out the pub- Thanks to Cathleen Snyder for her dual role as Project Editor and Copy Editor. Cathleen kept things moving along. She knew when to nudge and when to lay back. On top of coor- dinating everything, she looked at the book from a reader's point of view, always striving to be sure things were clear. Thanks to Shawn Holmes, my Technical Editor. Shawn kept me honest and made sure my programs worked the way I said they did. Thanks to Sue Honeywell, my Layout Tech, and Gene Redding, my Proofreader. Their work makes the book look good —literally. Talso want to thank Mitzi Koontz, my Acquisitions Editor, for seeing the need for this book and having the will to move it forward when there was nothing out there quite like it. Finally, 1 want to thank all of the game programmers who created the games 1 played while growing up. They inspired me to work in the industry and create games of my own. I hope Ican inspire a few readers to do the same. TeamLRN TeamLRN ABOUT THE AUTHOR MicHaEL DAwsoN has worked as both a programmer and a computer game designer and producer. In addition to real-world game industry experience, Mike earned his bachelor's degree in Computer Science from the University of Southern California. Mike currently teaches game programming and design to students of all ages through UCLA Extension courses and private lessons. Visit his website at http://www.programgames.com to learn more or to get support for any of his books. TeamLRN Chapter 3 Chapter 4 Contents Using the switch Statement .......cccccccssicscicascaeasas 43 Mingo oops: siiiadbiridçias ini a ES La A Ra 46 E PME LES ara ans apa Deere ci ta foge Ep Op DS E pad Sp 48 Using break and continue Statements ........cicccciiiscsioos 50 Using Logical Operators ......ucucascsesesesea ess pera eae aã 52 Generating Random Numbers ........ccccciiiiccccicacaios 58 Understanding the Game Loop ...........icisiccicscasasãss 61 Introducing Guess My Number ...iiciscsisscssarcasariaaaãs 63 DATE ca EV RÁ SE PT Sa 2 Er q 66 Questions:and ANnGNORS qeprs std PR E a EM DEa Iraladçd 67 Disclisshgr. LESS” ses Ports gpa ias aa a A DS E E aa SS 68 ERBEEIRES: 5; os rara Paleta pio pato pol AALA efa aro fra as 69 For Loops, Strings, and Arrays: Word Jumble ........... rá He Terão polia 2 atira SERES salte Ai Ma ATT a E DA Su Fá! Understanding Objects «. agua ssians esposas ss pas ee araras 75 Esraá SE OBjaCiS sus ve her is da ae a E ÃO E pe ralo 7 UR APRE Siri ais dr nn got da id RE A Md 83 Uridersandina ESBeStnas sala pano pre aja igia ads e af ri 87 Using Multidimensional Arrays .....ccccicisiiisiciccscaiaãs 8 Introducing Word Jumble: . esses ce san die gie qra a Eat press avi 90 MUIPAR tara DEGnd TA a TE E E ds A LA IR 94 QUESTO NS o RENA RISIVEES: inss adro is dy E pata LÊ Ap CE o q LE io Ana 95 Biscussiom QUEsans ssa pena ssrancrdo pensas passa 97 ERCERRE Larg ns taty Dee SS EE AIRE pe arpão dito Eres ra 97 The Standard Template Library: Hangman ............. 99 Introducing the Standard Template Library ..........cccccciios 99 LIRA VERMES gs re ud nes e Pa o ds re Asa a sp tetra 100 ERing Hersiars, «opa za ira da Ba Md DT LTDA AMT RATES 105 já aro pes Vio to dh Gta TAROUCO co DART ODM DENTE 112 Understanding Vector Performance .......cccciiciciccceria 116 Examining Other STL Containers ........iccccicsiiciciciiãs 118 Planning: Yoúr Programs 22 202525 ngada dpiabad des dio la 119 Introducing Hangman ...iccscsiesica rasas eee seda a 120 vii viii Contents Chapter 5 Chapter 6 TeamLRN SARRO a ate spa pias ADE a PERA nr A Sd a Ei 124 Questiontand ARGAAS. ss vaç a see da LEG a E E De Tia d ES Lie gÊs 125 DISQUSSTO NI CILIESERANE: bb a dps TEA Tp E E Da E DS 126 EXERGIRES: o pista rir penta A SD UE pap OS 127 Furictions: MadULib us aos essa pcs ras DAL SA Sil ça 5 SMA 129 CrEStO UNOS ep bu Ayres Moraes DE Ea Pd 129 Using Parameters and Return Values ........ccccciiiiiiciio 132 Understanding Software Reuse .........ccicccasecasearases 137 Working with Scopes .sganasrassdciaar nas Ceia ad ndoçõe 4 na 138 tisinarelobal varablas. s miiisi Db ds nd ra lero dg ES 142 Usiha Global: Cansfanta «susana na si pira piapama Canna 145 Using Default Arguments .....cccccccisiciicesarenararanos 145 Overloading Functions ......cccccciiiscisscisciasscrraro 149 io lIfalti rem di (ara foto ASR o DR RD RO ND RR DR 151 Introducing the Mad Lib Game ....iiccccasecescarie rasas 153 DER ss dp gere ns era RR rd a di op 156 Quesionsant ANNE... qe sopa DERA DE 5 Linda DIS add sie 157 DIRCiES on ERES: quis pa dis DE a E sei a aba de SE ES 158 EXGICISOS 2 pato mia aa DpEv AN pa pia a aaa CANIS ad 159 References: Tic-Tac-Toe ........iiiiciiiiciiciris 161 ES IRS TERE NES pia Dhta artes sa, flo 0 a od gEa Spas dan 161 Passing References to Alter Arguments .........ccciiicisiioo 164 Passing References for Efficiency .......ccccccciccciiiireros 167 Deciding How to Pass Arguments .......iciccciciciiiicees 170 Returniho:Referentss. su ue cgi data sie dep DS nd aa a En 171 Introducing the Tic-Tac-Toe Game ......iccscccsciiisciraa 174 SERES ts sa o Dra pts a dd Pena RA Sd PEA di E RI 186 Questions and Answers .....iicccicisscesscaasacaserrescs 187 Ds Cissian ENTAStO RS: aa sd E EE Sd aa la e 189 EXGNGISES pera gas Spas ana mas lia a Dia sds ação 189 Contents Chapter 10 TeamLRN Inheritance and Polymorphism: Blackjack ............. 279 ODE REAIS: cs ums di aa Sri a SL 279 Controlling Access under Inheritance .....ccccccccilicccccco 284 Calling and Overriding Base Class Member Functions ........... 286 Using Overloaded Assignment Operators and Copy Constructors in DEE EA GS SS o atua anepata doer Doida alegar É Md cer pura den 290 Introducing Polymorphism .......ccciciiiccccscccciccrecta 291 Using ABSERACNETaSSOS «a san ti ig dE GU RI E E 296 Oigantatio Voge Code .. pras er pars pie De DA E A 299 Introducing the Blackjack Game ......ccccccccccciciicccers 303 SOIS ais DS 28 A E id e a 322 Questions and ANSWOIS .cssusmentararnadas nes nara ana s rs 323 Discussion Questions ...ccaususcanemenenegus que es exneges 324 EXQRCSOS sena PERES GATES PORT I GO RDI DAS FEEI GE 324 IDE ep es pe a a CT SAE DESCE 325 INTRODUCTION | q utting-edge computer games rival the best that Hollywood has to offer in visual effects, musical score, and pure adrenaline rush. But games are a form of enter- tainment unlike any other; they can keep players glued to their monitors for hours on end. What sets games apart and makes them so engrossing is interactivity. In a com- puter game, you don't simply sit back and watch a hero fighting against all odds, you become the hero. The key to achieving this interactivity is programming. Ifs programming that allows an alien creature, an attack squadron, or an entire army to react differently to a player in dif- ferent situations. Through programming, a game's story can unfold in new ways. In fact, as the result of programming, a game can respond to a player in ways that the game cre- ators might never have imagined. Although there are literally thousands of computer programming languages, C++ is the game industry standard. If you were to wander the PC game section of your favorite store and grab a title at random, the odds are overwhelming that the game in your hand would be written largely or exclusively in C++. The bottom line is this: If you want to program computer games professionally, you must know C++. The goal of this book is to introduce you to the C++ language from a game programming perspective. Although no single book can make you the master of two deep topics such as C++ and game programming, this book will start you on your journey. TeamLRN xi TeamLRN Introduction Chapter 4: The Standard Template Library: Hangman. You'll be introduced to a power- ful library—a toolbox that game programmers (and even non-game programmers) rely on to hold collections of things, such as items in a player's inventory. You'll also learn about techniques that can help you plan larger game programs. Chapter 5: Functions: Mad-Lib. You'll learn to break up your game programs into smaller, more manageable chunks of code. You'll accomplish this by discovering func- tions, the fundamental units of logic in your game programs. Chapter 6: References: Tic-Tac-Toe. You'll learn how to share information with different parts of your programs in an efficient and clear manner. You'll also see a brief example of Al (artificial intelligence) and you'll learn how to give a computer opponent a little bit of personality. Chapter 7: Pointers: Tic-Tac-Toe 2.0. You'll begin to discover some of the most low-level and powerful features of C++, such as how to directly address and manipulate your com- puter's memory. Chapter 8: Classes: Critter Caretaker. You'll learn how to create your own kinds of objects and define the ways they'll interact with each other through object-oriented pro- gramming. In the process, you'll create your very own critter to care for. Chapter 9: Advanced Classes and Dynamic Memory: Game Lobby. You'll expand on your direct connection with the computer and learn to acquire and free memory as your game programs require. You'll also see the pitfalls of using this “dynamic” memory and how to avoid them. Chapter 10: Inheritance and Polymorphism: Blackjack. You'll learn how to define objects in terms of other objects. Then you'll pull everything you've learned together into one big final game. You'll see how a sizeable project is designed and implemented by cre- ating a multiplayer version of the classic casino game of Blackjack (tacky green felt not included). Conventions Used in This Book Throughout the book, PIl throw in a few other tidbits. For example, I italicize any new term and explain what it means. I also use a number of special elements, including the fol- lowing: hint These are good ideas that will help you become a better game programmer. xiii xiv Introduction trap These point out areas where it's easy to make a mistake. trick These suggest techniques and shortcuts that will make your life as a game programmer easier. in the real world These are facts about the real world of game programming. The CD-ROM The CD-ROM that comes with this book includes the following: = All of the source code for the programs and games presented in the book = The Bloodshed Dev-C++ IDE, which uses the MinGW port of GCC as its compiler = A walkthrough of how to use the Dev-C++ IDE to create your first program = SGU's Standard Template Library Programmer's Guide = Useful links for C++, game programming, and industry news and information A Word about Compilers Imight be getting a little ahead of myself here by talking about compilers, but the issue is important because a compiler is what translates the source code you write into a program that your computer can run. I strongly recommend that you use the Dev-C++ IDE that's on the CD-ROM that came with this book. It's easy to use, includes a modern C++ com- piler, and best of all, it's free! I feel so strongly about this that Ive included a walkthrough on the CD-ROM (Appendix A, “Creating Your First C++ Program”) that explains how to compile your first C++ program using Dev-C++. So, what are you waiting for? Grab that CD-ROM, install Dev-C++, and check out the walkthrough. trap | hate to pick on any particular compiler or software company, but | have to say that | cannot rec- ommend Microsoft Visual C++ 6.0. Its compiler fails to correctly implement C++ in some impor- tant ways. As a result, a few of the programs in this book will not compile under Visual C++ 6.0. | do my best to point out the issues when they arise in the programs in the book. If you want to go with Microsoft, | recommend their current line of Visual Studio .NET products, which implement the C++ standard quite faithfully. TeamLRN 2 Chapter 1 = Types, Variables, and Standard I/O: Lost Fortune m Jts fast. Well-written C++ programs can be blazingly fast. One of C++'s design goals is performance. And if you need to squeeze out even more performance from your programs, C++ allows you to use assembly language—the lowest-level human-readable programming language—to communicate directly with the com- puter's hardware. = Tt's flexible. C++ is a multi-paradigm language that supports different styles of programming, including object-oriented programming. Unlike some other modern languages, though, C++ doesn't force one particular style on a programmer. = It's well supported. Because it is the dominant game programming language, there's a large pool of assets available to the C++ game programmer, including graphics APIs and 2D, 3D, physics, and sound engines—all of which allow a pro- grammer to leverage previous work to greatly speed up the process of writing a new game. Creating an Executable File The file that you run to launch a program—whether you're talking about a game or a business application—is an executable file. There are several steps to creating an executable file from C++ source code (a collection of instructions in the C++ language). The process is illustrated in Figure 1.1. Editor Source Code Compiler Object Code tl Linker Executable . File Figure 1.1 The creation of an executable file from C++ source code É TeamLRN Introducing C++ 3 1, First, the programmer uses an editor to write the C++ source code, a file that usu- ally has the extension .cpp. The editor is like a word processor for programs; it allows a programmer to create, edit, and save source code. . After the programmer saves a source file, he invokes a C++ compiler-—an applica- tion that reads source code and translates it into an object file. Object files usually have the extension .obj. . Next, a linker links the object file to any external files as necessary, and then creates the executable file, which generally ends with the extension .exe. At this point, a user (or gamer) can run the program by launching the executable file. hint The process I've described is the simple case. Creating a complex application in C++ often involves multiple source code files written by a programmer (or even a team of programmers). To help automate this process, is common for a programmer to use an all-in-one tool for development, called an IDE (Integrated Development Environment). An IDE typically combines an editor, a compiler, and a linker, along with other tools. Popular commercial IDEs for Windows include Visual Studio .NET and C++Builder Studio. Dev-C++ is an excellent free and open source IDE for Windows (and just so happens to be included on the CD-ROM that came with this book). Dealing with Errors When I described the process for creating an executable from C++ source, 1 left out one minor detail —errors. If to err is human, then programmers are the most human of us. Even the best programmers write code that generates errors the first (or fifth) time through. Programmers must fix the errors and start the entire process over. Here are the basic types of errors yowll run into as you program in C++: TeamLRN = Compile errors. These occur during code compilation. As a result, an object file is not produced. These errors are often syntax errors, meaning that the compiler doesn't understand something. They're often caused by something as simple as a typo. Compilers can issue warnings, too. Although you usually don't have to heed the warnings, you should treat them as errors, fix them, and recompile. Link errors. These occur during the linking process and may indicate that something the program references externally can't be found. These errors are usually solved by adjusting the offending reference and starting the compile/link process again. Run-time errors. These occur when the executable is run. If the program does something illegal, it can crash abruptly. But a more subtle form of run-time error, a logical error, can make the program simply behave in unintended ways. If you've TeamLRN Writing Your First C++ Program Wrogram FilesWicrosoft Visual StudioWMyPr Figure 1.2 Your first C++ program displays the two most infamous words in computer gaming. You can type the code in yourself, but Pve also provided the source code for all of the pro- grams on the CD-ROM that came with this book. The code for this program is in the Chapter 1 folder on the CD-ROM; the file name is game over.cpp. /! Game Over (th first CH program include int main0) | std::cout << "Game Over!” << std::endl; return O; ] hint For step-by-step instructions on how to create, save, compile, and run the Game Over program using Dev-C++, check out Appendix A, “Creating Your First C++ Program,” on the CD-ROM that came with this book. If you're using another compiler or IDE, check its documentation. Commenting Code The first two lines of the program are comments. /! Game Over (HA first CH program Chapter 1 = Types, Variables, and Standard I/O: Lost Fortune Comments are completely ignored by the compiler; they're meant for humans. They can help other programmers understand your intentions. But comments can also help you. They can remind you how you accomplished something that might not be clear at first glance. You can create a comment using two forward slashes in a row (//). Anything after this on the rest of the physical line is considered part of the comment. This means you can also include a comment after a piece of C++ code, on the same line. hint You can also use what are called C-style comments, which can span multiple lines. All you have to do is start the comment with /* and end it with */. Everything in between the two markers is part of the comment. Using Whitespace The next line in the program is technically a blank line. The compiler ignores blank lines. In fact, compilers ignore just about all whitespace—spaces, tabs, and newlines. Like com- ments, whitespace is just for us humans. Judicious use of whitespace helps make programs clearer. For example, you can use blank lines to separate sections of code that belong together. 1 also use whitespace (a tab, to be precise) at the beginning of the two lines between the curly braces to set them off. Including Other Files The next line in the program is a preprocessor directive. You know this because the line begins with the | symbol. itinclude The preprocessor runs before the compiler does its thing and substitutes text based on var- ious directives. In this case, the line involves the include directive, which tells the pre- processor to include the contents of another file. Linclude the file iostream, which is part of the standard library, because it contains code to help me display output. 1 surround the filename with less than (<) and greater than (>) characters to tell the compiler to find the file where it keeps all the files that came with the compiler. A file that you include in your programs like this is called a header file. Defining the main() Function The next non-blank line is the header of a function called main(). int main() TeamLRN