C/C++教程

C++实现猜数游戏(源代码)

本文主要是介绍C++实现猜数游戏(源代码),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
#include <bits/stdc++.h>
using namespace std;

void Start();
void GetResults();

int i, j, life, maxrand;
char c;

void Start()
{
  i = 0;
  j = 0;
  life = 0;
  maxrand = 6;

  cout << "选一个等级:\n"; // the user has to select a difficutly level
  cout << "1 : 简单 (0-20)\n";
  cout << "2 : 中等 (0-40)\n";
  cout << "3 : 困难 (0-60)\n";
  cout << "来选一个吧!!!\n";
  c = 30;

  cin >> c;                   // read the user's choice
  cout << "\n";

  switch (c)
  {
    case '1':
      maxrand = 20;  // the random number will be between 0 and maxrand
      break;
    case '2':
      maxrand = 40;
      break;
    case '3':
      maxrand = 60;
      break;
    default:
      exit(0);
      break;
  }

  life = 5;         // number of lifes of the player
  srand((unsigned)time(NULL)); // init Rand() function
  j = rand() % maxrand;  // j get a random value between 0 and maxrand

  GetResults();
}

void GetResults()
{
  if (life <= 0)   // if player has no more life then he loses
  {
    cout << "你输了!!!\n\n";
    Start();
  }

  cout << "猜一个数字: \n";
  cin >> i;

  if((i>maxrand) || (i<0))   // if the user number isn't correct, restart
  {
    cout << "错误:这个数不能是0和 \n" << maxrand;
    GetResults();
  }

  if(i == j)
  {
    cout << "你赢了!!!\n\n"; // the user found the secret number
    Start();
  }
  else if(i>j)
  {
    cout << "大了!\n";
    life = life - 1;
    cout << "血量: " << life << "\n\n";
    GetResults();
  }
  else if(i<j)
  {
    cout << "小了!\n";
    life = life - 1;
    cout << "血量: " << life << "\n\n";
    GetResults();
  }
}

int main()
{
  cout << "**<< 猜数游戏 >>**\n";
  cout << "这个游戏会让你猜一个数字。\n";
  cout << "我们只能告诉你你猜的数比电脑想的数字是大了还是\n";
  cout << "小了,一共三个等级,五滴血。\n\n";
  Start();
  return 0;
}
这篇关于C++实现猜数游戏(源代码)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!