且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

《C++游戏编程入门(第4版)》——1.8 Lost Fortune简介

更新时间:2022-09-21 16:04:46

本节书摘来自异步社区出版社《C++游戏编程入门(第4版)》一书中的第1章,第1.8节,作者:【美】Michael Dawson(道森),更多章节内容可以访问云栖社区“异步社区”公众号查看。

1.8 Lost Fortune简介

C++游戏编程入门(第4版)
本章最后一个项目Lost Fortune是一个拟人化的探险游戏。在游戏中,玩家输入一些信息,计算机把这些信息扩展成一个探险故事。程序的运行示例如图1.9所示。
![image]()


《C++游戏编程入门(第4版)》——1.8 Lost Fortune简介

图1.9 故事由玩家提供的细节构成

这里不一次展示全部代码,而是每次给出一部分。从Cengage Learning网站(www.cengageptr.com/
downloads)上可以下载到该程序的代码。程序位于Chapter 1文件夹中,文件名为lost_fortune.cpp。

1.8.1 创建程序

首先是一些初始注释、两个必要的头文件和一些using指令。

// Lost Fortune
// A personalized adventure
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::string;```
程序包含string文件,它是标准库的一部分。因此,通过变量,程序可以用string对象来存取字符串。关于string对象的内容很多,但这里不准备介绍。第3章将介绍更多关于string对象的知识。

同样,程序使用using指令明确指出准备使用的std名称空间中的对象。因此,我们能清楚地看到string属于std名称空间。

###1.8.2 从玩家获取信息
接下来程序从玩家获取一些信息。

int main()
{
   const int GOLD_PIECES = 900;
   int adventurers, killed, survivors;
   string leader;
   //get the information
   cout << "Welcome to Lost Fortunenn";
   cout << "Please enter the following for your personalized adventuren";
   cout << "Enter a number: ";
   cin >> adventurers;
   cout << "Enter a number, smaller than the first: ";
   cin >> killed;
   survivors = adventurers - killed;
   cout << "Enter your last name: ";
   cin >> leader;`
GOLD_PIECES是常量,用于存储探险家要寻找的宝藏中金块的数目。adventurers用于存储探险家的总数目。killed用于存储在旅途中死亡的探险家数目。程序计算出幸存的探险家数目并存储在survivors中。最后,程序还要获取玩家名字,存储在leader中。

陷阱
 简单地使用cin从用户获取字符串的方法只适用于字符串不包含空白字符(如制表符或空格)的情况。有方法可以弥补这一点,但这会涉及流的概念,超出了本章的讨论范围。因此,还是像这样使用cin,但要注意它的限制。

1.8.3 讲故事

接下来程序用变量来讲故事。

   //tell the story
   cout << "\nA brave group of " << adventurers << " set out on a quest ";
   cout << "-- in search of the lost treasure of the Ancient Dwarves. ";
   cout << "The group was led by that legendary rogue, " << leader << ".\n";
   cout << "\nAlong the way, a band of marauding ogres ambushed the party. ";
   cout << "All fought bravely under the command of " << leader;
   cout << ", and the ogres were defeated, but at a cost. ";
   cout << "Of the adventurers, " << killed << " were vanquished, ";
   
     cout << "leaving just " << survivors << " in the group.\n";
   cout << "\nThe party was about to give up all hope. ";
   cout << "But while laying the deceased to rest, ";
   cout << "they stumbled upon the buried fortune. ";
   cout << "So the adventurers split " << GOLD_PIECES << " gold pieces.";
   cout << leader << " held on to the extra " << (GOLD_PIECES % survivors);
   cout << " pieces to keep things fair of course.\n";

   return 0;
}```
程序的代码和惊险的叙述都非常清晰。然而要指出的是,为了计算探险队队长持有的金块数目,程序在表达GOLD_PIECES % survivors中使用了模除运算符。该表达式计算GOLD_PIECES / survivors的余数,也就是将幸存的探险家私藏的金块平分后剩下的金块数目。