《C++游戏编程》基础

Beginning C++ Through Came Programming

2017.03.14 - 2017.03.17

简单编程熟悉概念,四天全部看完。

(001) 致谢

赠人玫瑰,手有余香

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 do the same.

(002) 目录

Chapter 01: Types, Variables, and Standard I/O: Lost Fortune

Chapter 02: Truth, Branching, and the Game Loop: Guess My Number

Chapter 03: for Loops, Strings, and Arrays: Word Jumble

Chapter 04: The Standard Template Library: Hangman

Chapter 05: Functions: Mad Lib

Chapter 06: References: Tic-Tac-Toe

Chapter 07: Pointers: Tic-Tac-Toe 2.0

Chapter 08: Classes: Critter Caretaker

Chapter 09: Advanced Classes and Dynamic Memory: Game Lobby

Chapter 10: Inheritance and Polymorphism: Blackjack

Appendix

(003) C++语言对于游戏的重要性

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++.

(004) 本书目标

The goal of this book is to introduce you to the C++ language from a game programming perspective.

By the end of this book, you'll have a solid foundation in the game programming language of the professionals.


Chapter 1: Types, Variables, And Standard I/O: Lost Fortune

(005) 第一个游戏

The Game Over program puts a gaming twist on the classic and displays Game Over! instead.

[html] view plain copy
  1. 1 // Game Over  
  2.  2 // A first C++ program  
  3.  3 #include <iostream>  
  4.  4   
  5.  5 int main()  
  6.  6 {  
  7.  7     std::cout << "Game Over!" << std::endl;  
  8.  8     return 0;  
  9.  9 }  
wang@wang:~/workspace/beginc++game$ ./game_over 
Game Over!

(006) ostream

cout is an object, defined in the file iostream, that's used to send data to the standard output stream.

(007) 使用std directive

[html] view plain copy
  1.  1 // Game Over 2.0  
  2.  2 // Demonstrates a using directive  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     cout << "Game Over!" << endl;  
  10. 10     return 0;  
  11. 11 }  
wang@wang:~/workspace/beginc++game$ ./game_over2 
Game Over!
(008) 使用using declaration

[html] view plain copy
  1.  1 // Game Over 3.0  
  2.  2 // Demonstrates using declarations  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using std::cout;  
  6.  6 using std::endl;  
  7.  7   
  8.  8 int main()  
  9.  9 {  
  10. 10     cout << "Game Over!" << endl;  
  11. 11     return 0;  
  12. 12 }  
wang@wang:~/workspace/beginc++game$ ./game_over3
Game Over!

(009) 加减乘除

[html] view plain copy
  1.  1 // Expensive Calculator  
  2.  2 // Demonstrates built-in arithmetic operators  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     cout << "7 + 3 = " << 7 + 3 << endl;  
  10. 10     cout << "7 - 3 = " << 7 - 3 << endl;  
  11. 11     cout << "7 * 3 = " << 7 * 3 << endl;  
  12. 12   
  13. 13     cout << "7 / 3 = " << 7 / 3 << endl;  
  14. 14     cout << "7.0 / 3.0 = " << 7.0 / 3.0 << endl;  
  15. 15   
  16. 16     cout << "7 % 3 = " << 7 % 3 << endl;  
  17. 17   
  18. 18     cout << "7 + 3 * 5 = " << 7 + 3 * 5 << endl;  
  19. 19     cout << "(7 + 3) * 5 = " << (7 + 3) * 5 << endl;  
  20. 20   
  21. 21     return 0;  
  22. 22 }  
wang@wang:~/workspace/beginc++game$ ./expensive_calculator 
7 + 3 = 10
7 - 3 = 4
7 * 3 = 21
7 / 3 = 2
7.0 / 3.0 = 2.33333
7 % 3 = 1
7 + 3 * 5 = 22
(7 + 3) * 5 = 50

(010) 变量

A variable represents a particular piece of your computer's memory that has been set aside for you to use to store, retrieve, and manipulate data.

(011) 状态值举例

[html] view plain copy
  1.  1 // Game Stats  
  2.  2 // Demonstrates declaring and initializing variables  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     int score;  
  10. 10     double distance;  
  11. 11     char playAgain;  
  12. 12     bool shieldsUp;  
  13. 13   
  14. 14     short lives, aliensKilled;  
  15. 15   
  16. 16     score = 0;  
  17. 17     distance = 1200.76;  
  18. 18     playAgain = 'y';  
  19. 19     shieldsUp = true;  
  20. 20     lives = 3;  
  21. 21     aliensKilled = 10;  
  22. 22     double engineTemp = 6572.89;  
  23. 23   
  24. 24     cout << "score: " << score << endl;  
  25. 25     cout << "distance: " << distance << endl;  
  26. 26     cout << "playAgain: " << playAgain << endl;  
  27. 27     // skipping shieldsUp since you don't generally print Boolean values  
  28. 28     cout << "lives: " << lives << endl;  
  29. 29     cout << "aliensKilled: " << aliensKilled << endl;  
  30. 30     cout << "engineTemp: " << engineTemp << endl;  
  31. 31   
  32. 32     int fuel;  
  33. 33     cout << "How much fuel? ";  
  34. 34     cin >> fuel;  
  35. 35     cout << "fuel: " << fuel << endl;  
  36. 36   
  37. 37     typedef unsigned short int ushort;  
  38. 38     ushort bonus = 10;  
  39. 39     cout << "bonus: " << bonus << endl;  
  40. 40   
  41. 41     return 0;  
  42. 42 }  

wang@wang:~/workspace/beginc++game$ ./game_stats 
score: 0
distance: 1200.76
playAgain: y
lives: 3
aliensKilled: 10
engineTemp: 6572.89
How much fuel? 12
fuel: 12
bonus: 10

(012) modifier

signed and unsigned are modifiers  that work only with integer types.

(013) identifier命名规则

1. Choose descriptive names

2. Be consistent

3. Follow the traditions of the language

4. Keep the length in check

(014) typedef定义

To define new names for existing types, use typedef followed by the current type, followed by the new name.

(015) 变量运算举例

[cpp] view plain copy
  1.  1 // Game Stats 2.0  
  2.  2 // Demonstrates arithmetic operations with variables  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     unsigned int score = 5000;  
  10. 10     cout << "score: " << score << endl;  
  11. 11   
  12. 12     // altering the value of a variable  
  13. 13     score = score + 100;  
  14. 14     cout << "score: " << score << endl;  
  15. 15   
  16. 16     // combined assignment operator  
  17. 17     score += 100;  
  18. 18     cout << "score: " << score << endl;  
  19. 19   
  20. 20     // increment operators  
  21. 21     int lives = 3;  
  22. 22     ++lives;  
  23. 23     cout << "lives: " << lives << endl;  
  24. 24   
  25. 25     lives = 3;  
  26. 26     lives++;  
  27. 27     cout << "lives: " << lives << endl;  
  28. 28   
  29. 29     lives = 3;  
  30. 30     int bonus = ++lives * 10;  
  31. 31     cout << "lives, bonus = " << lives << ", " << bonus << endl;  
  32. 32   
  33. 33     lives = 3;  
  34. 34     bonus = lives++ * 10;  
  35. 35     cout << "lives, bonus = " << lives << ", " << bonus << endl;  
  36. 36   
  37. 37     // integer wrap around  
  38. 38     score = 4294967295;  
  39. 39     cout << "socre: " << score << endl;  
  40. 40     ++score;  
  41. 41     cout << "score: " << score << endl;  
  42. 42   
  43. 43     return 0;  
  44. 44 }  
wang@wang:~/test$ ./game_stat2 
score: 5000
score: 5100
score: 5200
lives: 4
lives: 4
lives, bonus = 4, 40
lives, bonus = 4, 30
socre: 4294967295
score: 0
(016) wrap around溢出

Make sure to pick an integer type that has a large enough range for its intended use.

(017) 常量

First, they make programs clearer.

Second, constants make changes easy.

(018) 枚举类型举例

An enumeration is a set of unsigned int constants, called enumerators. 

