Beginning C++ Through Game Progamming 全书学习笔记

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.

 1 // Game Over
  2 // A first C++ program
  3 #include <iostream>
  4 
  5 int main()
  6 {
  7     std::cout << "Game Over!" << std::endl;
  8     return 0;
  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

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

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

(009) 加减乘除

  1 // Expensive Calculator
  2 // Demonstrates built-in arithmetic operators
  3 
  4 #include <iostream>
  5 using namespace std;
  6 
  7 int main()
  8 {
  9     cout << "7 + 3 = " << 7 + 3 << endl;
 10     cout << "7 - 3 = " << 7 - 3 << endl;
 11     cout << "7 * 3 = " << 7 * 3 << endl;
 12 
 13     cout << "7 / 3 = " << 7 / 3 << endl;
 14     cout << "7.0 / 3.0 = " << 7.0 / 3.0 << endl;
 15 
 16     cout << "7 % 3 = " << 7 % 3 << endl;
 17 
 18     cout << "7 + 3 * 5 = " << 7 + 3 * 5 << endl;
 19     cout << "(7 + 3) * 5 = " << (7 + 3) * 5 << endl;
 20 
 21     return 0;
 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) 状态值举例

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

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

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

有趣的文字游戏

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

  1 #include <iostream>
  2 using namespace std;
  3 
  4 int main()
  5 {
  6     int firstScore, secondScore, thirdScore;
  7     cout << "Enter three integers: ";
  8     cin >> firstScore >> secondScore >> thirdScore;
  9     int average = (firstScore + secondScore + thirdScore) / 3;
 10     cout << average << endl;
 11     return 0;
 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;

  1 // Score Rater
  2 // Demonstrates the if statement
  3 
  4 #include <iostream>
  5 using namespace std;
  6 
  7 int main()
  8 {
  9     if (true) {
 10         cout << "This is always displayd.\n";
 11     }
 12     if (false) {
 13         cout << "This is never displayed.\n";
 14     }
 15 
 16     int score = 1000;
 17     if (score) {
 18         cout << "At least you didn't score zero.\n";
 19     }
 20     if (score > 250) {
 21         cout << "You scored 250 more. Decent.\n";
 22     }
 23     if (score >= 500) {
 24         cout << "You scored 500 or more. Nice.\n";
 25         if (score >= 1000) {
 26             cout << "You scored 1000 or more. Impressive!\n";
 27         }
 28     }
 29     return 0;
 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 语句

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

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

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

  1 // Play Again
  2 // Demonstrates while loops
  3 
  4 #include <iostream>
  5 using namespace std;
  6 
  7 int main()
  8 {
  9     char again = 'y';
 10     while (again == 'y') {
 11         cout << "**Played an exciting game**\n";
 12         cout << "Do you want to play again? (y/n): ";
 13         cin >> again;
 14     }
 15     cout << "Okay, bye.\n";
 16     return 0;
 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循环

  1 // Play Again 2.0
  2 // Demonstrates do loops
  3 
  4 #include <iostream>
  5 using namespace std;
  6 
  7 int main()
  8 {
  9     char again;
 10     do {
 11         cout << "**Played an exciting game**";
 12         cout << "\nDo you want to play again? (y/n): ";
 13         cin >> again;
 14     } while (again == 'y');
 15 
 16     cout << "Okay, bye.\n";
 17     return 0;
 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.

  1 // Finicky Counter
  2 // Demonstrates break and continue statements
  3 
  4 #include <iostream>
  5 using namespace std;
  6 
  7 int main()
  8 {
  9     int count = 0;
 10     while (true) {
 11         count += 1;
 12         // end loop if count is greater than 10
 13         if (count > 10)
 14             break;
 15         // skip the number 5
 16         if (count == 5)
 17             continue;
 18         cout << count << endl;
 19     }
 20     return 0;
 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, ||.

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

  1 // Die Roller
  2 // Demonstrates generating random numbers
  3 
  4 #include <iostream>
  5 #include <cstdlib>
  6 #include <ctime>
  7 using namespace std;
  8 
  9 int main()
 10 {
 11     // seed random number generator
 12     srand(static_cast<unsigned int> (time(0)));
 13     int randomNumber = rand();
 14     // get a number between 1 and 6
 15     int die = (randomNumber % 6) + 1;
 16     cout << "You rolled a " << die << endl;
 17     return 0;
 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) 猜数字游戏,适合三岁小孩子玩。

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

  1 #include <iostream>
  2 using namespace std;
  3 
  4 int main()
  5 {
  6     cout << "Difficult Levels\n";
  7     cout << "1 - Easy\n";
  8     cout <<
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值