编写一个简单的游戏来练习用 C++ 编程

> 
> C++ 语言很复杂，但它可以教会你很多关于数据类型、内存管理和代码链接的知识。
> 
> 
> 


![](/data/attachment/album/202101/05/110821dwzztxchazhto8ko.jpg)


学习一门编程语言有几种方法。如果你是编码新手，你通常会学习一些基本的计算机编码概念，并尝试应用它们。如果你已经知道如何用另一种语言进行编码，你可以重新学习编码概念在新语言中是如何表达的。


不管是哪种情况，学习这些新原理的便捷方法是创建一个简单的猜谜游戏。这会迫使你了解一门语言如何接收输入和发送输出，如何比较数据，如何控制程序的流程，以及如何利用条件来影响结果。它还确保你知道一门语言是如何组织其代码的；例如，Lua 或 [Bash](https://opensource.com/article/20/12/learn-bash) 可以很容易地作为脚本运行，而 [Java](https://opensource.com/article/20/12/learn-java-writing-guess-number-game) 则需要你创建一个类。


在本文中，我将演示如何用 [C++](https://www.cplusplus.com/) 在终端上实现猜谜游戏。


### 安装依赖关系


要跟上本文的步伐，你需要 C++ 和一个编译器。


在 Linux 上，你可以通过从你的发行版软件仓库中安装 Qt Creator IDE 来获得你所需要的一切。


在 Fedora、CentOS 或 RHEL 上：



```
$ sudo dnf install qt-creator

```

在 Debian、Ubuntu、Chromebook 或类似的系统上：



```
$ sudo apt install qtcreator

```

本文并没有使用 Qt Creator IDE，但它是一个安装你所需要的一切的简单方法，对于复杂的 C++ 项目（包括那些带有 GUI 的项目），它是一个必不可少的工具。在 macOS 或 Windows 上，按照 Qt 网站上的[安装说明](https://www.qt.io/product/development-tools)进行安装。


### 设置包含和命名空间


C++ 的核心语言是精简的。即使是一个简单的应用程序也需要使用额外的库。这个应用程序使用 [iostream](http://www.cplusplus.com/reference/iostream/) 来获得对 `cout` 和 `cin` 关键字的访问。


另外，确保程序使用 `std` 命名空间：



```
#include <iostream>

using namespace std;

```

这并不是绝对必要，但如果不将命名空间设置为 `std`，所有来自 `iostream` 库的关键字都需要一个命名空间前缀。例如，我不能写作 `cout`，而是要写作 `std::cout`。


C++ 中的语句以分号结束。


### 创建一个函数


每个 C++ 应用程序至少需要一个函数。一个 C++ 应用程序的主函数必须称为 `main`，它必须返回一个整数（`int`），这符合 [POSIX](https://opensource.com/article/19/7/what-posix-richard-stallman-explains) 的期望，即一个进程在成功时返回 0，而在失败时返回其他值。你可以通过为它提供返回类型和名称来创建一个新函数。



```
int main() {
 // code goes here
}

```

### 实现程序逻辑


游戏代码必须首先产生一个随机数供玩家猜测。在 C++ 中，你可以通过建立一个用于生成伪随机数的*种子*来实现。一个简单的种子就是当前的时间。一旦有了种子，你就可以得到一个在 1 和 100 之间的数字。通过调用 `rand` 函数，并设置上限值 100 来产生一个从 0 到 99 的随机数，所以无论选择了什么数字都要加 1，并将结果分配给一个名为 `number` 的变量。你还必须声明一个变量来保存玩家的猜测值。为了清楚起见，我称这个变量为 `guess`。


这个示例代码还包括一个调试语句，告诉你随机数到底是什么。这对于猜测游戏来说不是很好，但它使测试速度快了很多。以后，你可以删除这一行，或者直接在行前面用 `//` 注释出来：



```
 srand (time(NULL));
 int number = rand() % 100+1;
 int guess = 0;

 cout << number << endl; //debug

```

### 增加 do-while 和 if 语句


C++ 中的 `do-while` 语句以关键字 `do` 开头，并将你希望 C++ 做的所有事情用括号括起来。用 `while` 关键字结束语句，后面是必须满足的条件（括号内）：



```
do {
 // code here
} while ( number != guess );

```

游戏代码出现在 `if`、`else if` 和 `else` 语句之间，为玩家提供提示。


首先，用 `cout` 语句提示玩家猜测。`cout` 函数将输出打印到 `stdout` 上。因为 `cout` 语句没有连着 `endl`（endline）函数，所以没有换行。紧接着这个 `cout` 语句，通过使用 `cin` 函数告诉 C++ 等待输入。正如你所猜测的那样，`cin` 等待来自 `stdin` 的输入。


接下来，程序进入 `if` 控制语句。如果玩家的猜测大于 `number` 变量中包含的伪随机数，那么程序就会打印出一个提示，后面是一个换行符。这就中断了 `if` 语句，但 C++ 仍然被困在 `do-while` 循环中，因为它的条件（`number` 变量等于 `guess`）还没有满足。


如果玩家的猜测小于 `number` 变量中包含的伪随机数，那么程序就会打印出一个提示，后面是一个换行符。这再次中断了 `if` 语句，但程序仍然被困在 `do-while` 循环中。


当 `guess` 等于 `number` 时，最终满足关键条件，触发 `else` 语句，`do-while` 循环结束，程序结束：



```
do {
  cout << "Guess a number between 1 and 100: ";
  cin >> guess;

  if ( guess > number) { cout << "Too high.\n" << endl; }
  else if ( guess < number ) { cout << "Too low.\n" << endl; }
  else {
    cout << "That's right!\n" << endl;
    exit(0);
  } // fi
 } while ( number != guess );
return 0;
} // main

```

### 构建代码和玩游戏


你可以用 GCC 构建你的应用程序：



```
$ g++ -o guess.bin guess.cpp

```

运行二进制文件试试：



```
$ ./guess.bin
74
Guess a number between 1 and 100: 76
Too high.

Guess a number between 1 and 100: 1
Too low.

Guess a number between 1 and 100: 74
That's right!

```

成功了！


### 试试 C++ 吧


C++ 语言很复杂。为终端编写 C++ 应用程序可以让你学到很多关于数据类型、内存管理和代码链接的知识。试着用 C++ 编写一个有用的实用程序，看看你能发现什么！




---


via: <https://opensource.com/article/20/12/learn-c-game>


作者：[Seth Kenlon](https://opensource.com/users/seth) 选题：[lujun9972](https://github.com/lujun9972) 译者：[wxy](https://github.com/wxy) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
There are a couple of ways to learn a programming language. If you're new to coding, you usually learn some basic computer coding concepts and try to apply them. If you already know how to code in another language, you relearn how coding concepts are expressed in the new language.

In either case, a convenient way to learn these new principles is to create a simple guessing game. This forces you to understand how a language receives input and sends output, how it compares data, how to control a program's flow, and how to leverage conditionals to affect an outcome. It also ensures that you know how a language structures its code; for instance, Lua or [Bash](https://opensource.com/article/20/12/learn-bash) can easily run as a script, while [Java](https://opensource.com/article/20/12/learn-java-writing-guess-number-game) requires you to create a class.


In this article, I'll demonstrate how to implement a guessing game for the terminal in [C++](https://www.cplusplus.com/).

## Install dependencies

To follow along with this article, you need C++ and a compiler.

You can get everything you need on Linux by installing the Qt Creator IDE from your distribution's software repository.

On Fedora, CentOS, or RHEL:

`$ sudo dnf install qt-creator`


On Debian, Ubuntu, Chromebook, or similar:

`$ sudo apt install qtcreator`


This article doesn't utilize the Qt Creator IDE, but it's an easy way to get everything you need installed, and for complex C++ projects (including those with a GUI), it's an essential tool to have. On macOS or Windows, follow the [installation instructions](https://www.qt.io/product/development-tools) on Qt's website.

## Set up includes and namespace

C++'s core language is minimal. Even a simple application requires the use of additional libraries. This application uses [iostream](http://www.cplusplus.com/reference/iostream/) to gain access to the `cout`

and `cin`

keywords.

Also, ensure that the program uses the `std`

namespace:

```
#include <iostream>
#include <stdlib.h> // srand
using namespace std;
```


This isn't strictly necessary, but without setting the namespace to `std`

, all keywords from the iostream library require a namespace prefix. For instance, instead of writing `cout`

, I would have to write `std::cout`

.

Statements in C++ terminate with a semicolon.

## Create a function

Every C++ application requires at least one function. The primary function of a C++ application must be called `main`

, and it must return an integer (`int`

), which corresponds to the [POSIX](https://opensource.com/article/19/7/what-posix-richard-stallman-explains) expectation that a process returns 0 upon success and something else upon failure. You create a new function by providing its return type and then its name:

```
int main() {
// code goes here
}
```


## Implement program logic

The game code must first produce a random number for the player to guess. You do this in C++ by establishing a *seed* for pseudo-random number generation. A simple seed is the current time. Once the seed starts, you retrieve a number between 1 and 100 by calling the `rand`

function with an upper constraint of 100. This generates a random number from 0 to 99, so add 1 to whatever number is chosen and assign the result to a variable called `number`

. You must also declare a variable to hold the player's guess. For clarity, I'm calling this variable `guess`

.

This sample code also includes a debug statement that tells you exactly what the random number is. This isn't very good for a guessing game, but it makes testing a lot faster. Later, you can remove the line or just comment it out by prefacing it with `//`

:

```
srand (time(NULL));
int number = rand() % 100+1;
int guess = 0;
cout << number << endl; //debug
```


## Add do-while and if statements

A `do-while`

statement in C++ starts with the keyword `do`

and encloses everything that you want C++ to do in braces. Close the statement with the `while`

keyword followed by the condition that must be met (in parentheses):

```
do {
// code here
} while ( number != guess );
```


The game code occurs within an `if`

statement with an `else if`

and `else`

statements to provide the player with hints.

First, prompt the player for a guess with a `cout`

statement. The `cout`

function prints output onto `stdout`

. Because the `cout`

statement isn't appended with the `endl`

(endline) function, no linebreak occurs. Immediately following this `cout`

statement, tell C++ to wait for input by using the `cin`

function. As you might surmise, `cin`

waits for input from `stdin`

.

Next, the program enters the `if`

control statement. If the player's guess is greater than the pseudo-random number contained in the `number`

variable, then the program prints out a hint followed by a newline character. This breaks the `if`

statement, but C++ is still trapped within the `do-while`

loop because its condition (the `number`

variable being equal to `guess`

) has not yet been met.

If the player's guess is less than the pseudo-random number contained in the `number`

variable, then the program prints out a hint followed by a newline character. This again breaks the `if`

statement, but the program remains trapped within the `do-while`

loop.

When `guess`

is equal to `number`

, the key condition is finally met, the `else`

statement is triggered, the `do-while`

loop ends, and the application ends:

```
do {
cout << "Guess a number between 1 and 100: ";
cin >> guess;
if ( guess > number) { cout << "Too high.\n" << endl; }
else if ( guess < number ) { cout << "Too low.\n" << endl; }
else {
cout << "That's right!\n" << endl;
exit(0);
} // fi
} while ( number != guess );
return 0;
} // main
```


## Building the code and playing the game

You can build your application with GCC:

`$ g++ -o guess.bin guess.cpp`


Run the binary to try it out:

```
$ ./guess.bin
74
Guess a number between 1 and 100: 76
Too high.
Guess a number between 1 and 100: 1
Too low.
Guess a number between 1 and 100: 74
That's right!
```


Success!

## Give C++ a try

The C++ language is complex. Writing C++ applications for terminals can teach you a lot about data types, memory management, and code linking. Try writing a useful utility in C++ and see what you can discover!

## Comments are closed.