[2006-05-06]せっかくパソコンを使って、デジタルゲームを作ったのに



/*

* Guess number game
* Program: David Zhang ( Feb - 03 - 2008 )
* E-mail: [email protected]
* 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
"; 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; }