[cpp] view plain copy
  1.  1 // Game Stats 3.0  
  2.  2 // Demonstrates constants  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     const int ALIEN_POINTS = 150;  
  10. 10     int aliensKilled = 10;  
  11. 11     int score = aliensKilled * ALIEN_POINTS;  
  12. 12     cout << "score: " << score << endl;  
  13. 13     enum difficulty {NOVICE, EASY, NORMAL, HARD, UNBEATABLE};  
  14. 14     difficulty myDifficulty = EASY;  
  15. 15     enum shipCost {FIGHTER_COST = 25, BOMBER_COST, CRUISER_COST = 50};  
  16. 16     shipCost myShipCost = BOMBER_COST;  
  17. 17     cout << "To upgrade my ship to a Cruiser will cost "  
  18. 18         << (CRUISER_COST - myShipCost) << " Resource Points.\n";  
  19. 19     return 0;  
  20. 20 }  
wang@wang:~/test$ ./game_stats3 
score: 1500
To upgrade my ship to a Cruiser will cost 24 Resource Points.
(019) 综合举例

有趣的文字游戏

[cpp] view plain copy
  1.  1 // Lost Fortune  
  2.  2 // A personalized adventure  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 #include <string>  
  6.  6   
  7.  7 using namespace std;  
  8.  8 int main()  
  9.  9 {  
  10. 10     const int GOLD_PIECES = 900;  
  11. 11     int adventurers, killed, survivors;  
  12. 12     string leader;  
  13. 13   
  14. 14     // get the information  
  15. 15     cout << "Welcome to Lost Fortune\n";  
  16. 16     cout << "Please enter the following for your personalized adventure\n";  
  17. 17     cout << "Enter a number: ";  
  18. 18     cin >> adventurers;  
  19. 19     cout << "Enter a number, smaller than the first: ";  
  20. 20     cin >> killed;  
  21. 21     survivors = adventurers - killed;  
  22. 22     cout << "Enter your last name: ";  
  23. 23     cin >> leader;  
  24. 24     // tell the story  
  25. 25     cout << "A brave group of " << adventurers << " set out on a quest ";  
  26. 26     cout << "-- in search of the lost treasure of the Ancient Dwarves. ";  
  27. 27     cout << "The group was led by that legendary rogue, " << leader << ".\n";  
  28. 28     cout << "Along the way, a band of marauding ogres ambushed the party. ";  
  29. 29     cout << "All fought bravely under the command of " << leader;  
  30. 30     cout << ", and the ogres were defeated, but at a cost. ";  
  31. 31     cout << "Of the adventurers, " << killed << " were vanquished, ";  
  32. 32     cout << "leaving just " << survivors << " in the group.\n";  
  33. 33     cout << "The party was about to give up all hope. ";  
  34. 34     cout << "But while laying the deceased to rest, ";  
  35. 35     cout << "they stumbled upon the buried fortune. ";  
  36. 36     cout << "So the adventurers split " << GOLD_PIECES << " gold pieces. ";  
  37. 37     cout << leader << " held on to the extra " << (GOLD_PIECES % survivors);  
  38. 38     cout << " pieces to keep things fair of cource.\n";  
  39. 39     return 0;  
  40. 40 }  
wang@wang:~/test$ g++ lost_fortune.cpp -o lost_fortune
wang@wang:~/test$ ./lost_fortune 
Welcome to Lost Fortune
Please enter the following for your personalized adventure
Enter a number: 19
Enter a number, smaller than the first: 13
Enter your last name: wang
A brave group of 19 set out on a quest -- in search of the lost treasure of the Ancient Dwarves. The group was led by that legendary rogue, wang.
Along the way, a band of marauding ogres ambushed the party. All fought bravely under the command of wang, and the ogres were defeated, but at a cost. Of the adventurers, 13 were vanquished, leaving just 6 in the group.
The party was about to give up all hope. But while laying the deceased to rest, they stumbled upon the buried fortune. So the adventurers split 900 gold pieces. wang held on to the extra 0 pieces to keep things fair of cource.

(020) 习题

1. enum names {WORST, WORSR, BAD, GOOD, BETTER, BEST};

2.  2,   2.333333,  2.333333

3. 输入三个整数,输出它们的平均值

[cpp] view plain copy
  1.  1 #include <iostream>  
  2.  2 using namespace std;  
  3.  3   
  4.  4 int main()  
  5.  5 {  
  6.  6     int firstScore, secondScore, thirdScore;  
  7.  7     cout << "Enter three integers: ";  
  8.  8     cin >> firstScore >> secondScore >> thirdScore;  
  9.  9     int average = (firstScore + secondScore + thirdScore) / 3;  
  10. 10     cout << average << endl;  
  11. 11     return 0;  
  12. 12 }  
wang@wang:~/test$ ./three_score 
Enter three integers: 1 2 3
2


Chapter 2: Truth, Branching, And The Game Loop: Guess My Number

(021) if (expression) statement;

[cpp] view plain copy
  1.  1 // Score Rater  
  2.  2 // Demonstrates the if statement  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     if (true) {  
  10. 10         cout << "This is always displayd.\n";  
  11. 11     }  
  12. 12     if (false) {  
  13. 13         cout << "This is never displayed.\n";  
  14. 14     }  
  15. 15   
  16. 16     int score = 1000;  
  17. 17     if (score) {  
  18. 18         cout << "At least you didn't score zero.\n";  
  19. 19     }  
  20. 20     if (score > 250) {  
  21. 21         cout << "You scored 250 more. Decent.\n";  
  22. 22     }  
  23. 23     if (score >= 500) {  
  24. 24         cout << "You scored 500 or more. Nice.\n";  
  25. 25         if (score >= 1000) {  
  26. 26             cout << "You scored 1000 or more. Impressive!\n";  
  27. 27         }  
  28. 28     }  
  29. 29     return 0;  
  30. 30 }  
wang@wang:~/test$ g++ score_rater.cpp -o score_rater
wang@wang:~/test$ ./score_rater 
This is always displayd.
At least you didn't score zero.
You scored 250 more. Decent.
You scored 500 or more. Nice.
You scored 1000 or more. Impressive!
(022) else 语句

[cpp] view plain copy
  1.  1 // Score Rater 2.0  
  2.  2 // Demonstrates an else clause  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     int score;  
  10. 10     cout << "Enter your score: ";  
  11. 11     cin >> score;  
  12. 12   
  13. 13     if (score >= 1000) {  
  14. 14         cout << "You scored 1000 or more. Impressive!\n";  
  15. 15     } else {  
  16. 16         cout << "You score less than 1000.\n";  
  17. 17     }  
  18. 18     return 0;  
  19. 19 }  
wang@wang:~/test$ ./score_rater2
Enter your score: 456
You score less than 1000.
(023) 多个if语句

[cpp] view plain copy
  1.  1 // Score Rater 3.0  
  2.  2 // Demonstrates if else-if else suite  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     int score;  
  10. 10     cout << "Enter your score: ";  
  11. 11     cin >> score;  
  12. 12   
  13. 13     if (score >= 1000) {  
  14. 14         cout << "You scored 1000 or more. Impressive!\n";  
  15. 15     } else if (score >= 500) {  
  16. 16         cout << "You score 500 or more. Nice.\n";  
  17. 17     } else if (score >= 250) {  
  18. 18         cout << "You score 250 or more. Decent.\n";  
  19. 19     } else  
  20. 20         cout << "You scored less than 250. Nothing to brag about.\n";  
  21. 21     return 0;  
  22. 22 }  
wang@wang:~/test$ ./score_rater3 
Enter your score: 100
You scored less than 250. Nothing to brag about.
(024) switch语句举例

[cpp] view plain copy
  1.  1 // Menu Chooser  
  2.  2 // Demonstrates the switch statement  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     cout << "Difficulty Levels\n";  
  10. 10     cout << "1 - Easy\n";  
  11. 11     cout << "2 - Normal\n";  
  12. 12     cout << "3 - Hard\n";  
  13. 13   
  14. 14     int choice;  
  15. 15     cout << "Choice: ";  
  16. 16     cin >> choice;  
  17. 17   
  18. 18     switch (choice) {  
  19. 19     case 1:  
  20. 20         cout << "You picked Easy.\n";  
  21. 21         break;  
  22. 22     case 2:  
  23. 23         cout << "You picked Normal.\n";  
  24. 24         break;  
  25. 25     case 3:  
  26. 26         cout << "You picked Hard.\n";  
  27. 27     default:  
  28. 28         cout << "You made an illegal choice.\n";  
  29. 29     }  
  30. 30     return 0;  
  31. 31 }  
wang@wang:~/test$ ./menu_chooser 
Difficulty Levels
1 - Easy
2 - Normal
3 - Hard
Choice: 2
You picked Normal.
(025) while 循环举例

