TE AM FL Y Game Programming All in One Bruno Miguel Teixeira de Sousa © 2002 by Premier Press 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, recording, or by any information storage or retrieval system without written permission from Premier Press, except for the inclusion of brief quotations in a review Premier Press, Inc is a registered trademark of Premier Press, Inc Publisher: Stacy L Hiquet Marketing Manager: Heather Buzzingham Managing Editor: Sandy Doell Acquisitions Editor: Mitzi Foster Series Editor: André LaMothe Project Editor: Heather Talbot Technical Reviewer: André LaMothe Copy Editor: Jenny Davidson Interior Layout: Marian Hartsough Cover Design: Mike Tanamachi CD-ROM Producer: Keith Davenport Indexer: Kelly Talbot Proofreaders: Anne Owen, Fran Blauw, Linda Seifert Microsoft, DirectX, DirectSound, and DirectInput are registered trademarks of Microsoft Corporation Jasc and Paint Shop Pro are trademarks or registered trademarks of Jasc Software, Inc All other trademarks are the property of their respective owners Important: Premier Press cannot provide software support Please contact the appropriate software manufacturer’s technical support line or Web site for assistance Premier Press and the author have attempted throughout this book to distinguish proprietary trademarks from descriptive terms by following the capitalization style used by the manufacturer Information contained in this book has been obtained by Premier Press from sources believed to be reliable However, because of the possibility of human or mechanical error by our sources, Premier Press, 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 ISBN: 1-931841-23-3 Library of Congress Catalog Card Number: 2001096486 Printed in the United States of America 02 03 04 05 06 RI 10 De todas as coisas que quero, és a única coisa que eu preciso Para ti, Ana Acknowledgments N ow is the time I should go up to the stage, get the Oscar, and recite a booklength script of all the people that helped make this book However, the thank you would probably be as big as this book, so to prevent from forgetting anyone, I would like to thank everyone that directly or indirectly made this book possible On the technical side, I would like to thank the people at Premier Press for giving me the opportunity to write this book I would also like to thank my editors, Emi Smith, Mitzi Foster, Heather Talbot, and Jenny Davidson for all their patience and all they had to put up with (Yes, the usual delays and the incessant questions.) Please remember that what you are reading is not a book that I wrote myself, but one that comprises the work of many talented people who are usually forgotten I would also like to thank André LaMothe for reviewing the book On the personal side, I would like to thank my mom and dad for their support and love during my life, and of course, for paying those enormous Internet bills when I was still learning game programming I would also like to thank all of my friends and relatives for their support not only with the book, but also with my life I would like to send a special thanks to Diana for always being there for me whenever I needed her Last, and probably most important, I would like to thank Ana for her love, support, patience, and just about everything I love you from the bottom of my heart About the Author BRUNO MIGUEL TEIXEIRA DE SOUSA began programming at age 11 Although he began his programming career at age 15 as a database programmer in Visual Basic, he never lost his passion for game development Two years later, he began a fulltime career performing general game programming for a UK-based company He has been using C++ for more than years and remains an avid game hobbyist RONALD PENTON wrote Chapter 17 Ron started programming on his Tandy 1000TL way back in 1989, when he became interested in making games, rather than just playing them Ever since then, he has been on a never-ending quest to learn more about computers and become more efficient at programming them He started school at the Rochester Institute of Technology in 1998, and is currently finishing his bachelor’s degree in computer science at The University of Buffalo Contents at a Glance Introduction xxxvi Part One C++ Programming Chapter Chapter Chapter Chapter Chapter Chapter Chapter Chapter Chapter Introduction to C++ Programming Variables and Operators 25 Functions and Program Flow 51 Multiple Files and the Preprocessor 95 Arrays, Pointers, and Strings 107 Classes 153 Developing Monster 197 Streams 245 Basic Software Architecture 279 Part Two Windows Programming 297 Chapter 10 Chapter Chapter Chapter Chapter Chapter 11 12 13 14 15 Designing Your Game Library: Mirus 299 Beginning Windows Programming 317 Introduction to DirectX 357 DirectX Graphics 369 DirectInput 521 DirectSound 567 Contents at a Glance Part Three Hardcore Game Programming 595 Chapter 16 Chapter 17 Introduction to Game Design 597 Data Structures and Algorithms 609 Chapter 18 The Mathematical Side of Games 661 Chapter 19 Introduction to Artificial Intelligence 697 Chapter 20 Introduction to Physics Modeling 723 Chapter 21 Building Breaking Through 791 Chapter 22 Publishing Your Game 851 Part Four Appendixes 863 Appendix A Appendix B Appendix C Appendix Appendix Appendix Appendix Appendix D E F G H What’s on the CD-ROM 865 Debugging Using Microsoft Visual C++ 870 Binary, Hexadecimal, and Decimal System 874 A C Primer 877 Answers to the Exercises 885 C++ Keywords 893 Useful Tables 895 More Resources 902 Index 907 ix Contents Letter from the Series Editor xxxiv AM FL Y Introduction xxxvi TE Part One C++ Programming Chapter Introduction to C++ Programming Why Use C++? Setting Up Visual C++ Creating a Workspace Creating Projects Creating and Adding Files Your First Program: “Hello all you happy people” Structure of a C++ Program 12 Program Design Language 12 Program Source and Compiling 14 Objects and Linking 14 Executable 15 Commenting 16 Catching Errors 17 Warnings 20 Summary 21 Questions and Answers 21 Exercises 23 Team-Fly® Contents Chapter Variables and Operators 25 Variables and Memory 26 What Type of Variables Are There? 27 Using Variables in Your Programs 30 Declaring a Variable 30 Using Variables 31 Initializing Variables 32 Variable Modifiers 33 Const 33 Register 35 Variable Naming 36 Redefining Types 36 What Is an Operator? 37 Assignment Operator 37 Mathematical Operators 37 Unary Operators 38 Binary Operators 39 Compound Assignment Operators 41 Bitwise Shift Operators 41 Relational Operators 42 Conditional Operator 43 Logical Operators 44 Operator Precedence 45 Summary 47 Questions and Answers 48 Exercises 48 xi 940 Index operators (continued) new, 123-126 operands, 37 overloading, 164-166 pointers, 126-129 precedence, 45-47 relational, 42-43 shift, 41-42 sizeof, 48 ternary, 43 OR (||) operator, 45 orientation, vectors, 668 ostream class, 251-253 output See I/O output window, 17 OutputString function, 200-201, 211 overloading functions, 59 operators, 164-166 P paddles (Breaking Through game), 804-809 pAge pointer, 127-128 parameters arguments, 57 constructors, 162 default, 58-59, 66 functions, 56 Height, 56 HINSTANCE, 326 iMessage, 336 LPSTR lpCmdLine, 327 size t, 134 unsigned short, 205 void, 56 Width, 56 WORD, 205 parent-child relationship, 625 particle systems building, 773-774, 780-784 flames, 784-787 rendering, 782-784 simulating, 781, 782 particles building, 770-773 interpolation, 776-777 rendering, 775-778 simulating, 775 velocity, 778-780 passing arrays, 120-122 patterns algorithm, 710-713 PCM (Pulse Code Modulation), 577 PDL (Program Design Language), 12-14 PeekMessage function, 337-339 perceptrons, 706 perp-dot products (vectors), 677 PerpDotProduct function, 677 perpendicular vectors, 675-676 Perpendicular function, 675-676 physics acceleration, 732 angular, 733 linear, 733 advanced techniques, 764-770 Cartesian plane, 729-730 classic mechanics, 724 collisions conserving momentum, 755-756 impulse method, 756-761 maintaining momentum, 755 simulating, 756-763 damping, 762 engines, 725-728 forces, 735-736 linear, 736-739 resulted, 740-741 torque, 739-740 frame rates, 763-764 friction, 748-749 inclines, 752 kinetic friction, 752 normal force, 749-751 static friction, 751-752 using, 753-755 gravity, 741 Law of Universal Gravitation, 742-743 planets, 743-745 projectiles, 745-748 Index international system, 724 kinetics, 724 mass, 728-729 center, 734-735 Newtonian, 724 particle systems building, 773-774, 780-784 flames, 784-787 rendering, 782-784 simulating, 781-782 particles building, 770-773 interpolation, 776-777 rendering, 775-778 simulating, 775 velocity, 778-780 position, 729-730 time, 729 velocity, 731-732 angular, 732 linear, 731-732 speed, 732 weight, 729 pInterest pointer, 127-128 pitch, surfaces, 392-393 pixels blending, 417-418 color (alpha), 416 planes, Cartesian, 435, 729-730 planets, gravity, 743-745 Play function, 306-307, 584-585 players coordinates, 216-218 creating, 216-218 lives, 28, 216-218 scores, 216-218 playing Breaking Through game, 796-797 mrSound class, 584-585 POINT structure, 353 pointers arrays, 119-122 functions, 120-122 buffers, 130-131 declaring, 117 handles, 326 implementing, 117-119 initializing, 117 interfaces, 376 message handlers, 328 mrSurface class, 475-476 operators, 126-129 pAge, 127-128 pInterest, 127-128 strings, 132 surfaces, 393-394 this, 166 variables, 116 PointerValues variable, 128-129 Poll function, 562-563, 566 polling mrJoystick class, 562-563, 566 mrKeyboard class, 566 mrMouse class, 566 polygons See also animation; images; objects; physics; primitives convex, 437 drawing, 437-438 primitives circles, 438 lines, 433-437 polygons, 437-438 types, 409-410 render states, 406 rendering, 401-410 rotating, 430-433 mrAnimation class, 497-498 scaling, 429-430 size, 429-430 textures, 371, 398-400 coordinates, 399-400 translating, 428-429 vertex buffers, 371 vertices, 397-398, 405 coordinates, 401 polymorphism, 178-181 position grids, 113-114 physics, 729-730 relative, 788 windows, 351-353 941 942 Index creating, 9-12, 322-323 developing, 12-14 DOS, executing, 66 files, compiling, 14 finite state machines, 713-715 header files, 10 Hello World, 9-12 include files, 10 input/output, 10-11 namespaces, std, 11 objects, linking, 14-15 PDL, 12-14 pseudocode, 12-14 source code, 14 streams, 10-11 tokens, 12 UNIX, Windows creating, Visual C++, 322-323 Project menu command, Add to Project, projectiles, gravity, 745-748 projects creating, 322-323 files, MFC AppWizard (dll), MFC AppWizard (exe), setting up, 6-8 tools, Win32 API, 322 Win32 Application, Win32 Console Application, Win32 Dynamic-Link Library, Win32 Static Library, Projects tab (New dialog box), properties mrABO class, 505-506 mrJoystick class, 560-561 mrMouse class, 544-546 protected classes, 159-160 protected keyword, 159-160 pseudocode, 12-14 TE AM FL Y PostOrder function, 631 PostQuitMessage function, 336 #pragma directive, 20-21, 101-102, 105-106 precedence, operators, 45-47 prefixes, 165 PreOrder function, 630-631 preprocessors defining, 100-101 directives See directives macros, 104-105 preventing multiple headers, 101-102 Present function, 385 primitives See also animation; images; objects; physics; polygons circles, 438 lines Cartesian plane, 435 deltas, 437 drawing, 433-437 slope, 433 polygons, 437-438 types, 409-410 private classes, 159, 285-288 private keyword, 159 probability overview, 688-689 sets, 689 intersecting, 690-691 unions, 689-690 Process function, 221, 242-243, 839 ProcessGame function, 236-238 ProcessLost function, 242 ProcessLostLife function, 241 ProcessMenu function, 235-236 ProcessSplash function, 235 Program Design Language (PDL), 12-14 programs building, 323-326 headers, 326 instances, 326 window state, 327 code blocks, 11 commenting, 16 Team-Fly® Index public classes, 159, 285-288 public keyword, 159 publishers, 853-854 publishing games bug reports, 856-857 contracts, 854-856 marketability, 852-853 milestones, 856-857 NDAs, 855 publishers, 853-854 references, 861 royalties, 856 self-publishing, 857 Pulse Code Modulation (PCM), 577 put function, 251-252 Q QueryPerformanceCounter function, 313-314 QueryPerformanceFrequency function, 311-312 queues, messages, 322 quick sorts, 651-655 QuickSortInt function, 653 quotation marks (“”), 10 R radians angles, 662-664 circles, 662-664 RAM (random access memory), 26 rand function, 80-83 random motion algorithm, 707-709 random-access data structures, 612 randomizing numbers, 80-83 RandomLeap function, 218 rasterizing lines, 433-437 Cartesian plane, 435 deltas, 437 read function, 267-268, 461-462 Read function, 200-201, 212 ReadConsole function, 212 reading binary streams, 267-268 read-only memory (ROM), 26 943 real-time loops, 336-341 rectangles (collision detection), 426-427 recursive functions, 64-66 recursive structures, 624 Red Bull, 519 red-black trees, 647 references, games, 861 register keyword, 35-36 RegisterClass function, 331 registers (variables), 35-36 reinterpret casting, 180 relational operators, 42-43 relative mode, 530-532 relative positions, 788 release executables, 15 Release function, 572 releasing objects, 386-387 Remove function, 635, 638-646 RemoveChild function, 629 RemoveCurrentChild function, 628 RemoveCurrentItem function, 620-622 Render function, 304-305, 478, 496-497, 511, 775778, 782-784 rendering See also drawing mrABO class, 511 mrAnimation class, 496-500 mrSurface class, 478 particle systems, 782-784 particles, 775-778 polygons, 401-410 render states mrScreen class, 447-448 polygons, 406 surfaces, 389-396 textures, 401-410 windows, 385 resolution, 378-379 resulted forces (physics), 740-741 returning values, 12 RLE (Run-Length Encoding), 657-659 RLECompressIng function, 658-659 ROM (read-only memory), 26 root function, 629 Rotate function, 305, 517 944 Index rotating images, 430-433 mrABO class, 517-518 polygons, 497-498 rows (matrices), 678 royalties, 856 rules Breaking Through game, 793 Craps game, 84 Monster game, 215-216 Run function, 302, 343 Run-Length Encoding (RLE), 657-659 S Save function, 274 SaveGame function, 847 saving games, 270-277 scalars, 668, 673 scaling images, 429-430 scope, variables, 60-63 scores, player, 216-218 screens clearing, 201, 208-210 coordinates, 208-209 Direct3D backbuffering, 447-448 bitdepth, 456-457 clearing, 372-376 color, 378-379 constructor, 442 cursors, 456 destructor, 443 developing, 439-458 drawing, 450-453 formats, 446-447 frames, 448-449 initializing, 442-443 render states, 447-448 resolution, 378-379 screen modes, 444-445, 454-455 full screen mode, 379-380 functionality, 303 game design, 217 handles, 200, 202-203 output, 11 windowed mode, 379-380 Search function, 635-637 searching nodes, 635-637 seeds (numbers), 83 seekg function, 268-269, 461-463 seekp function, 269 self-publishing games, 857 semicolon (line-ending token), 12 sequential data structures:, 612 service packs (Visual C++), 345 Set Active Configuration command (Build menu), 15 Set Active Project Configuration dialog box, 15 SetActiveTexture function, 305, 488 SetBackgroundColor function, 200-201, 204-207 SetColor function, 516 SetColorKey function, 508-509 SetConsole function, 221 SetConsoleCursorPosition function, 211 SetConsoleTextAttribute function, 205-207 SetConsoleTitle function, 208 SetCooperativeLevel function, 532, 543, 574 SetCurrentAnimation function, 511 SetCurrentFrame function, 501 SetDataFormat function, 530-532, 543 SetImageBuffer function, 461 SetMode function, 444-445 SetModeClear function, 303 SetPosition function, 200-201, 210-211, 272-273, 351-352, 516 SetProperty function, 544-546, 560-561 SetRadius function, 516 SetRawImage function, 474 SetRenderState function, 406, 447-448 sets intersecting, 690-691 probability, 689 SetSize function, 354, 516, 802 SetTextColor function, 200-201, 207 SetTexture function, 408 Index SetTextureState function, 406-407 setting buffers, 130-131 cursors, 201, 210-211 setting up Direct3D, 377-384 DirectInput, 523 Visual C++, files, 8-9 projects, 6-8 workspaces, 5-6 SetTitle function, 200-201, 208 SetupDirect3D function, 377-384 SetVolume function, 306, 584 SetWindowLong function, 347-348 SetWindowPos function, 351-352, 354 SetWindowText function, 345-346 shift operators, 41-42 short keyword, 28-29 Show function, 221, 231-232, 355 ShowCursor function, 303, 456 ShowExit function, 230-231 ShowGame function, 227-228 ShowHelp function, 70 ShowLost function, 230 ShowLostLife function, 229-230 ShowWindow function, 345, 355 ShowWon function, 229 signed keyword, 28-29 signed variables, 28 Simonyi, Charles, 291 Simulate function, 761-763, 768, 775, 781-782 simulating collisions, 756-763 particle systems, 781-782 particles, 775 sin function, 666 sines angle relations, 666-667 look-up tables, 114-116 triangles, 664-666 single quotes (ASCII conversion characters), 210 singletons, 186-189 advantages, 303, 316 singly linked lists, 613-615 size arrays, 109, 122-126, 151 functions, 134 images, 429-430 streams, 278 strings, 135-136, 171 surfaces, 392-393 textures, 403 variables, 30, 48 vectors, 674, 676 windows, 345, 354 size t parameter, 134 sizeof operator, 48 slope lines, 433 physics, 752 Smugglers game, 857-859 sorting data bubble sorts, 648-651 comparison, 655-656 declining iterations, 650 quick sorts, 651-655 swap counters, 649 sound amplitude, 568 CD players, 306-307 cycles, 568 digital, 569 Directsound, 569-570 frequency, 568 functionality, 306 managers, 186 MCI, 586-587 mrCDPlayer class, 588-593 mrSound class audio blocks, 583 buffers, 580-582 defining, 575-576 developing, 575-586 implementing, 576-579 locking, 582-583 playing, 584-585 volume, 584 945 946 Index sound (continued) mrSoundPlayer class cooperative levels, 574 defining, 571-572 developing, 571-575 implementing, 572 initializing, 573 PCM, 577 synthesized, 569 theory, 568-569 waveforms, 569 waves, 568 Sound component (Mirus), 306-307 source code, 14 source files, 96-99 speed (physics), 732 splay trees, 647 sprintf function, 145-147 Square function, 55 srand function, 83 Standard Template Library (STL), 611 Start function, 627 StartFrame function, 303, 448-449 starting points, vectors, 694 StartIterator function, 616 StartNewGame function, 221, 232-233 state devices, 523-524 fuzzy logic, 715 games (universe problem), 707 mrJoystick class, 563-565 mrKeyboard class, 534-537 mrMouse class, 548-551 windows, 327 statements break, 75, 80 code blocks, 66-67 conditional, 67-70 switch, 78-79 continue, 76-77 do…while, 72-73 else, 70 for, 73-75 game design, 284 if, 67-70 compared to switch, 78-79 switch, 77-80, 336 while, 70-72 states finite state machines, 713-715 render See render states static casting, 180-181 static friction, 751-752 static keyword, 185 static libraries, static members, 185 static variables, 62-63 status games, 220-221 streams, 256-258 std namespace, 11 stdlib.h header file, 83 STL (Standard Template Library), 611 Stop function, 306-307, 585 storing variables, 27 strcat function, 136-138 strchr function, 140-142 strcmp function, 169-170 strcomp function, 138-140 strcpy function, 133-134, 169 streams binary, 246-247 markers, 268-269 reading, 267-268 writing, 264-267 closing, 253, 255-258 defined, 10-11 EOF, 250 extraction operator (>>), 251 file streams, 253 I/O, 247-253 input, 247-251 output, 251-253 insertion operator (