[2006-05-06]难得这么多时间用电脑,编了一个猜数字游戏

猜数字游戏程序
本文介绍了一个简单的猜数字游戏程序,采用C++语言实现。程序能够自动生成四位不同的数字供玩家猜测,并通过A和B的形式反馈猜测结果,帮助玩家逐步接近正确答案。

/*

* Guess number game
* Program: David Zhang ( Feb - 03 - 2008 )
* E-mail: Crispgm@gmail.com
* WARNING:
* This source file is distributed under GNU General Public Licence
* PLEASE READ IT CAREFULLY
*/

#include <cstdlib>
#include <ctime>
#include <iostream>

using namespace std;

void Generate( int *n );
bool IsExist ( int x, int *n );
void Compare ( int x, int *n, int index );

int main()
{
/* FOUR digit array generate by program */
int n[4] = { 0 };
/* player input this */
int in;
/* program use compare to compare with input */
int compare;
enum status{ WON, LOST, CONTINUE };

status gameStatus = CONTINUE;

cout << "Guess number V0.2\n";

Generate( n );
compare = n[0] * 1000 + n[1] * 100 + n[2] * 10 + n[3];

for( int i = 0; i < 8; i++ )
{
cout << endl << "Input what you guess: ";
cin >> in;
if( compare == in )
{
gameStatus = WON;
break;
}
Compare( in, n, i );
}

if( gameStatus == WON )
cout << "You won!" << endl;
else
cout << "You lost!" << endl;

return 0;
}

void Generate( int *n )
/* generate an array n */
{
int x, i = 0;
srand(time(NULL));

while( i < 4 )
{
x = rand() % 9 + 1;
if( !IsExist( x, n ) )
n[ i++ ] = x;
}

}

bool IsExist( int x, int *n )
/* This function is test where x is exist in array of n */
{

for( int i = 0; i < 4; i++ )
if( x == n[i] )
return true;

return false;
}

void Compare( int x, int *n, int index )
{
int A = 0, B = 0;
int c[4], temp;
c[0] = (int)( x/1000 );
temp = x - c[0] * 1000;
c[1] = (int)( temp/100 );
temp = temp - c[1] * 100;
c[2] = (int)( temp/10 );
c[3] = temp - c[2] * 10;

for( int i = 0; i < 4; i++ )
{
for( int j = 0; j < 4; j++ )
{
if( n[i] == c[j] ){
if( i == j )
A++;
else
B++;
}
}
}
cout << index + 1 << " "
<< c[0] << c[1] << c[2] << c[3]
<< " " << A << "A"
<< B << "B"
<< endl;

return;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值