[cpp] view plain copy
  1.  1 // Play Again  
  2.  2 // Demonstrates while loops  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     char again = 'y';  
  10. 10     while (again == 'y') {  
  11. 11         cout << "**Played an exciting game**\n";  
  12. 12         cout << "Do you want to play again? (y/n): ";  
  13. 13         cin >> again;  
  14. 14     }  
  15. 15     cout << "Okay, bye.\n";  
  16. 16     return 0;  
  17. 17 }  
wang@wang:~/test$ ./play_again 
**Played an exciting game**
Do you want to play again? (y/n): y
**Played an exciting game**
Do you want to play again? (y/n): b
Okay, bye.
(026) do while循环

[cpp] view plain copy
  1.  1 // Play Again 2.0  
  2.  2 // Demonstrates do loops  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     char again;  
  10. 10     do {  
  11. 11         cout << "**Played an exciting game**";  
  12. 12         cout << "\nDo you want to play again? (y/n): ";  
  13. 13         cin >> again;  
  14. 14     } while (again == 'y');  
  15. 15   
  16. 16     cout << "Okay, bye.\n";  
  17. 17     return 0;  
  18. 18 }  
wang@wang:~/test$ ./play_again2 
**Played an exciting game**
Do you want to play again? (y/n): y
**Played an exciting game**
Do you want to play again? (y/n): n
Okay, bye.
(027) break & continue

You can immediately exit a loop with the break statement, and you can jump directly to the top of a loop with a continue statement.

[cpp] view plain copy
  1.  1 // Finicky Counter  
  2.  2 // Demonstrates break and continue statements  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     int count = 0;  
  10. 10     while (true) {  
  11. 11         count += 1;  
  12. 12         // end loop if count is greater than 10  
  13. 13         if (count > 10)  
  14. 14             break;  
  15. 15         // skip the number 5  
  16. 16         if (count == 5)  
  17. 17             continue;  
  18. 18         cout << count << endl;  
  19. 19     }  
  20. 20     return 0;  
  21. 21 }  
wang@wang:~/test$ ./finicky_counter 
1
2
3
4
6
7
8
9
10
(028) 逻辑运算符&& || !

Logical NOT, ! has a higher level of precedence that logical AND, &&, which has a higher precedence than logical OR, ||.

[cpp] view plain copy
  1.  1 // Designers Network  
  2.  2 // Demonstrates logical operators  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 #include <string>  
  6.  6   
  7.  7 using namespace std;  
  8.  8   
  9.  9 int main()  
  10. 10 {  
  11. 11     string username;  
  12. 12     string password;  
  13. 13     bool success;  
  14. 14     cout << "\tGame Designer's Network\n";  
  15. 15     do {  
  16. 16         cout << "Username: ";  
  17. 17         cin >> username;  
  18. 18         cout << "Password: ";  
  19. 19         cin >> password;  
  20. 20   
  21. 21         if (username == "S.Meier" && password == "civilization") {  
  22. 22             cout << "Hey, Sid.\n";  
  23. 23             success = true;  
  24. 24         } else if (username == "S.Miyamoto" && password == "mariobros") {  
  25. 25             cout << "What's up, Shigegu?\n";  
  26. 26             success = true;  
  27. 27         } else if (username == "guest" || password == "guest") {  
  28. 28             cout << "Welcome, guest.\n";  
  29. 29             success = true;  
  30. 30         } else {  
  31. 31             cout << "Your login failed.\n";  
  32. 32             success = false;  
  33. 33         }  
  34. 34     } while (!success);  
  35. 35     return 0;  
  36. 36 }  
wang@wang:~/test$ ./designers_network 
    Game Designer's Network
Username: wang
Password: wang
Your login failed.
Username: wang
Password: guest
Welcome, guest.
(029) 产生随机数

The file sctdlib contains (among other things) functions that deal with generating random numbers.

The upper limit is stored in the constant RAND_MAX.

In terms of the actual code, the srand() function seeds the random number generator.

[cpp] view plain copy
  1.  1 // Die Roller  
  2.  2 // Demonstrates generating random numbers  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 #include <cstdlib>  
  6.  6 #include <ctime>  
  7.  7 using namespace std;  
  8.  8   
  9.  9 int main()  
  10. 10 {  
  11. 11     // seed random number generator  
  12. 12     srand(static_cast<unsigned int> (time(0)));  
  13. 13     int randomNumber = rand();  
  14. 14     // get a number between 1 and 6  
  15. 15     int die = (randomNumber % 6) + 1;  
  16. 16     cout << "You rolled a " << die << endl;  
  17. 17     return 0;  
  18. 18 }  
wang@wang:~/test$ ./die_roller 
You rolled a 3
wang@wang:~/test$ ./die_roller 
You rolled a 3
wang@wang:~/test$ ./die_roller 
You rolled a 6
(030) 猜数字游戏,适合三岁小孩子玩。

[cpp] view plain copy
  1.  1 // Guess My Number  
  2.  2 // The classic number guessing game  
  3.  3 #include <iostream>  
  4.  4 #include <cstdlib>  
  5.  5 #include <ctime>  
  6.  6 using namespace std;  
  7.  7   
  8.  8 int main()  
  9.  9 {  
  10. 10     // seed random  
  11. 11     srand(static_cast<unsigned int>(time(0)));  
  12. 12     // random number between 1 and 100  
  13. 13     int secretNumber = rand() % 100 + 1;  
  14. 14     int tries = 0;  
  15. 15     int guess;  
  16. 16     cout << "\tWelcome to Guess My Number\n";  
  17. 17     do {  
  18. 18         cout << "Enter a guess: ";  
  19. 19         cin >> guess;  
  20. 20         ++tries;  
  21. 21         if (guess > secretNumber)  
  22. 22             cout << "Too high!\n";  
  23. 23         else if (guess < secretNumber)  
  24. 24             cout << "Too low!\n";  
  25. 25         else  
  26. 26             cout << "That's it! you got it in " << tries << " guesses!\n";  
  27. 27     } while (guess != secretNumber);  
  28. 28     return 0;  
  29. 29 }  
wang@wang:~/test$ ./guess_my_number 
    Welcome to Guess My Number
Enter a guess: 56
Too high!
Enter a guess: 28
Too high!
Enter a guess: 14
Too high!
Enter a guess: 8
Too high!
Enter a guess: 4
Too high!
Enter a guess: 2
Too low!
Enter a guess: 3
That's it! you got it in 7 guesses!

(031) 习题

1. 使用enum表示。

[cpp] view plain copy
  1.  1 #include <iostream>  
  2.  2 using namespace std;  
  3.  3   
  4.  4 int main()  
  5.  5 {  
  6.  6     cout << "Difficult Levels\n";  
  7.  7     cout << "1 - Easy\n";  
  8.  8     cout << "2 - Normal\n";  
  9.  9     cout << "3 - Hard\n";  
  10. 10     enum level {EASY = 1, NORMAL, HARD};  
  11. 11     int choice;  
  12. 12     cout << "Choice: ";  
  13. 13     cin >> choice;  
  14. 14     switch (choice) {  
  15. 15     case EASY:  
  16. 16         cout << "You picked Easy.\n";  
  17. 17         break;  
  18. 18     case NORMAL:  
  19. 19         cout << "You picked Normal.\n";  
  20. 20         break;  
  21. 21     case HARD:  
  22. 22         cout << "You picked Hard.\n";  
  23. 23     default:  
  24. 24         cout << "You made an illegal choice.\n";  
  25. 25     }  
  26. 26     return 0;  
  27. 27 }  
wang@wang:~/test$ ./menulevel 
Difficult Levels
1 - Easy
2 - Normal
3 - Hard
Choice: 2
You picked Normal.

2. 没有进入while循环中。

3. 用户提供数据,电脑猜

[cpp] view plain copy
  1.  1 // Guess My Number  
  2.  2 // The classic number guessing game  
  3.  3 #include <iostream>  
  4.  4 #include <cstdlib>  
  5.  5 #include <ctime>  
  6.  6 using namespace std;  
  7.  7   
  8.  8 int main()  
  9.  9 {  
  10. 10     int number;  
  11. 11     cout << "Enter a number (1 - 10): ";  
  12. 12     cin >> number;  
  13. 13     int tries = 0;  
  14. 14     int guess;  
  15. 15     cout << "\tWelcome to Guess My Number\n";  
  16. 16     do {  
  17. 17         // seed random  
  18. 18         srand(static_cast<unsigned int>(time(0)));  
  19. 19         // random number between 1 and 10  
  20. 20         guess = rand() % 10 + 1;  
  21. 21         ++tries;  
  22. 22         if (guess > number)  
  23. 23             cout << "Too high!\n";  
  24. 24         else if (guess < number)  
  25. 25             cout << "Too low!\n";  
  26. 26         else  
  27. 27             cout << "That's it! you got it in " << tries << " guesses!\n";  
  28. 28     } while (guess != number);  
  29. 29     return 0;  
  30. 30 }  
