Next >

image


image

Beginning C++ Through Game Programming, Third Edition


image


Michael Dawson

Course Technology PTR

A part of Cengage Learning


image


image

Australia . Brazil . Japan . Korea . Mexico . Singapore . Spain . United Kingdom . United States

image


image

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

Cover Designer: Mike Tanamachi Indexer: Kevin Broccoli Proofreader: Michael Beady

© 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


All trademarks are the property of their respective owners. All images C Cengage Learning unless otherwise noted.


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 ofce locations around the globe, including Singapore, the United Kingdom, Australia, Mexico, Brazil, and Japan. Locate your local ofce 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 1 2 3 4 5 6 7 12 11 10


To my sweet, tough cookiefor all of the help, support, understanding (and distractions) you offered.

And to Ariella Saraswati Dawson, a girl whos even more impressive than her name. I look forward to rediscovering the world with you, Monkey.


image

 

AcknowledgmentsAbout the AuthorContents IntroductionWho This Book Is ForHow This Book Is OrganizedConventions Used in This Book Source Code for the Programs in this BookA Word about CompilersTypes, Variables, and Standard I/O: Lost Fortune Introducing CþþUsing Cþþ for GamesCreating an Executable FileDealing with ErrorsUnderstanding the ISO StandardWriting Your First Cþþ Program Introducing the Game Over ProgramCommenting CodeUsing WhitespaceIncluding Other FilesDefining the main() FunctionDisplaying Text through the Standard Output Terminating StatementsReturning a Value from main()Working with the std Namespace Introducing the Game Over 2.0 ProgramEmploying a using DirectiveIntroducing the Game Over 3.0 Program Employing using DeclarationsUnderstanding When to Employ usingUsing Arithmetic Operators Introducing the Expensive Calculator ProgramAdding, Subtracting, and MultiplyingUnderstanding Integer and Floating Point Division Using the Modulus OperatorUnderstanding Order of OperationsDeclaring and Initializing Variables Introducing the Game Stats ProgramUnderstanding Fundamental TypesUnderstanding Type Modifiers Declaring VariablesNaming VariablesAssigning Values to Variables Initializing VariablesDisplaying Variable ValuesGetting User Input Defining New Names for TypesUnderstanding Which Types to UsePerforming Arithmetic Operations with Variables Introducing the Game Stats 2.0 ProgramAltering the Value of a VariableUsing Combined Assignment Operators Using Increment and Decrement OperatorsDealing with Integer Wrap AroundWorking with Constants Introducing the Game Stats 3.0 ProgramUsing ConstantsUsing Enumerations Introducing Lost FortuneSetting Up the ProgramGetting Information from the Player Telling the StorySummaryQuestions and Answers Discussion QuestionsExercisesTruth, Branching, and the Game Loop: Guess My Number Understanding TruthUsing the if StatementIntroducing the Score Rater Program Testing true and falseInterpreting a Value as true or falseUsing Relational Operators Nesting if StatementsUsing the else ClauseIntroducing the Score Rater 2.0 Program Creating Two Ways to BranchUsing a Sequence of if Statements with else Clauses Introducing the Score Rater 3.0 ProgramUsing the switch StatementIntroducing the Menu Chooser ProgramCreating Multiple Ways to Branch Using while LoopsIntroducing the Play Again ProgramLooping with a while LoopUsing do Loops Introducing the Play Again 2.0 ProgramLooping with a do Loop Using break and continue StatementsIntroducing the Finicky Counter Program Creating a while (true) LoopUsing the break Statement to Exit a Loop Using the continue Statement to Jump Back to the Top of a LoopUnderstanding When to Use break and continue Using Logical OperatorsIntroducing the Designers Network Program Using the Logical AND OperatorUsing the Logical OR Operator Using the Logical NOT OperatorUnderstanding Order of Operations Generating Random NumbersIntroducing the Die Roller Program Calling the rand() FunctionSeeding the Random Number Generator Calculating a Number within a RangeUnderstanding the Game Loop Introducing Guess My NumberApplying the Game Loop Setting Up the GameCreating the Game Loop Wrapping Up the GameSummary Questions and AnswersDiscussion Questions ExercisesFor Loops, Strings, and Arrays: Word Jumble Using for LoopsIntroducing the Counter Program Counting with for LoopsUsing Empty Statements in for Loops Nesting for LoopsUnderstanding Objects Using String ObjectsIntroducing the String Tester Program Creating string ObjectsConcatenating string Objects Using the size() Member FunctionIndexing a string Object Iterating through string ObjectsUsing the find() Member Function Using the erase() Member FunctionUsing the empty() Member Function Using ArraysIntroducing the Hero’s Inventory Program Creating ArraysIndexing Arrays Accessing Member Functions of an Array Element Being Aware of Array BoundsUnderstanding C-Style Strings Using Multidimensional Arrays Introducing the Tic-Tac-Toe Board ProgramCreating Multidimensional Arrays Indexing Multidimensional Arrays Introducing Word Jumble Setting Up the Program Picking a Word to Jumble Jumbling the Word Welcoming the Player Entering the Game Loop Saying Goodbye Summary Questions and Answers Discussion Questions Exercises The Standard Template Library: Hangman Using Vectors Introducing the Hero’s Inventory 2.0 Program Preparing to Use Vectors Declaring a Vector Using the push_back() Member Function Using the size() Member Function Indexing Vectors Calling Member Functions of an Element Using the pop_back() Member Function Using the clear() Member Function Using the empty() Member Function Using Iterators Introducing the Hero’s Inventory 3.0 Program Declaring Iterators Looping through a Vector Changing the Value of a Vector Element Accessing Member Functions of a Vector Element Using the insert() Vector Member Function Using the erase() Vector Member Function Using Algorithms Introducing the High Scores Program Preparing to Use Algorithms Using the find() Algorithm Using the random_shuffle() Algorithm Using the sort() Algorithm Understanding Vector Performance Examining Vector Growth Examining Element Insertion and Deletion Examining Other STL Containers Planning Your Programs Using Pseudocode Using Stepwise Refinement Introducing Hangman Planning the Game Setting Up the Program Initializing Variables and Constants Entering the Main Loop Getting the Player’s Guess Ending the Game Summary Questions and Answers Discussion Questions Exercises Functions: Mad Lib Creating Functions Introducing the Instructions Program Declaring Functions Defining Functions Calling Functions Understanding Abstraction Using Parameters and Return Values Introducing the Yes or No Program Returning a Value Accepting Values into Parameters Understanding Encapsulation Understanding Software Reuse Working with Scopes Introducing the Scoping Program Working with Separate Scopes Working with Nested Scopes Using Global Variables Introducing the Global Reach Program Declaring Global Variables Accessing Global Variables Hiding Global Variables Altering Global Variables Minimizing the Use of Global Variables Using Global Constants Using Default Arguments Introducing the Give Me a Number Program Specifying Default Arguments Assigning Default Arguments to Parameters Overriding Default Arguments Overloading Functions Introducing the Triple Program Creating Overloaded Functions Calling Overloaded Functions Inlining Functions Introducing the Taking Damage Program Specifying Functions for Inlining Calling Inlined Functions Introducing the Mad Lib Game Setting Up the Program The main() Function The askText() Function The askNumber() Function The tellStory() Function Summary Questions and Answers Discussion Questions Exercises References: Tic-Tac-Toe Using References Introducing the Referencing Program Creating References Accessing Referenced Values Altering Referenced Values Passing References to Alter Arguments Introducing the Swap Program Passing by Value Passing by Reference Passing References for Efficiency Introducing the Inventory Displayer Program Understanding the Pitfalls of Reference Passing Declaring Parameters as Constant References Passing a Constant Reference Deciding How to Pass Arguments Returning References Introducing the Inventory Referencer Program Returning a Reference Displaying the Value of a Returned Reference Assigning a Returned Reference to a Reference Assigning a Returned Reference to a Variable Altering an Object through a Returned Reference Introducing the Tic-Tac-Toe Game Planning the Game Setting Up the Program The main() Function The instructions() Function The askYesNo() Function The askNumber() Function The humanPiece() Function The opponent() Function The displayBoard() Function The winner() Function The isLegal() Function The humanMove() Function The computerMove() Function The announceWinner() Function Summary Questions and Answers Discussion Questions Exercises Pointers: Tic-Tac-Toe 2.0 Understanding Pointer Basics Introducing the Pointing Program Declaring Pointers Initializing Pointers Assigning Addresses to Pointers Dereferencing Pointers Reassigning Pointers Using Pointers to Objects Understanding Pointers and Constants Using a Constant Pointer Using a Pointer to a Constant Using a Constant Pointer to a Constant Summarizing Constants and Pointers Passing Pointers Introducing the Swap Pointer Version Program Passing by Value Passing a Constant Pointer Returning Pointers Introducing the Inventory Pointer Program Returning a Pointer Using a Returned Pointer to Display a Value Assigning a Returned Pointer to a Pointer Assigning to a Variable the Value Pointed to by a Returned Pointer Altering an Object through a Returned Pointer Understanding the Relationship between Pointers and Arrays Introducing the Array Passer Program Using an Array Name as a Constant Pointer Passing and Returning Arrays Introducing the Tic-Tac-Toe 2.0 Game Summary Questions and Answers Discussion Questions Exercises Classes: Critter Caretaker Defining New Types Introducing the Simple Critter Program Defining a Class Defining Member Functions Instantiating Objects Accessing Data Members Calling Member Functions Using Constructors Introducing the Constructor Critter Program Declaring and Defining a Constructor Calling a Constructor Automatically Setting Member Access Levels Introducing the Private Critter Program Specifying Public and Private Access Levels Defining Accessor Member Functions Defining Constant Member Functions Using Static Data Members and Member Functions Introducing the Static Critter Program Declaring and Initializing Static Data Members Accessing Static Data Members Declaring and Defining Static Member Functions Calling Static Member Functions Introducing the Critter Caretaker Game Planning the Game Planning the Pseudocode The Critter Class The main() Function Summary Questions and Answers Discussion Questions Exercises Advanced Classes and Dynamic Memory: Game Lobby Using Aggregation Introducing the Critter Farm Program Using Object Data Members Using Container Data Members Using Friend Functions and Operator Overloading Introducing the Friend Critter Program Creating Friend Functions Overloading Operators Dynamically Allocating Memory Introducing the Heap Program Using the new Operator Using the delete Operator Avoiding Memory Leaks Working with Data Members and the Heap Introducing the Heap Data Member Program Declaring Data Members that Point to Values on the Heap Declaring and Defining Destructors Declaring and Defining Copy Constructors Overloading the Assignment Operator Introducing the Game Lobby Program The Player Class The Lobby Class The Lobby::AddPlayer() Member Function The Lobby::RemovePlayer() Member Function The Lobby::Clear() Member Function The operator<<() Member Function The main() Function Summary Questions and Answers Discussion Questions Exercises Inheritance and Polymorphism: Blackjack Introducing Inheritance Introducing the Simple Boss Program Deriving from a Base Class Instantiating Objects from a Derived Class Using Inherited Members Controlling Access under Inheritance Introducing the Simple Boss 2.0 Program Using Access Modifiers with Class Members Using Access Modifiers When Deriving Classes Calling and Overriding Base Class Member Functions Introducing the Overriding Boss Program Calling Base Class Constructors Declaring Virtual Base Class Member Functions Overriding Virtual Base Class Member Functions Calling Base Class Member Functions Using Overloaded Assignment Operators and Copy Constructors in Derived Classes Introducing Polymorphism Introducing the Polymorphic Bad Guy Program Using Base Class Pointers to Derived Class Objects Defining Virtual Destructors Using Abstract Classes Introducing the Abstract Creature Program Declaring Pure Virtual Functions Deriving a Class from an Abstract Class Introducing the Blackjack Game Designing the Classes Planning the Game Logic The Card Class The Hand Class The GenericPlayer Class The Player Class The House Class The Deck Class The Game Class The main() Function Overloading the operator<<() Function Summary Questions and Answers Discussion Questions Exercises Creating Your First C++ Program Operator Precedence Keywords ASCII Chart Escape Sequences A B C D E F G H I K L M N O P Q R S T U V W Y