您的位置:首页 > 编程语言 > C语言/C++

C++一个猜数游戏程序

2010-12-03 22:29 441 查看
// diceGame.cpp : 定义控制台应用程序的入口点。
//****************************************************************
//diceGame.cpp
//功能:一个猜数游戏程序,主要用来演示选择语句和循环语句的使用
//****************************************************************

#include "stdafx.h"

#include <iostream>  //使用cin,cout,endl
#include <cstdlib>   //rand() srand(seed)
#include <ctime>     //seed=time() ,srand(seed)

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
int randNum1,randNum2,randNum3;   //用于存放3个椭机数
int rsum;
int count;
bool flag;
int n;
char c;
//game note:
cout<<"here will be an exciting game ^_^ "<<endl;
cout<<"There are three dice casting in a black box.";
cout<<"and each face of one dice shows points from 1 to 6,";
cout<<" please guess the sum of the three dice! "<<endl;
cout<<" Note that you have three times to guess at most."<<endl;

flag=true;
while(flag)
{
cout<<"Now the game begin!!!"<<endl;
rsum=0;
srand((unsigned)time(NULL));  //time函数获取系统时间
//srand函数设置道生椭机数的种子
randNum1=rand()%6+1;
randNum2=rand()%6+1;
randNum3=rand()%6+1;
rsum=randNum1+randNum2+randNum3;

//gamer 最多有3次机会输入答案
for(count=0;count<3;count++)
{
cout<<"Please enter the sum you guess:";
cin>>n;
if(n<rsum && count<2)
{
cout<<"Too small number! Enter bigger one!"<<endl;
}
else if(n>rsum && count<2)
{
cout<<"Too big number! Enter smaller one!"<<endl;
}
else if(n==rsum)
{
cout<<"How smart you are! YOU WIN!!!"<<endl;
cout<<"The points one the three dice are:"<<endl;
cout<<randNum1<<"  "<<randNum2<<"  "<<randNum3<<endl;
break;
}
}
if(count==3)
{
cout<<endl;
cout<<"Sorry,You lose!"<<endl;
cout<<randNum1<<"  "<<randNum2<<"  "<<randNum3<<endl;
cout<<"sum="<<rsum<<endl;
}
//询问是否再玩一局
cout<<endl<<"Do you want to play the game again?"<<endl;
cout<<"Please enter Y or y to play again,enter other letter to exit the game:"<<endl;
cin>>c;
if(c=='Y' || c=='y')
{
flag=true;
}
else
{
flag=false;
}
}

//暂停操作
char str;
std::cin>>str;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息