随机猜猜的次数太多。

That's it! you got it in 300166 guesses!


Chapter 3: For Loops, Strings, And Arrays: Word Jumble

(032) for循环

[cpp] view plain copy
  1.  1 // Counter  
  2.  2 // Demonstrates for loops  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     cout << "Count forward: ";  
  10. 10     for (int i = 0; i < 10; ++i)  
  11. 11         cout << i << " ";  
  12. 12     cout << "\nCounting backward: ";  
  13. 13     for (int i = 9; i >= 0; --i)  
  14. 14         cout << i << " ";  
  15. 15     cout << "\nCounting by fives: ";  
  16. 16     for (int i = 0; i <= 50; i += 5)  
  17. 17         cout << i << " ";  
  18. 18     cout << "\nCounting with null statements: ";  
  19. 19     int count = 0;  
  20. 20     for (; count < 10;) {  
  21. 21         cout << count << " ";  
  22. 22         ++count;  
  23. 23     }  
  24. 24     cout << "\nCounting with nested for loops:\n";  
  25. 25     const int ROWS = 5;  
  26. 26     const int COLUMNS = 3;  
  27. 27     for (int i = 0; i < ROWS; ++i) {  
  28. 28         for (int j = 0; j < COLUMNS; ++j) {  
  29. 29             cout << i << "," << j << "  ";  
  30. 30         }  
  31. 31         cout << endl;  
  32. 32     }  
  33. 33     return 0;  
  34. 34 }  
wang@wang:~/test$ ./counter 
Count forward: 0 1 2 3 4 5 6 7 8 9 
Counting backward: 9 8 7 6 5 4 3 2 1 0 
Counting by fives: 0 5 10 15 20 25 30 35 40 45 50 
Counting with null statements: 0 1 2 3 4 5 6 7 8 9 
Counting with nested for loops:
0,0  0,1  0,2  
1,0  1,1  1,2  
2,0  2,1  2,2  
3,0  3,1  3,2  
4,0  4,1  4,2 

(033) string 对象的用法

string 几种不同的初始化方式。

earse第一个参数是位置,第二个参数是个数。

When using find(), you can supply an optional argument that specifies a character number for the program to start looking for the substring.

[cpp] view plain copy
  1.  1 // String Tester  
  2.  2 // Demonstrates string objects  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 #include <string>  
  6.  6 using namespace std;  
  7.  7   
  8.  8 int main()  
  9.  9 {  
  10. 10     string word1 = "Game";  
  11. 11     string word2("Over");  
  12. 12     string word3(3, '!');  
  13. 13   
  14. 14     string phrase = word1 + " " + word2 + word3;  
  15. 15     cout << "The phrase is: " << phrase << "\n";  
  16. 16     cout << "The phrase has " << phrase.size() << " characters in it.\n";  
  17. 17     cout << "The character at position 0 is: " << phrase[0] << "\n";  
  18. 18     cout << "Changing the character at position 0.\n";  
  19. 19     phrase[0] = 'L';  
  20. 20     cout << "The phrase is now: " << phrase << "\n";  
  21. 21     for (unsigned int i = 0; i < phrase.size(); ++i)  
  22. 22         cout << "Character at position " << i << " is: " << phrase[i] << "\n";  
  23. 23     cout << "The sequence 'Over' begins at location ";  
  24. 24     cout << phrase.find("Over") << endl;  
  25. 25     if (phrase.find("eggplant") == string::npos)  
  26. 26         cout << "'eggplant' is not in the phrase.\n";  
  27. 27     phrase.erase(4, 5);  
  28. 28     cout << "The phrase is now: " << phrase << endl;  
  29. 29     phrase.erase(4);  
  30. 30     cout << "The phrase is now: " << phrase << endl;  
  31. 31     phrase.erase();  
  32. 32     cout << "The phrase is now: " << phrase << endl;  
  33. 33     if (phrase.empty())  
  34. 34         cout << "The phrase is no more.\n";  
  35. 35     return 0;  
  36. 36 }  
wang@wang:~/test$ ./string_tester 
The phrase is: Game Over!!!
The phrase has 12 characters in it.
The character at position 0 is: G
Changing the character at position 0.
The phrase is now: Lame Over!!!
Character at position 0 is: L
Character at position 1 is: a
Character at position 2 is: m
Character at position 3 is: e
Character at position 4 is:  
Character at position 5 is: O
Character at position 6 is: v
Character at position 7 is: e
Character at position 8 is: r
Character at position 9 is: !
Character at position 10 is: !
Character at position 11 is: !
The sequence 'Over' begins at location 5
'eggplant' is not in the phrase.
The phrase is now: Lame!!!
The phrase is now: Lame
The phrase is now: 
The phrase is no more.
(034) 英雄复仇游戏

主要讲述携带的装备情况

[cpp] view plain copy
  1.  1 // Hero's Inventory  
  2.  2 // Demonstrates arrays  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 #include <string>  
  6.  6 using namespace std;  
  7.  7   
  8.  8 int main()  
  9.  9 {  
  10. 10     const int MAX_ITEMS = 10;  
  11. 11     string inventory[MAX_ITEMS];  
  12. 12     int numItems = 0;  
  13. 13     inventory[numItems++] = "sword";  
  14. 14     inventory[numItems++] = "armor";  
  15. 15     inventory[numItems++] = "shield";  
  16. 16     cout << "Your items:\n";  
  17. 17     for (int i = 0; i < numItems; i++)  
  18. 18         cout << inventory[i] << endl;  
  19. 19     cout << "You trade your sword for a battle axe.\n";  
  20. 20     inventory[0] = "battle axe";  
  21. 21     for (int i = 0; i < numItems; ++i)  
  22. 22         cout << inventory[i] << endl;  
  23. 23     cout << "The item name '" << inventory[0] << "' has ";  
  24. 24     cout << inventory[0].size() << " letters in it.\n";  
  25. 25     cout << "You find a healing potion.\n";  
  26. 26     if (numItems < MAX_ITEMS)  
  27. 27         inventory[numItems++] = "healing portion";  
  28. 28     else  
  29. 29         cout << "You have too many items and can't carry another.\n";  
  30. 30     for (int i = 0; i < numItems; ++i)  
  31. 31         cout << inventory[i] << endl;  
  32. 32     return 0;  
  33. 33 }  
wang@wang:~/test$ ./heros_inventory 
Your items:
sword
armor
shield
You trade your sword for a battle axe.
battle axe
armor
shield
The item name 'battle axe' has 10 letters in it.
You find a healing potion.
battle axe
armor
shield
healing portion

(035) index check

Testing to make sure that an index number is a valid array position before using it is called bounds checking.

(036) tic-tac-toe游戏

[cpp] view plain copy
  1.  1 // Tic-Tac-Toe Board  
  2.  2 // Demonstrates multidimensional arrays  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     const int ROWS = 3;  
  10. 10     const int COLUMNS = 3;  
  11. 11     char board[ROWS][COLUMNS] = {{'O''X''O'}, {' ''X''X'}, {'X''O''O'}};  
  12. 12     cout << "Here's the tic-tac-toe board:\n";  
  13. 13     for (int i = 0; i < ROWS; i++) {  
  14. 14         for (int j = 0; j < COLUMNS; ++j)  
  15. 15             cout << board[i][j];  
  16. 16         cout << endl;  
  17. 17     }  
  18. 18     cout << "'X' moves to the empty location.\n";  
  19. 19     board[1][0] = 'X';  
  20. 20     cout << "Now the tic-tac-toe board is:\n";  
  21. 21     for (int i = 0; i < ROWS; i++) {  
  22. 22         for(int j = 0; j < COLUMNS; ++j)  
  23. 23             cout << board[i][j];  
  24. 24         cout << endl;  
  25. 25     }  
  26. 26     cout << "'X' wins!\n";  
  27. 27     return 0;  
  28. 28 }  
wang@wang:~/test$ ./tic-tac-toe_board 
Here's the tic-tac-toe board:
OXO
 XX
XOO
'X' moves to the empty location.
Now the tic-tac-toe board is:
OXO
XXX
XOO
'X' wins!
(037) 猜字游戏

