昨天因为去看望小朋友了所以没时间写,今天先把我们前天写的竞猜小游戏优化一下,让竞猜能够循环进行,并在你需要的时候退出,先看看修改前的代码:
void guess()
{
system("cls");
srand(time(NULL));
int degree, result, n;
cout << "=======Simple竞猜=======" << endl;
cout << "输入1 : 简单难度(1~5)"<< endl;
cout << "输入2 : 困难难度(1~20)"<< endl;
cout << "输入3 : 地狱难度(1~100)"<< endl;
cout << "========================" << endl;
cout << "你的选择是:";
cin >> degree;
switch (degree)
{
case 1:
result = 1 + rand() % 5;
cout << "你猜的数字是:";
cin >> n;
if (result == n)
cout << "bingo!" << endl;
else
cout << "笨蛋!" << endl;
break;
case 2:
result = 1 + rand() % 20;
cout << "你猜的数字是:";
cin >> n;
if (result == n)
cout << "bingo!" << endl;
else
cout << "笨蛋!" << endl;
break;
case 3:
result = 1 + rand() % 100;
cout << "你猜的数字是:";
cin >> n;
if (result == n)
cout << "bingo!" << endl;
else
cout << "笨蛋!" << endl;
break;
}
}
想要让竞猜循环进行,很自然的想到嵌套一个while循环在switch外面,类似于我们简单计算器的外壳。while循环的条件表达式用一个初值为1的变量表示,当我们选择为退出的时候,将这个变量赋值为0,以达到退出循环的目的。
修改后的函数如下:
void guess()
{
int s=1;
while (s)
{
system("cls");
srand(time(NULL));
int degree, result, n;
cout << "=======Simple竞猜=======" << endl;
cout << "输入1 : 简单难度(1~5)" << endl;
cout << "输入2 : 困难难度(1~20)" << endl;
cout << "输入3 : 地狱难度(1~100)" << endl;
cout << "输入4 : 退出竞猜" << endl;
cout << "========================" << endl;
cout << "你的选择是:";
cin >> degree;
switch (degree)
{
case 1:
result = 1 + rand() % 5;
cout << "你猜的数字是:";
cin >> n;
if (result == n)
cout << "bingo!" << endl;
else
cout << "笨蛋!" << endl;
system("pause");
break;
case 2:
result = 1 + rand() % 20;
cout << "你猜的数字是:";
cin >> n;
if (result == n)
cout << "bingo!" << endl;
else
cout << "笨蛋!" << endl;
system("pause");
break;
case 3:
result = 1 + rand() % 100;
cout << "你猜的数字是:";
cin >> n;
if (result == n)
cout << "bingo!" << endl;
else
cout << "笨蛋!" << endl;
system("pause");
break;
case 4:
s = 0;
break;
}
}
}
需要注意的是,在加入循环之后,我们需要在每次竞猜结束后加入一个system(“pause”)来查看我们是否猜中,否则在输入猜的数字之后将会立刻清屏并进行下一次竞猜。之前我们由于不进行循环,所以每次猜完数字之后都会由主函数里while循环的system(“pause”)帮我们冻结屏幕,这个区别需要大家注意一下。
光是干巴巴的竞猜有点乏味,那就必须加入一些能调动人激情的东西了,那就是:战绩!我们引入两个变量,一个记录竞猜的总次数,一个记录竞猜猜对的次数,并随时显示我们的战绩、胜率。
胜率就是:胜利的次数 / 总次数,这很易于理解,至于以往战绩查询,比如每一次竞猜实际答案和你所输入的答案,这涉及到数组存储,以后再讲,今天只实现胜率显示。
我们只需要额外定义两个变量,一个变量success,一个变量count,count在每次竞猜结束后都会自增一次,用count++实现。而success则只在猜中的时候自增,在每次竞猜循环结束后对胜率进行计算并显示。
具体实现代码在明天会给出,相信大家不用我说也能写出来。
明天是日记的第九篇,九是一个很重要的数字,是数字的极大之数。所以明天会讲c++一个相当重要的东西:类与对象。