Chinaunix首页 | 论坛 | 博客
  • 博客访问: 26879
  • 博文数量: 38
  • 博客积分: 2010
  • 博客等级: 大尉
  • 技术积分: 390
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-29 22:54
文章分类

全部博文(38)

文章存档

2010年(38)

我的朋友
最近访客

分类: C/C++

2010-05-29 23:03:15

/*

* 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
#include
#include

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;
}

阅读(158) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~