把单词打乱,然后根据提示猜是什么单词。

[cpp] view plain copy
  1. // Word Jumble  
  2. // The classic word jumble game where the player can ask for a hint  
  3. #include <iostream>  
  4. #include <string>  
  5. #include <cstdlib>  
  6. #include <ctime>  
  7. using namespace std;  
  8.   
  9. int main()  
  10. {  
  11.     enum field {WORD, HINT, NUM_FIELDS};  
  12.     const int NUM_WORDS = 5;  
  13.     const string WORDS[NUM_WORDS][NUM_FIELDS] = {  
  14.         {"wall""Do you feel you're banging your head against something?"},  
  15.         {"glasses""These might help you see the answer."},  
  16.         {"labored""Going slowly, is it?"},  
  17.         {"persistent""Keep at it."},  
  18.         {"jumble""It's what the game is all about."}};  
  19.     srand(static_cast<unsigned int>(time(0)));  
  20.     int choice = rand() % NUM_WORDS;  
  21.     string theWord = WORDS[choice][WORD];  
  22.     string theHint = WORDS[choice][HINT];  
  23.     // jumbled version of word  
  24.     string jumble = theWord;  
  25.     int length = jumble.size();  
  26.     for (int i = 0; i < length; ++i) {  
  27.         int index1 = (rand() % length);  
  28.         int index2 = (rand() % length);  
  29.         char temp = jumble[index1];  
  30.         jumble[index1] = jumble[index2];  
  31.         jumble[index2] = temp;  
  32.     }  
  33.     cout << "\t\tWelcome to Word Jumble!\n";  
  34.     cout << "Unscramble the letters to make a word.\n";  
  35.     cout << "Enter 'hint' for a hint.\n";  
  36.     cout << "Enter 'quit' to quit the game.\n";  
  37.     cout << "The jumble is: " << jumble;  
  38.     string guess;  
  39.     cout << "\nyou guess: ";  
  40.     cin >> guess;  
  41.     while ((guess != theWord) && (guess != "quit")) {  
  42.         if(guess == "hint")  
  43.             cout << theHint;  
  44.         else  
  45.             cout << "Sorry, that's not it.";  
  46.         cout << "\nYour guess: ";  
  47.         cin >> guess;  
  48.     }  
  49.     if (guess == theWord)  
  50.         cout << "That's it! You guess it!\n";  
  51.     cout << "Thanks for playing.\n";  
  52.     return 0;  
  53. }  
wang@wang:~/test$ ./word_jumble 
        Welcome to Word Jumble!
Unscramble the letters to make a word.
Enter 'hint' for a hint.
Enter 'quit' to quit the game.
The jumble is: eetpsitsnr
you guess: hint
Keep at it.
Your guess: persistent
That's it! You guess it!
Thanks for playing.
(038) 对象

Objects are encapsulated, cohesive entities that combine data (called data members) and functions (called member functions).

(039) 习题

1. 增加计数的效果

[cpp] view plain copy
  1. cin >> guess;  
  2.  41     int count = 1;  
  3.  42     while ((guess != theWord) && (guess != "quit")) {  
  4.  43         if(guess == "hint")  
  5.  44             cout << theHint;  
  6.  45         else  
  7.  46             cout << "Sorry, that's not it.";  
  8.  47         cout << "\nYour guess: ";  
  9.  48         cin >> guess;  
  10.  49         ++count;  
  11.  50     }  
2. 数组访问会越界

i < phrase.size();

3. char board[ROWS][COLUMNS]; 


Chapter 4: The Standard Template Library: Hangman

(040) 标准库

The STL(Standard Template Library) represents a powerful collection of programming work that's been done well.

(041) 使用vector举例

[html] view plain copy
  1.  1 // Hero's Inventory 2.0  
  2.  2 // Demonstrates vectors  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 #include <string>  
  6.  6 #include <vector>  
  7.  7 using namespace std;  
  8.  8   
  9.  9 int main()  
  10. 10 {  
  11. 11     vector<string> inventory;  
  12. 12     inventory.push_back("sword");  
  13. 13     inventory.push_back("armor");  
  14. 14     inventory.push_back("shield");  
  15. 15     cout << "You have " << inventory.size() << " items.\n";  
  16. 16     cout << "Your items:\n";  
  17. 17     for (unsigned int i = 0; i < inventory.size(); ++i)  
  18. 18         cout << inventory[i] << endl;  
  19. 19     cout << "You trade your sword for a battle axe.";  
  20. 20     inventory[0] = "battle axe";  
  21. 21     cout << "Your items:\n";  
  22. 22     for (unsigned int i = 0; i < inventory.size(); ++i)  
  23. 23         cout << inventory[i] << endl;  
  24. 24     cout << "The item name '" << inventory[0] << "' has ";  
  25. 25     cout << inventory[0].size() << " letters in it.\n";  
  26. 26     cout << "your shield is destroyed in a fierce battle.";  
  27. 27     inventory.pop_back();  
  28. 28     cout << "Your items:\n";  
  29. 29     for (unsigned int i = 0; i < inventory.size(); ++i)  
  30. 30         cout << inventory[i] << endl;  
  31. 31     cout << "You were robbed of all of your possessions by a thief.\n";  
  32. 32     inventory.clear();  
  33. 33     if (inventory.empty())  
  34. 34         cout << "You have nothing.\n";  
  35. 35     else  
  36. 36         cout << "You have at least one item.\n";  
  37. 37     return 0;  
  38. 38 }  
wang@wang:~/workspace/beginc++game$ ./heros_inventory2 
You have 3 items.
Your items:
sword
armor
shield
You trade your sword for a battle axe.Your items:
battle axe
armor
shield
The item name 'battle axe' has 10 letters in it.
your shield is destroyed in a fierce battle.Your items:
battle axe
armor
You were robbed of all of your possessions by a thief.
You have nothing.

(042) 迭代器举例

[cpp] view plain copy
  1.  1 // Hero's Inventory 3.0  
  2.  2 // Demonstrates iterators  
  3.  3 #include <iostream>  
  4.  4 #include <string>  
  5.  5 #include <vector>  
  6.  6 using namespace std;  
  7.  7   
  8.  8 int main()  
  9.  9 {  
  10. 10     vector<string> inventory;  
  11. 11     inventory.push_back("sword");  
  12. 12     inventory.push_back("armor");  
  13. 13     inventory.push_back("shield");  
  14. 14     vector<string>::iterator myIterator;  
  15. 15     vector<string>::const_iterator iter;  
  16. 16     cout << "Your items:\n";  
  17. 17     for (iter = inventory.begin(); iter != inventory.end(); ++iter)  
  18. 18         cout << *iter << endl;  
  19. 19     cout << "You trade your sword for a battle axe.\n";  
  20. 20     myIterator = inventory.begin();  
  21. 21     *myIterator = "battle axe";  
  22. 22     cout << "Your items:\n";  
  23. 23     for (iter = inventory.begin(); iter != inventory.end(); ++iter)  
  24. 24         cout << *iter << endl;  
  25. 25     cout << "The item name '" << *myIterator << "' has ";  
  26. 26     cout << (*myIterator).size() << " letters in it.\n";  
  27. 27     cout << "The item name '" << *myIterator << "' has ";  
  28. 28     cout << myIterator->size() << " letters in it.\n";  
  29. 29     cout << "You recover a corssbox from a slain enemy.\n";  
  30. 30     inventory.insert(inventory.begin(), "crossbox");  
  31. 31     cout << "Your items:\n";  
  32. 32     for (iter = inventory.begin(); iter != inventory.end(); ++iter)  
  33. 33         cout << *iter << endl;  
  34. 34     cout << "Your armor is destoryed in a fierce battle.\n";  
  35. 35     inventory.erase(inventory.begin() + 2);  
  36. 36     cout << "Your items:\n";  
  37. 37     for (iter = inventory.begin(); iter != inventory.end(); ++iter)  
  38. 38         cout << *iter << endl;  
  39. 39     return 0;  
  40. 40 }  
wang@wang:~/test$ ./heros_inventory3 
Your items:
sword
armor
shield
You trade your sword for a battle axe.
Your items:
battle axe
armor
shield
The item name 'battle axe' has 10 letters in it.
The item name 'battle axe' has 10 letters in it.
You recover a corssbox from a slain enemy.
Your items:
crossbox
battle axe
armor
shield
Your armor is destoryed in a fierce battle.
Your items:
crossbox
battle axe
shield
(043) insert方法

