Creating Games in C++: A Step-by-Step Guide By David Conger, Ron Little Publisher: New Riders Pub Date: February 21, 2006 Print ISBN-10: 0-7357-1434-7 Print ISBN-13: 978-0-7357-1434-2 Pages: 464 Table of Contents | Index Do 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 and CD-ROM Author David Conger starts at square one, introducing the tools of the trade and all the basic concepts 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 take you 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 as you learn Bio: David Conger has been programming professionally for over 23 years Along with countless custom business applications, he has written several PC and online games Conger also worked on graphics firmware for military aircraft, and taught computer science at the university level for four years Conger has written numerous books on C, C++, and other computer-related topics He lives in western Washington State and has also published a collection of Indian folk tales Creating Games in C++: A Step-by-Step Guide By David Conger, Ron Little Publisher: New Riders Pub Date: February 21, 2006 Print ISBN-10: 0-7357-1434-7 Print ISBN-13: 978-0-7357-1434-2 Pages: 464 Table of Contents | Index Copyright Acknowledgments Introduction What's Different About This Book What's in This Book? System Requirements Free Stuff on the CD Who Am I? Part 1: The Really Basic Stuff Chapter 1 What it Takes to be a Game Programmer Programming Skills Computer Graphics Skills Game Design Skills Art Skills Sound and Music Skills Summary Chapter 2 Writing C++ Programs Introducing the Dev-C++ Compiler Programming in C++ Essential Math Operators Loops While Loops Do-while loops Windows Programming Game Programming Summary Part 2: ObjectOriented Programming in Games Chapter 3 Introducing Object-Oriented Programming Software Objects Classes Logical Operators The If-Else Statement Namespaces and Scope Resolution A Brief Word About Structures Summary Chapter 4 Introducing the LlamaWorks2D Game Engine A Step-by-Step Overview How Does Llamaworks2D Work? A Stationary Ball A Bouncing Ball Getting Good Results Summary Chapter 5 Function and Operator Overloading What Is Overloading? Implementing a Vector Class with Overloading Summary Chapter 6 Inheritance: Getting a Lot for a Little What Is Inheritance? Deriving Classes Protected Members Overriding Base Class Functions 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 Boy Summary Part 4: Graduating to Better C++ Chapter 9 Floating-Point Math in C++ Getting into the Guts of Floating-Point Numbers Case Study: Floating-Point Numbers and Gamespaces Summary Chapter 10 Arrays What Are Arrays? Declaring and Using Arrays Initializing Arrays Problems with Array Boundaries Summary Chapter 11 Pointers Why Are Pointers Important to Games? Declaring and Using Pointers Pointers and Dynamic Memory Allocation Pointers and Inheritance Arrays Are Pointers in Disguise Summary Chapter 12 File Input and Output Games and File I/O Types of Files Summary Chapter 13 Moving into Real Game Development Sprites that Come Alive High-Speed Input Summary Part 5: The Big Payoff Chapter 14 No Slime Allowed: Invasion of the Slugwroths What It Takes to Make a Real Game Essential Game Design Designing Invasion of the Slugwroths Summary Chapter 15 Captain Chloride Gets Going Introducing Captain Chloride Pulling It Together In The Game Class Summary Chapter 16 The World of Captain Chloride The New Captain Chloride Levels in LlamaWorks2D Summary Chapter 17 Captain Chloride Encounters Solid Objects Bumping into a Solid Door Picking Up a Key Making the Door Open and Close Summary Chapter 18 That's a Wrap! Time for Consolidation Enter villains, Stage Left Additions to the Game Epilogue: Not the End Glossary Index Copyright Creating Games in C++: A Step-by-Step Guide David Conger with Ron Little New Riders 1249 Eighth Street Berkeley, CA 94710 510/524-2178 800/283-9444 510/524-2221 (fax) Find us on the Web at: www.newriders.com To report errors, please send a note to errata@peachpit.com New Riders is an imprint of Peachpit, a division of Pearson Education Copyright © 2006 by David Conger Project Editors: Davina Baum, Kristin Kalning Development Editors: Davina Baum, Denise Santoro Lincoln Production Editor: Myrna Vladic Copyeditor: Liz Welch Tech Editor: Ron Little Compositor: WolfsonDesign Indexer: Karin Arrigoni Cover design: Aren Howell Interior design: WolfsonDesign Notice of Rights All rights reserved No part of this book may be reproduced or transmitted in any form by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher For information on getting permission for reprints and excerpts, contact permissions@peachpit.com Notice of Liability The information in this book is distributed on an "As Is" basis without warranty While every precaution has been taken in the preparation of the book, neither the author nor Peachpit shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the instructions contained in this book or by the computer software and hardware products described in it Trademarks Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and Peachpit was aware of a trademark claim, the designations appear as requested by the owner of the trademark All other product names and services identified throughout this book are used in editorial fashion only and for the benefit of such companies with no intention of infringement of the trademark No such use, or the use of any trade name, is intended to convey endorsement or other affiliation with this book 9 8 7 6 5 4 3 2 1 Printed and bound in the United States of America Dedication This book is dedicated to my mother, Jan Conger, for all the good that she has done and still does Thanks, Mom Acknowledgments This book has been one of the hardest projects I've ever worked on Not because the book itself was hard to write, but because of three major computer crashes (and two replacement motherboards), two serious illnesses, two surgeries, having to change compilers after the third chapter, and having to entirely rewrite the game engine after the fourth I can honestly say that I could not have got through this book without the support of all those who worked on it I especially want to thank Kristin Kalning, who is simply the best project 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 And without his help on the sample programs for the last five chapters, I'd probably still be working on this book Introduction The first video game I ever played (at age 13) was Pong It was a very simple ping-pong simulation During my teenage years, a few, more advanced games appeared on the market Most notable were the Atari games such as Missile Command, a nuclear warfare simulator When I was 19, I went to live for a couple 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 crested its phenomenal wave of popularity I had never seen anything so cool By the time 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 take this programming class I know you'll love it." He was right By the time two weeks had passed, return statement return type 2nd rounding errors running programs 2nd 3rd 4th 5th Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Y] [Z] salt shooter 2nd 3rd save files 2nd 3rd scalars 2nd scan lines 2nd 3rd scope 2nd scope resolution operator (: :) 2nd 3rd 4th score markers 2nd score, player 2nd 3rd 4th 5th screen [See also monitor.] outputting to refresh rate resolution 2nd 3rd screen animation 2nd 3rd screen space coordinates 2nd screen_object pointer semicolon (;) 2nd SetI ( ) function shadows shooters 2nd 3rd 4th 5th shooting weapons 2nd 3rd 4th short data type side-scrolling games 2nd 3rd significant digits 2nd 3rd Sims, The sizeof ( ) operator slash marks (/ /) Sleep ( ) function Slugwroths 2nd [See also characters; Invasion of the Slugwroths.] software objects 2nd 3rd sound [See also music; sound effects.] audio editors 2nd compression digitized 2nd 3rd from CD/DVD 2nd gain 2nd importance of loading MIDI mixing with OpenAL MP3 files 2nd 3rd 4th 5th overview playing recording sound cards 2nd 3rd 4th sound class 2nd sound effect collections sound effect generator programs sound effects [See also music.] creating DirectX Audio 2nd 3rd finding importance of in LlamaWorks2D loading sounds OpenAL 2nd 3rd playing sounds software/tools for volume control WAV files 2nd sound files 2nd 3rd 4th sound libraries 2nd 3rd sound programming sound/music skills source code [See also code; object code.] compatibility of compiling [See compilers; compiling programs ] described 2nd line numbers in LlamaWorks2D macros for 2nd translating into binary source files 2nd space variables and white 2nd 3rd sprite animation 2nd 3rd 4th sprite class 2nd 3rd sprite objects 2nd sprites animation frames and bouncing collision detection described in LlamaWorks2D setting direction/speed of sqrt ( ) function square brackets [ ] 2nd 3rd 4th squared ( ) function srand ( ) function statements [See also specific statements.] described 2nd executing 2nd 3rd translating into binary commands states 2nd 3rd static keyword static memory allocation std namespace 2nd stdlib (standard) libraries 2nd stdlib.h file Stop ( ) function strcpy ( ) function streams cin cout 2nd 3rd described for files include statements and string arrays string object string type strings data in described literal 2nd structures [See also classes.] subscript 2nd subtraction operator Super Mario games 2nd 3rd switch statement system ( ) function Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Y] [Z] Tagged Image File (TIF) format 2nd temp pointer terabytes 2nd Tetris text files 2nd 3rd 4th texture blending 2nd TGA files theApp object theAPP.InitApp ( ) function TIF (Tagged Image File) format 2nd tilde (~) tokens 2nd transparent color 2nd troubleshooting [See also debugging; rounding errors.] crashes 2nd jerky movements memory problems slowness of programs true condition 2nd Type ( ) function type casting type functions type, declaring objects of same Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Y] [Z] uncomments underscore character (_) unit vectors unsigned data type unsigned integer UpdateFrame ( ) function 2nd user input 2nd 3rd 4th 5th using keyword Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Y] [Z] values color 2nd error passing returning 0 value returning from functions variables data types and declaring 2nd 3rd decrementing described incrementing keywords and nameless temporary 2nd names 2nd "out of scope," overview pointer 2nd scope of storing addresses in vs parameters vector classes floating-point overloading 2nd vector constructors vector variable vectors adding direction division of dot product of magnitude 2nd 3rd multiplying point location subtracting unit velocity 2nd 3rd video adapters 2nd 3rd 4th video modes 2nd 3rd [See also graphics modes.] villains virtual key code virtual keyword Visual C++ volumetric rendering Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Y] [Z] WarCraft WAV files weapons cannons [See CannonShoot program ] electron guns 2nd firing 2nd 3rd 4th salt shooter 2nd 3rd while loops white space 2nd 3rd window class Windows messages 2nd 3rd Windows Paint Windows programming 2nd Windows Recorder 2nd 3rd Windows version of GCC Windows-style coordinate system WinMain () function WMF (Windows Metafile) format WM_KEYDOWN message world coordinates 2nd worlds 2nd write ( ) function Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Y] [Z] X ( ) function 2nd 3rd XML level files 2nd 3rd XML tags 2nd 3rd 4th 5th x/y components x/y coordinates Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Y] [Z] Y ( ) function 2nd Yoshi's Story Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Y] [Z] z coordinate ... Case Study: Floating-Point Numbers and Gamespaces Summary Chapter 10 Arrays What Are Arrays? Declaring and Using Arrays Initializing Arrays Problems with Array Boundaries Summary Chapter 11 Pointers Why Are Pointers Important to Games? ... Why Are Pointers Important to Games? Declaring and Using Pointers Pointers and Dynamic Memory Allocation Pointers and Inheritance Arrays Are Pointers in Disguise Summary Chapter 12 File Input and Output Games and File I/O... After that, I taught collegelevel programming classes for several years My next career change enabled me to attain my long-standing goal of becoming a professional game programmer I wrote games for American Laser Games, For Her Interactive Inc., and Microsoft