Beginning C++ Through Game Programming, Third Edition Michael Dawson Course Technology PTR A part of Cengage Learning Australia Brazil Japan Korea Mexico Singapore Spain United Kingdom United States Beginning C++ Through Game Programming, Third Edition Michael Dawson Publisher and General Manager, Course Technology PTR: Stacy L Hiquet Associate Director of Marketing: Sarah Panella Manager of Editorial Services: Heather Talbot Marketing Manager: Jordan Castellani Senior Acquisitions Editor: Emi Smith Project Editor: Jenny Davidson Technical Reviewer: Maneesh Sethi Interior Layout Tech: MPS Limited, a Macmillan Company © 2011 Course Technology, a part of Cengage Learning ALL RIGHTS RESERVED No part of this work covered by the copyright herein may be reproduced, transmitted, stored, or used in any form or by any means graphic, electronic, or mechanical, including but not limited to photocopying, recording, scanning, digitizing, taping, Web distribution, information networks, or information storage and retrieval systems, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, without the prior written permission of the publisher For product information and technology assistance, contact us at Cengage Learning Customer & Sales Support, 1-800-354-9706 For permission to use material from this text or product, submit all requests online at www.cengage.com/permissions Further permissions questions can be emailed to permissionrequest@cengage.com Cover Designer: Mike Tanamachi Indexer: Kevin Broccoli All trademarks are the property of their respective owners Proofreader: Michael Beady All images Cengage Learning unless otherwise noted C Library of Congress Control Number: 2010928011 ISBN-13: 978-1-4354-5742-3 ISBN-10: 1-4354-5742-0 eISBN-10:1-4354-5743-9 Course Technology, a part of Cengage Learning 20 Channel Center Street Boston, MA 02210 USA Cengage Learning is a leading provider of customized learning solutions with office locations around the globe, including Singapore, the United Kingdom, Australia, Mexico, Brazil, and Japan Locate your local office at: international.cengage.com/region Cengage Learning products are represented in Canada by Nelson Education, Ltd For your lifelong learning solutions, visit courseptr.com Visit our corporate website at cengage.com Printed in the United States of America 12 11 10 To my sweet, tough cookie—for all of the help, support, understanding (and distractions) you offered And to Ariella Saraswati Dawson, a girl who’s even more impressive than her name I look forward to rediscovering the world with you, Monkey Acknowledgments Every book you’ve ever read perpetuates a big fat lie And I’m here to out the publishing 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 dedicated people to pull off the final product Authors could not it alone; I certainly could not have done it alone So I want to thank all those who helped make this book a reality Thanks to Jenny Davidson for her dual role as Project Editor and Copy Editor Jenny kept me on schedule and my commas in place Thanks to Maneesh Sethi, my Technical Reviewer, who made sure my programs worked the way I said they did Thanks to Michael Beady, my Proofreader His work makes this book look good—literally I also want to thank Emi Smith, my Senior Acquisitions Editor, for all of her encouragement Finally, I want to thank all of the game programmers who created the games I played while growing up They inspired me to work in the industry and create games of my own I hope I can inspire a few readers to the same About the Author Michael Dawson is a game programming author and instructor who teaches students the art and science of writing their own games Mike has developed and taught game programming courses for UCLA Extension, The Digital Media Academy, and The Los Angeles Film School In addition, his books have been required reading in colleges and universities around the country Mike got his start in the game industry as a producer and designer, but he also “starred” in an adventure game in which the player controls the main character, named Mike Dawson In the game, the player directs the digitized images of Dawson, who must stop an extraterrestrial invasion before an implanted alien embryo is born from his head In real life, Mike is the author of Beginning Cỵỵ Through Game Programming, Python Programming for the Absolute Beginner, Cỵỵ Projects: Programming with Text-Based Games, and Guide to Programming with Python He earned his bachelor’s degree in Computer Science from the University of Southern California Visit his website at www.programgames.com to learn more or to get support for any of his books Contents Introduction Chapter Types, Variables, and Standard I/O: Lost Fortune Introducing Cỵỵ Using Cỵỵ for Games Creating an Executable File Dealing with Errors Understanding the ISO Standard Writing Your First Cỵỵ Program Introducing the Game Over Program Commenting Code Using Whitespace Including Other Files Defining the main() Function Displaying Text through the Standard Output Terminating Statements Returning a Value from main() Working with the std Namespace Introducing the Game Over 2.0 Program Employing a using Directive Introducing the Game Over 3.0 Program Employing using Declarations Understanding When to Employ using vi xviii 2 5 7 8 10 10 10 11 11 12 12 Contents Using Arithmetic Operators Introducing the Expensive Calculator Program Adding, Subtracting, and Multiplying Understanding Integer and Floating Point Division Using the Modulus Operator Understanding Order of Operations Declaring and Initializing Variables Introducing the Game Stats Program Understanding Fundamental Types Understanding Type Modifiers Declaring Variables Naming Variables Assigning Values to Variables Initializing Variables Displaying Variable Values Getting User Input Defining New Names for Types Understanding Which Types to Use Performing Arithmetic Operations with Variables Introducing the Game Stats 2.0 Program Altering the Value of a Variable Using Combined Assignment Operators Using Increment and Decrement Operators Dealing with Integer Wrap Around Working with Constants Introducing the Game Stats 3.0 Program Using Constants Using Enumerations Introducing Lost Fortune Setting Up the Program Getting Information from the Player Telling the Story Summary Questions and Answers Discussion Questions Exercises Chapter 13 13 14 14 15 15 16 16 18 18 19 20 21 22 22 23 23 24 24 24 26 26 27 28 29 29 31 31 32 32 33 34 35 36 38 38 Truth, Branching, and the Game Loop: Guess My Number 39 Understanding Truth 39 vii viii Contents Using the if Statement Introducing the Score Rater Program Testing true and false Interpreting a Value as true or false Using Relational Operators Nesting if Statements Using the else Clause Introducing the Score Rater 2.0 Program Creating Two Ways to Branch Using a Sequence of if Statements with else Clauses Introducing the Score Rater 3.0 Program Creating a Sequence of if Statements with else Clauses Using the switch Statement Introducing the Menu Chooser Program Creating Multiple Ways to Branch Using while Loops Introducing the Play Again Program Looping with a while Loop Using Loops Introducing the Play Again 2.0 Program Looping with a Loop Using break and continue Statements Introducing the Finicky Counter Program Creating a while (true) Loop Using the break Statement to Exit a Loop Using the continue Statement to Jump Back to the Top of a Loop Understanding When to Use break and continue Using Logical Operators Introducing the Designers Network Program Using the Logical AND Operator Using the Logical OR Operator Using the Logical NOT Operator Understanding Order of Operations Generating Random Numbers Introducing the Die Roller Program Calling the rand() Function Seeding the Random Number Generator Calculating a Number within a Range 40 41 42 43 44 44 45 46 47 48 49 50 51 52 54 54 54 55 56 56 57 58 58 60 60 61 61 61 62 65 66 66 67 68 68 69 70 71 Contents Understanding the Game Loop Introducing Guess My Number Applying the Game Loop Setting Up the Game Creating the Game Loop Wrapping Up the Game Summary Questions and Answers Discussion Questions Exercises Chapter 72 73 74 74 76 76 76 78 80 80 For Loops, Strings, and Arrays: Word Jumble 81 Using for Loops Introducing the Counter Program Counting with for Loops Using Empty Statements in for Loops Nesting for Loops Understanding Objects Using String Objects Introducing the String Tester Program Creating string Objects Concatenating string Objects Using the size() Member Function Indexing a string Object Iterating through string Objects Using the find() Member Function Using the erase() Member Function Using the empty() Member Function Using Arrays Introducing the Hero’s Inventory Program Creating Arrays Indexing Arrays Accessing Member Functions of an Array Element Being Aware of Array Bounds Understanding C-Style Strings Using Multidimensional Arrays Introducing the Tic-Tac-Toe Board Program Creating Multidimensional Arrays Indexing Multidimensional Arrays 81 82 84 85 86 87 89 89 91 92 92 93 93 94 95 96 96 96 98 99 100 100 101 103 103 105 105 ix 396 Appendix D n ASCII Chart ASCII Chart (Continued ) Decimal Hexadecimal Character 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 5F 60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F _ ` 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 { | } ~ DEL appendix E Escape Sequences Escape Sequences Escape Sequence Description \’ \" \\ \0 \a \b \f \n \r \t \v \x Single quote Double quote Backslash Null character System bell Backspace Formfeed Newline Carriage return Horizontal tab Vertical tab Hexadecimal number 397 This page intentionally left blank INDEX À (subtraction) operator, 14 ! (NOT) operator, 61tbl, 66–67, 77 != (not equal to) operator, 40tbl # (hash mark) symbol, 7, 35 % (modulus operator), 15, 72 & (reference operator), 189, 217 && (AND) operator, 61tbl, 77 * (dereference operator), 128, 146, 230 * (multiplication) operator, 14 (member selection operator), 88, 259 / (forward slash), 14 :: (scope resolution operator), 9, 125, 259, 345 ; (semicolon) if statement, 43 terminating statements, [ ] (subscripting operator), 93, 99, 121, 147 || (OR) operator, 61tbl, 66 ỵ (addition) operator, 14, 92 ỵỵ (increment operator), 2728 < (less than) operator, 40tbl = (greater than or equal to) operator, 40tbl 64-element array, 103 A abstract classes, 352–356, 380, 382 Abstract Creature program, 352–354 declaring pure virtual functions, 354–355 deriving classes from, 355–356 virtual functions and, 355 Abstract Creature program, 352–354 abstraction encapsulation and, 160 functions, 155 access control, 337–340 Simple Boss 2.0 program, 338–339 using access modifiers when deriving classes, 340 using access modifiers with class members, 339–340 access modifiers using when deriving classes, 340 using with class members, 339–340 access_global() function, 168 accessing array elements, 246 data members, 259–260 global variables, 168 member functions of array element, 100 member functions of vector element, 129–130 reference values, 190 static data members, 272–273 accessor member functions, 267– 268, 282 action statement, for loop, 82 Add() member function, 292 Add New Item dialog box, 386g addition (ỵ) operator, 14, 92 address, variable, 249 advanced classes aggregation, 287–292 container data members, 291–292 Critter Farm program, 288–290 object data members, 290–291 friend functions creating, 295 Friend Critter program, 292–294 Game Lobby program, 315–325 Lobby class, 318–320 Lobby::AddPlayer() member function, 320–322 Lobby::Clear() member function, 322–323 Lobby::RemovePlayer() member function, 322 main() function, 324–325 operator