One form of the insert() member function inserts a new element into a vector just before the element referred to by a given iterator.

(044) 算法举例

The random_shuffle() algorithm randomizes the elements of a sequence.

The sort() algorithm sorts the elements of a sequence in ascending order.

[cpp] view plain copy
  1.  1 // High Scores  
  2.  2 // Demonstrates algorithms  
  3.  3 #include <iostream>  
  4.  4 #include <vector>  
  5.  5 #include <algorithm>  
  6.  6 #include <ctime>  
  7.  7 #include <cstdlib>  
  8.  8 using namespace std;  
  9.  9   
  10. 10 int main()  
  11. 11 {  
  12. 12     vector<int>::const_iterator iter;  
  13. 13     cout << "Creating a list of scores.\n";  
  14. 14     vector<int> scores;  
  15. 15     scores.push_back(1500);  
  16. 16     scores.push_back(3500);  
  17. 17     scores.push_back(7500);  
  18. 18   
  19. 19     cout << "High Scores:\n";  
  20. 20     for (iter = scores.begin(); iter != scores.end(); ++iter)  
  21. 21         cout << *iter << endl;  
  22. 22     cout << "Finding a score:\n";  
  23. 23     int score;  
  24. 24     cout << "Enter a score to find: ";  
  25. 25     cin >> score;  
  26. 26     iter = find(scores.begin(), scores.end(), score);  
  27. 27     if (iter != scores.end())  
  28. 28         cout << "Score found.\n";  
  29. 29     else  
  30. 30         cout << "Score not found.\n";  
  31. 31     cout << "Randomizing scores.\n";  
  32. 32     srand(static_cast<unsigned int>(time(0)));  
  33. 33     random_shuffle(scores.begin(), scores.end());  
  34. 34     cout << "High Scores:\n";  
  35. 35     for (iter = scores.begin(); iter != scores.end(); ++iter)  
  36. 36         cout << *iter << endl;  
  37. 37     cout << "Sorting scores.\n";  
  38. 38     sort(scores.begin(), scores.end());  
  39. 39     cout << "High Scores:\n";  
  40. 40     for (iter = scores.begin(); iter != scores.end(); ++iter)  
  41. 41         cout << *iter << endl;  
  42. 42     return 0;  
  43. 43 }  
wang@wang:~/test$ ./high_scores 
Creating a list of scores.
High Scores:
1500
3500
7500
Finding a score:
Enter a score to find: 7500
Score found.
Randomizing scores.
High Scores:
7500
3500
1500
Sorting scores.
High Scores:
1500
3500
7500
(045) 标注库提供的所有容器

deque                   Sequential                    Double-ended queue

list                          Sequential                    Linear list

map                       Associative                   Collection of key/value pairs in which each key is associated with exactly one value

multimap              Associative                   Collection of key/value pairs in which each key may be associated with more than one value

multiset                 Associative                   Collection in which each element is not necessarily unique

priority_queue     Adaptor                         Priority queue

queue                    Adaptor                         Queue

set                           Associative                  Collection in which each element is unique

stack                       Adaptor                        Stack

vector                     Sequential                   Dynamic array

(046) Pseudocode伪代码

需要很好的英语基础。

Many programmers sketch out their programs using pseudocode - a language that falls somewhere between English and a formal programming language.

By taking each step described in pseudocode and breaking it down into series of simpler steps, the plan becomes closer to programming code.

(047) 伪代码举例

比较经典的例子,猜字游戏,只有八次机会;

刚开始的时候可以乱猜,后来根据已知的字符猜未知的字符。

[cpp] view plain copy
  1. /* 
  2.  * Pseudocode 
  3.  * Create a group of words 
  4.  * Pick a random word from the group as the secret word 
  5.  * While player hasn't made too many incorrect guesses and hasn't 
  6.  * guessed the secret word 
  7.  *      Tell player how many incorrect guesses he or she has left 
  8.  *      Show player the letters he or she has guessed 
  9.  *      Show player how much of the secret word he or she has guessed 
  10.  *      Get player's next guess 
  11.  *      While player has entered a letter that he has already guessed 
  12.  *          Get player's guess 
  13.  *      Add the new guess to the group of used letters 
  14.  *      If the guess is in the secret word 
  15.  *          Tell the player the guess is correct 
  16.  *          Update the word guessed so far with the new letter 
  17.  *      Otherwise 
  18.  *          Tell the player the guess is incorrect 
  19.  * made 
  20.  * If the player has made too many incorrect guesses 
  21.  *      Tell the player that he or she has been hanged 
  22.  * Otherwise 
  23.  *      Congratulate the player on guessing the secret word 
  24.  */  
  25.   
  26. // Hangman  
  27. // The classic game of hangman  
  28. #include <iostream>  
  29. #include <string>  
  30. #include <vector>  
  31. #include <algorithm>  
  32. #include <ctime>  
  33. #include <cctype>  
  34.   
  35. using namespace std;  
  36.   
  37. int main(int argc, char *argv[])  
  38. {  
  39.     // setup  
  40.     // maximum number of incorrect guesses allowed  
  41.     const int MAX_WRONG = 8;  
  42.     vector<string> words;  
  43.     words.push_back("GUESS");  
  44.     words.push_back("HANGMAN");  
  45.     words.push_back("DIFFICULT");  
  46.     srand(static_cast<unsigned int>(time(0)));  
  47.     random_shuffle(words.begin(), words.end());  
  48.     const string THE_WORD = words[0];  
  49.     // number of incorrect guesses  
  50.     int wrong = 0;  
  51.     // word guessed so far  
  52.     string soFar(THE_WORD.size(), '-');  
  53.     // letters already guessed  
  54.     string used = "";  
  55.   
  56.     cout << "Welcome to Hangman. Good luck!\n";  
  57.   
  58.     // main loop  
  59.     while ((wrong < MAX_WRONG) && (soFar != THE_WORD)) {  
  60.         cout << "You have " << (MAX_WRONG - wrong) << " incorrect guesses left.\n";  
  61.         cout << "You have used the following letters: " << used << endl;  
  62.         cout << "So far, the word is: " << soFar << endl;  
  63.         char guess;  
  64.         cout << "Enter your guess: ";  
  65.         cin >> guess;  
  66.         // make uppercase since secret word in uppercase  
  67.         guess = toupper(guess);  
  68.         while (used.find(guess) != string::npos) {  
  69.             cout << "You have already guessed " << guess << endl;  
  70.             cout << "Enter your guess: ";  
  71.             cin >> guess;  
  72.             guess = toupper(guess);  
  73.         }  
  74.         used += guess;  
  75.         if (THE_WORD.find(guess) != string::npos) {  
  76.             cout << "That's right! " << guess << " is in the word.\n";  
  77.             // update soFar to include newly guessed letter  
  78.             for (int i = 0; i < THE_WORD.size(); ++i)  
  79.                 if (THE_WORD[i] == guess)  
  80.                     soFar[i] = guess;  
  81.         } else {  
  82.             cout << "Sorry, " << guess << " isn't in the word.\n";  
  83.             ++wrong;  
  84.         }  
  85.     }  
  86.     // shut down  
  87.     if (wrong == MAX_WRONG)  
  88.         cout << "You have been hanged!\n";  
  89.     else  
  90.         cout << "You guess it!\n";  
  91.     cout << "The word was " << THE_WORD << endl;  
  92.   
  93.     return 0;  
  94. }  

Welcome to Hangman. Good luck!
You have 8 incorrect guesses left.
You have used the following letters: 
So far, the word is: -------
Enter your guess: a
That's right! A is in the word.
You have 8 incorrect guesses left.
You have used the following letters: A
So far, the word is: -A---A-
Enter your guess: h
That's right! H is in the word.
You have 8 incorrect guesses left.
You have used the following letters: AH
So far, the word is: HA---A-
Enter your guess: n
That's right! N is in the word.
You have 8 incorrect guesses left.
You have used the following letters: AHN
So far, the word is: HAN--AN
Enter your guess: g
That's right! G is in the word.
You have 8 incorrect guesses left.
You have used the following letters: AHNG
So far, the word is: HANG-AN
Enter your guess: m
That's right! M is in the word.
You guess it!
The word was HANGMAN

(048) 习题

1. 编写vector包括你喜欢的游戏

