Computer as player

I was wondering how to make a guessing game where the computer has to guess the secret number that the programmer comes up with. Obviously the other way around is simple but I am not sure how to make the computer be the player. Here is my implementation of it...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

const int SECRET_NUMBER=54;

int main()
{
	int compGuess;

	cout << "Enter guess: ";
	compGuess=(rand()+time(0))%100;
	cout << compGuess;

	while(compGuess!=SECRET_NUMBER)
	{
		if(compGuess>SECRET_NUMBER)
			cout << "That number is too high. Guess again: ";
		else
			cout << "That number is too low. Guess again: ";

		compGuess=(rand()+time(0))%100;
	}

	cout << "The computer won!" << endl;

	return 0;
}
You can use rand() to get a random number.

http://www.cplusplus.com/reference/clibrary/cstdlib/rand/
I fixed the code up a bit so here is the new version that seems to be working

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>

using namespace std;

const int SECRET_NUMBER=54;

int main()
{
	int compGuess;
	int temp;

	cout << "Enter guess: ";
	compGuess=(rand()+time(0))%100;
	temp=compGuess;
	cout << compGuess << endl;

	while(compGuess!=SECRET_NUMBER)
	{
		if(compGuess>SECRET_NUMBER)
		{
			cout << "That number is too high. Guess again: ";
			compGuess=(rand()+time(0))%100;
			while(compGuess>=temp)
				compGuess=(rand()+time(0))%100;
		}
		else
		{
			cout << "That number is too low. Guess again: ";
			compGuess=(rand()+time(0))%100;
			while(compGuess<=temp)
				compGuess=(rand()+time(0))%100;
		}

		cout << compGuess << endl;
		temp=compGuess;
	}

	cout << "The computer won!" << endl;

	return 0;
}
Make that your first version, then look to see how you can make the computer a bit smarter with its guesses.

For example, if you were told that 59 was too high, would you go on to guess more numbers in the range 60-99?

Andy

P.S. If you record how many guess the computer (typically) requires, you could compare your mark #1 algoithm with your new ones.
Last edited on
if you were told that 59 was too high, would you go on to guess more numbers in the range 60-99?

Yes that's what my program is missing.. it is only checking adjacent guesses so I see what you're saying. I am going to work on that part now.
Topic archived. No new replies allowed.