wm: mmind

ref: 28c05ee3266fbdac9c6a89457ee62f6b21f93721
dir: /game.cpp/

View raw version
/*
	Mastermind impl.

	todo:
	fix main()
	ask for "Do you dare to leave this great game?"
	check harder for length differs in either main or compere or getguess
	write proper comments and strings (printrules?)
	check digit, etc? errors
	
*/

#include <iostream>

using namespace std;

// io functions
void printrules();
ulong getlen();
ulong getguess();
void compere(long goal, long guess);

// aux functions
uint length(ulong n);
ulong gengoal(ulong n);
int digit(long number, uint index);

void printrules()
{
	cout << "Hi," << endl;
}

ulong getlen()
{
	ulong len;
	/* shouldn't be longer than sizeof(len) */
	cout << "how long? " << endl;
	cin >> len;
	if(len < 1 || len > 19)
	{
		cerr << "Sorry, please enter a 0 < x < 20 number" << endl;
		len = getlen();
	}
	return len;
}

ulong getguess()
{
	/* "sang bozorg neshane nazadan ast" */
	char guess[512];
	int i = 0;
	ulong temp = 0;
	cout << "guess? " << endl;
	cin.getline(guess, 512);
	while(guess[i] != 0)
	{
		/* see if it's either a number or space, SCREAM otherwise! */
		if((guess[i] >= '0') && (guess[i] <= '9'))
		{
			/* because	we can't put ascii into int directly */
			temp *= 10;
			temp += (guess[i] - '0');
		}
		else if(guess[i] != ' ')
		{
			cerr << "That's not a number." << endl;
			return getguess();
		}
		i++;
	}
	return temp;
}

uint length(ulong n)
{
	ulong t = 0;
	while(n > 0)
	{
		n /= 10;
		t++;
	}
	return t;
}

/* generates a goal, n digits long */
ulong gengoal(ulong n)
{
	ulong num = 0;
	/* it's technically legal, but
	we get a int that's shorter than n */
	do
        num = rand() % 10;
    while (num == 0);

	/* we have already generated one digit */
	while(n > 1)
	{
		num *= 10;
		num += rand() % 10;
		n--;
	}
	return num;
}

/* we could also use arrays for this,
	alas, that would a can of worms 
	digit(number, index) = number[index] */
int digit(long number, uint index)
{
	if((index > length(number)) || (index < 0))
		return -1;

	int i = 0, j;
	while(i <= index)
	{
		j = number % 10;
		number /= 10;
		i++;
	}
	return j;
}

void compere(ulong goal, ulong guess)
{
	int i = length(goal) - 1;

	while(i+1 > 0)
	{
		if(digit(goal, i) == digit(guess, i))
			cout << '#';
		else
			cout << 'X';
		i--;
	}
	cout <<	endl;
}

int main()
{
	int lives, len, flag = 1;
	ulong goal, guess;
	printrules();
	len = getlen();
	/* you may try all digits in 9+, we don't want that*/
	(len > 9) ? lives = 9 : lives = len;
	goal = gengoal(len);
	// cout << "psst. here's a hint: goal = " << goal << endl;
	/* flush the buffer */
	cin.ignore();
	while(lives > 0 && flag)
	{
		guess = getguess();
		compere(goal, guess);
		if(goal != guess)
			lives--;
		else
		{
			cout << "You win, d(o.o)" << endl;
			flag = 0;
		}
	}
	if(lives == 0 && flag)
		cout << "you lose" << endl;
}