[cpp] view plain copy
  1.  1 #include <algorithm>  
  2.  2 #include <iostream>  
  3.  3 #include <vector>  
  4.  4 using namespace std;  
  5.  5   
  6.  6 int main()  
  7.  7 {  
  8.  8     vector<string> games;  
  9.  9     vector<string>::iterator iter;  
  10. 10     games.push_back("war world");  
  11. 11     games.push_back("person vender");  
  12. 12     iter = games.begin();  
  13. 13     games.insert(iter, "hello world");  
  14. 14     for (iter = games.begin(); iter != games.end(); ++iter)  
  15. 15         cout << *iter << endl;  
  16. 16     return 0;  
  17. 17 }  
wang@wang:~/test$ ./list_game 
hello world
war world
person vender
2. 每次都是调过一个数据,没有每个都遍历

3. 伪代码,写得不好。

get some words and introduction about every word.
choose one word in random.
jumble the word.
guess the word
    if word equal quit, exit the game
    if word equal hint, give the word introduction
if guess equal the word
    you success


Chapter 5: Functions: Mad Lib

(049) 函数简单举例

[cpp] view plain copy
  1.  1 // Instructions  
  2.  2 // Demonstrates writing new functions  
  3.  3 #include <iostream>  
  4.  4 using namespace std;  
  5.  5   
  6.  6 // function prototype (declaration)  
  7.  7 void instruction();  
  8.  8   
  9.  9 int main()  
  10. 10 {  
  11. 11     instruction();  
  12. 12     return 0;  
  13. 13 }  
  14. 14   
  15. 15 // function definition  
  16. 16 void instruction() {  
  17. 17     cout << "Welcome to the most fun you've ever had with text!\n";  
  18. 18     cout << "Here's how to play the game...\n";  
  19. 19 }  
wang@wang:~/test$ ./instructions 
Welcome to the most fun you've ever had with text!
Here's how to play the game...

(050)  第二个例子,传递参数

[cpp] view plain copy
  1.  1 // Yes or No  
  2.  2 // Demonstrates return values and parameters  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 #include <string>  
  6.  6 using namespace std;  
  7.  7   
  8.  8 char askYesNo1();  
  9.  9 char askYesNo2(string question);  
  10. 10   
  11. 11 int main()  
  12. 12 {  
  13. 13     char answer1 = askYesNo1();  
  14. 14     cout << "Thank you for answering: " << answer1 << "\n";  
  15. 15     char answer2 = askYesNo2("Do you wish to save your game?");  
  16. 16     cout << "Thanks for answering: " << answer2 << "\n";  
  17. 17     return 0;  
  18. 18 }  
  19. 19   
  20. 20 char askYesNo1() {  
  21. 21     char response1;  
  22. 22     do {  
  23. 23         cout << "Please enter 'y' or 'n': ";  
  24. 24         cin >> response1;  
  25. 25     } while(response1 != 'y' && response1 != 'n');  
  26. 26     return response1;  
  27. 27 }  
  28. 28   
  29. 29 char askYesNo2(string question) {  
  30. 30     char response2;  
  31. 31     do {  
  32. 32         cout << question << " (y/n): ";  
  33. 33         cin >> response2;  
  34. 34     } while (response2 != 'y' && response2 != 'n');  
  35. 35     return response2;  
  36. 36 }  
wang@wang:~/test$ ./yes_or_no 
Please enter 'y' or 'n': n
Thank you for answering: n
Do you wish to save your game? (y/n): y
Thanks for answering: y
(051) 不要做别人重复的工作

It's always a waste of time to reinvent the wheel.

Increased company productivity.

Improved software quality.

Improved software performance.

(052) 变量空间

Every time you use curly braces to create a block, you create a scope.

[cpp] view plain copy
  1.  1 // Scoping  
  2.  2 // Demonstrates scopes  
  3.  3 #include <iostream>  
  4.  4 using namespace std;  
  5.  5 void func();  
  6.  6 int main()  
  7.  7 {  
  8.  8     // local variable in main  
  9.  9     int var = 5;  
  10. 10     cout << "In main() var is: " << var << "\n";  
  11. 11     func();  
  12. 12     cout << "Back in main() var is: " << var << endl;  
  13. 13     {  
  14. 14         cout << "In main() in a new scope var is: " << var << endl;  
  15. 15         cout << "Creating new var in new scope.\n";  
  16. 16         // variable in new scope, hides other variable named var  
  17. 17         int var = 10;  
  18. 18         cout << "In main() in a new scope var is: " << var << "\n";  
  19. 19     }  
  20. 20     cout << "At end of main() var created in new scope no longer exists.\n";  
  21. 21     cout << "At end of main() var is: " << var << "\n";  
  22. 22     return 0;  
  23. 23 }  
  24. 24   
  25. 25 void func()  
  26. 26 {  
  27. 27     int var = -5;  
  28. 28     cout << "In func() var is: " << var << "\n";  
  29. 29 }  
wang@wang:~/test$ ./scoping 
In main() var is: 5
In func() var is: -5
Back in main() var is: 5
In main() in a new scope var is: 5
Creating new var in new scope.
In main() in a new scope var is: 10
At end of main() var created in new scope no longer exists.
At end of main() var is: 5
(053) 全局变量举例

[cpp] view plain copy
  1.  1 // Global Reach  
  2.  2 // Demonstrates global variables  
  3.  3 #include <iostream>  
  4.  4 using namespace std;  
  5.  5 // global variable  
  6.  6 int glob = 10;  
  7.  7 void access_global();  
  8.  8 void hide_global();  
  9.  9 void change_global();  
  10. 10 int main()  
  11. 11 {  
  12. 12     cout << "In main() glob is: " << glob << "\n";  
  13. 13     access_global();  
  14. 14     hide_global();  
  15. 15     cout << "In main() glob is: " << glob << endl;  
  16. 16     change_global();  
  17. 17     cout << "In main() glob is: " << glob << endl;  
  18. 18     return 0;  
  19. 19 }  
  20. 20   
  21. 21 void access_global() {  
  22. 22     cout << "In access_global() glob is: " << glob << endl;  
  23. 23 }  
  24. 24   
  25. 25 void hide_global() {  
  26. 26     // hide global variable glob  
  27. 27     int glob = 0;  
  28. 28     cout << "In hide_global() glob is: " << glob << endl;  
  29. 29 }  
  30. 30   
  31. 31 void change_global() {  
  32. 32     glob = -10;  
  33. 33     cout << "In change_global() glob is: " << glob << "\n";  
  34. 34 }  
wang@wang:~/test$ ./global_reach 
In main() glob is: 10
In access_global() glob is: 10
In hide_global() glob is: 0
In main() glob is: 10
In change_global() glob is: -10
In main() glob is: -10
(054) 常量全局变量

Unlike global variables, which can make your programs confusing, global constants -- constants that can be accessed from anywhere in your program -- can help make programs clearer.

(055) 默认参数

[cpp] view plain copy
  1.  1 // Give me a Number  
  2.  2 // Demonsrates default function arguments  
  3.  3 #include <iostream>  
  4.  4 #include <string>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int askNumber(int high, int low = 1);  
  8.  8   
  9.  9 int main()  
  10. 10 {  
  11. 11     int number = askNumber(5);  
  12. 12     cout << "Thanks for entering: " << number << "\n";  
  13. 13     number = askNumber(10, 5);  
  14. 14     cout << "Thanks for entering: " << number << "\n";  
  15. 15     return 0;  
  16. 16 }  
  17. 17   
  18. 18 int askNumber(int high, int low) {  
  19. 19     int num;  
  20. 20     do {  
  21. 21         cout << "Please enter a number (" << low << " - " << high << "): ";  
  22. 22         cin >> num;  
  23. 23     } while (num > high || num < low);  
  24. 24     return num;  
  25. 25 }  
wang@wang:~/test$ ./give_me_a_number 
Please enter a number (1 - 5): 3
Thanks for entering: 3
Please enter a number (5 - 10): 6
Thanks for entering: 6
(056) 重载函数

[cpp] view plain copy
  1.  1 // Triple  
  2.  2 // Demonstrates function overloading  
  3.  3 #include <iostream>  
  4.  4 #include <string>  
  5.  5 using namespace std;  
  6.  6 int triple(int number);  
  7.  7 string triple(string text);  
  8.  8   
  9.  9 int main()  
  10. 10 {  
  11. 11     cout << "Tripling 5: " << triple(5) << "\n";  
  12. 12     cout << "Tripling 'gamer': " << triple("gamer") << "\n";  
  13. 13     return 0;  
  14. 14 }  
  15. 15   
  16. 16 int triple(int number) {  
  17. 17     return (number * 3);  
  18. 18 }  
  19. 19   
  20. 20 string triple(string text) {  
  21. 21     return (text + text + text);  
  22. 22 }  
