/*
* 功 能:猜數字的遊戲
* 編譯環境:windows2000 + Dev-c++ 4.9
* 作 者:jhkdiy
* 電子郵件:[email protected]
* 備 注:無意中看到《Beginning C++ game programming》一書,隨便瀏覽了一下,
* 覺得這個遊戲有點意思,所以自己完善了下。初學者用來學習一下語法
* 和提高一下興趣還是很有意思的。該程序有BUG,大家找出來,
* 不是語法錯誤哦!!思考一下!
*/
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main(int argc, char *argv[])
{
//產生隨機數種子
srand(time(0));
int theNumber = rand() % 100 + 1; //隨機數控制在1-100之間
int tries = 0, //用戶嘗試的次數
guess; //用戶輸入的數字
char bPlayAgain; //是否繼續遊戲
cout << "/tWelcome to guess my number/n/n";
do
{
//接受用戶的輸入
cout << "Enter a guess: ";
cin >> guess;
++tries;
//如果輸入的數字大於產生的隨機數
if( guess > theNumber )
{
cout<<"Too high!/n/n";
}
//如果輸入的數字小於產生的隨機數
if( guess < theNumber )
{
cout << "Too low!/n/n";
}
//猜對了···
if( guess == theNumber )
{
cout << "/n/n/tVery good! you get it!"
<< "/tThe number is: " << theNumber << endl;
cout << "/n/n/tyou try " << tries << " times!" << endl;
//是否繼續遊戲
cout << "/n/nDo you want to play again?(y/n)";
cin >> bPlayAgain;
if( bPlayAgain == 'y' || bPlayAgain == 'Y')
{
//清屏後繼續遊戲
system("cls");
continue;
}
else if( bPlayAgain == 'n' || bPlayAgain == 'N')
{
cout << "/nSee you next time, bye!/n";
break;
}
else
{
cout << "/nEnter a wrong choice! program will exit!/n";
break;
}
}
}while(true);
//退出程序
system("pause");
return EXIT_SUCCESS;
}