游戏开始界面
输入错误代码
游戏次数用尽
代码总结:
比较简单和粗糙
定义了一个random用来生成随机数,方便了很多
用了Game类来进行游戏内循环,有点长,但个人觉得这样可以让代码可读性提高很多,比较有层次 主要是用类可以写很长看着爽:)
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
#define random(a,b) (rand()%(b-a)+a)
class Game
{
public:
int number, simple, user, flag;
int gametime;
Game();
~Game();
void start();
void gaming(int simple);
};
Game::Game()//利用构造器在类被引用时就生成一个随机数
{
number = random(0, 100);
}
Game::~Game()//析构器与构造器对应
{
cout << "拜拜~" << endl;
}
void Game::start()//菜单界面
{
cout << "猜数字~" << endl;
cout << "会输出一个0-100的数,来猜猜吧~" << endl;
cout << "----------------------------------------" << endl;
cout << "1.输入1开始游戏~" << '\n' << "2.输入2退出游戏" << endl;
cout << "----------------------------------------" << endl;
cin >> simple;
}
void Game::gaming(int simple)//游戏本体
{
if (simple == 1)
{
cout << "你觉得这个数是多少?" << endl;
cin >> user;
if (user > number)
{
cout << "这个数大了" << endl;
gametime--;
cout << "现在还有" << gametime << "次机会" << endl;
cout << "-----------------------------------" << endl;
}
if (user < number)
{
cout << "这个数小了" << endl;
gametime--;
cout << "现在还有" << gametime << "次机会" << endl;
cout << "-----------------------------------" << endl;
}
if (user == number)
{
cout << "猜对了!" << endl;
cout << "-----------------------------------" << endl;
flag = 1;
}
if (gametime == 0)
{
flag = 1;
cout << "游戏次数用尽~" << endl;
}
}
if (simple != 1)
{
cout << "输入正确的数~" << endl;
cout << "---------------------------------------" << endl;
start();
}
}
int main()
{
Game game;
game.gametime = 10;//定义游戏次数
game.flag = 0;
srand((int)time(0));
game.start();
if (game.simple == 2)
return 0;
else
{
while (game.flag != 1)
game.gaming(game.simple);
}
cout << "本次游戏结束" << endl;
return 0;
}