wang@wang:~/test$ ./triple 
Tripling 5: 15
Tripling 'gamer': gamergamergamer
(057) 内联函数

内联函数和默认参数相反,默认参数是在生命中,内联函数是在定义中。

[cpp] view plain copy
  1.  1 // Taking Damage  
  2.  2 // Demonstrates function inlining  
  3.  3 #include <iostream>  
  4.  4 int radiation(int health);  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     int health = 80;  
  10. 10     cout << "Your health is " << health << "\n";  
  11. 11     health = radiation(health);  
  12. 12     cout << "After radiation exposure your health is " << health << endl;  
  13. 13     health = radiation(health);  
  14. 14     cout << "After radiation exposure your health is " << health << endl;  
  15. 15     health = radiation(health);  
  16. 16     cout << "After radiation exposure your health is " << health << endl;  
  17. 17     return 0;  
  18. 18 }  
  19. 19   
  20. 20 inline int radiation(int health) {  
  21. 21     return (health / 2);  
  22. 22 }                    

wang@wang:~/test$ ./taking_damage 
Your health is 80
After radiation exposure your health is 40
After radiation exposure your health is 20
After radiation exposure your health is 10
(058) 综合举例

[cpp] view plain copy
  1. // Mad-Lib  
  2. // Creates a story based on user input  
  3. #include <iostream>  
  4. #include <string>  
  5. using namespace std;  
  6. string askText(string prompt);  
  7. int askNumber(string prompt);  
  8. void tellStory(string name, string noun, int number, string bodyPart, string verb);  
  9.   
  10. int main()  
  11. {  
  12.     cout << "Welcome to Mad Lib.\n";  
  13.     cout << "Answer the following questions to help create a new story.\n";  
  14.     string name = askText("Please enter a name: ");  
  15.     string noun = askText("Please enter a plural noun: ");  
  16.     int number = askNumber("Please enter a number: ");  
  17.     string bodyPart = askText("Please enter a body part: ");  
  18.     string verb = askText("Please enter a verb: ");  
  19.     tellStory(name, noun, number, bodyPart, verb);  
  20.     return 0;  
  21. }  
  22.   
  23. string askText(string prompt)  
  24. {  
  25.     string text;  
  26.     cout << prompt;  
  27.     cin >> text;  
  28.     return text;  
  29. }  
  30.   
  31. int askNumber(string prompt)  
  32. {  
  33.     int num;  
  34.     cout << prompt;  
  35.     cin >> num;  
  36.     return num;  
  37. }  
  38.   
  39. void tellStory(string name, string noun, int number, string bodyPart, string verb)  
  40. {  
  41.     cout << "Here's your story:\n";  
  42.     cout << "The famous explorer " << name;  
  43.     cout << " had nearly given up a life-long quest to find.\n";  
  44.     cout << "The Lost City of " << noun << " when one day, the " << noun;  
  45.     cout << " found the explorer.\n";  
  46.     cout << "Surrounded by " << number << " " << noun;  
  47.     cout << ", a tear came to " << name << "'s " << bodyPart << ".\n";  
  48.     cout << "After all this time, the quest was finally over. ";  
  49.     cout << "And then, then " << noun << endl;  
  50.     cout << "promptly devoured ";  
  51.     cout << name << ". ";  
  52.     cout << "The moral of the story? Be careful what you " << verb << " for.\n";  
  53. }  
wang@wang:~/test$ ./mad_lib 
Welcome to Mad Lib.
Answer the following questions to help create a new story.
Please enter a name: wang
Please enter a plural noun: wang
Please enter a number: 4
Please enter a body part: head
Please enter a verb: do
Here's your story:
The famous explorer wang had nearly given up a life-long quest to find.
The Lost City of wang when one day, the wang found the explorer.
Surrounded by 4 wang, a tear came to wang's head.
After all this time, the quest was finally over. And then, then wang
promptly devoured wang. The moral of the story? Be careful what you dofor.
(059) 习题

1. 默认参数放在函数生命最后。

2.  Two function, one for input, another for judge.

[cpp] view plain copy
  1. // Hangman  
  2. // The classic game of hangman  
  3. #include <iostream>  
  4. #include <string>  
  5. #include <vector>  
  6. #include <algorithm>  
  7. #include <ctime>  
  8. #include <cctype>  
  9.   
  10. using namespace std;  
  11.   
  12. char guesschar() {  
  13.     char guess;  
  14.     cout << "Enter your guess: ";  
  15.     cin >> guess;  
  16.     // make uppercase since secret word in uppercase  
  17.     guess = toupper(guess);  
  18.     return guess;  
  19. }  
  20.   
  21. bool include(char c, string word) {  
  22.     for (int i = 0; i < word.size(); ++i)  
  23.         if (c == word[i])  
  24.             return true;  
  25. }  
  26.   
  27. int main(int argc, char *argv[])  
  28. {  
  29.     // setup  
  30.     // maximum number of incorrect guesses allowed  
  31.     const int MAX_WRONG = 8;  
  32.     vector<string> words;  
  33.     words.push_back("GUESS");  
  34.     words.push_back("HANGMAN");  
  35.     words.push_back("DIFFICULT");  
  36.     srand(static_cast<unsigned int>(time(0)));  
  37.     random_shuffle(words.begin(), words.end());  
  38.     const string THE_WORD = words[0];  
  39.     // number of incorrect guesses  
  40.     int wrong = 0;  
  41.     // word guessed so far  
  42.     string soFar(THE_WORD.size(), '-');  
  43.     // letters already guessed  
  44.     string used = "";  
  45.   
  46.     cout << "Welcome to Hangman. Good luck!\n";  
  47.   
  48.     // main loop  
  49.     while ((wrong < MAX_WRONG) && (soFar != THE_WORD)) {  
  50.         cout << "You have " << (MAX_WRONG - wrong) << " incorrect guesses left.\n";  
  51.         cout << "You have used the following letters: " << used << endl;  
  52.         cout << "So far, the word is: " << soFar << endl;  
  53.         char guess = guesschar();  
  54.         while (used.find(guess) != string::npos) {  
  55.             cout << "You have already guessed " << guess << endl;  
  56.             guess = getchar();  
  57.         }  
  58.         used += guess;  
  59.         if (include(guess, THE_WORD)) {  
  60.             cout << "That's right! " << guess << " is in the word.\n";  
  61.             // update soFar to include newly guessed letter  
  62.             for (int i = 0; i < THE_WORD.size(); ++i)  
  63.                 if (THE_WORD[i] == guess)  
  64.                     soFar[i] = guess;  
  65.         } else {  
  66.             cout << "Sorry, " << guess << " isn't in the word.\n";  
  67.             ++wrong;  
  68.         }  
  69.     }  
  70.     // shut down  
  71.     if (wrong == MAX_WRONG)  
  72.         cout << "You have been hanged!\n";  
  73.     else  
  74.         cout << "You guess it!\n";  
  75.     cout << "The word was " << THE_WORD << endl;  
  76.   
  77.     return 0;  
  78. }  
Welcome to Hangman. Good luck!
You have 8 incorrect guesses left.
You have used the following letters: 
So far, the word is: -----
Enter your guess: E
That's right! E is in the word.
You have 8 incorrect guesses left.
You have used the following letters: E
So far, the word is: --E--
Enter your guess: F
Sorry, F isn't in the word.
You have 7 incorrect guesses left.
You have used the following letters: EF
So far, the word is: --E--
Enter your guess: D
Sorry, D isn't in the word.
You have 6 incorrect guesses left.
You have used the following letters: EFD
So far, the word is: --E--
Enter your guess: S
That's right! S is in the word.
You have 6 incorrect guesses left.
You have used the following letters: EFDS
So far, the word is: --ESS
Enter your guess: G
That's right! G is in the word.
You have 6 incorrect guesses left.
You have used the following letters: EFDSG
So far, the word is: G-ESS
Enter your guess: E
You have already guessed E
Sorry, 
 isn't in the word.
You have 5 incorrect guesses left.
You have used the following letters: EFDSG
So far, the word is: G-ESS
Enter your guess: U
That's right! U is in the word.
You guess it!
The word was GUESS

Press <RETURN> to close this window...

3. default argument

[cpp] view plain copy
  1.  1 #include <iostream>  
  2.  2 #include <string>  
  3.  3 using namespace std;  
  4.  4   
  5.  5