Friday, 14 June 2013

C++ Basic Game

A basic C++ game to generate a random number between 1 and 100

In this simple game, the program generates a number between 1 and 100. The user is then prompted to make a guess of the generated number.
If the guess is higher than the generated number, then the program informs the user that the guess is higher.
If the guess is lower then the generated number, then the program informs the user that the guess is lower.
If the guess is correct, then the user wins.
The user can only make a maximum of 6 guesses after which the program exits.

One can then adjust the game to suit their needs.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main ()
{
int secret, coin, count = 0;
int i;
//Makes a call to the Random function
srand(time(0));
//Generates a random number between 1 and 100
secret = (rand() % 100) + 1;
i = 0;
while (i < 10000) {
srand(time(0));
coin = rand() % 2;
if (coin == 0)
count = count + 1;
i = i + 1;
}
//Initializing variables to use.
int secretn;
int guessn = 0;
int maxguesses = 0;
cout << "A secret number between 1-100 has been generated...\n"<<endl;
while (guessn < 6)
{
cout << "Please enter your guess?\n";
cin >> secretn;
if (secretn == secret)
{
cout <<"Congratulations!!!\nYou guessed right.\nNumber of guesses="<< guessn<<endl;
guessn = 6;
maxguesses = 1;
system ("pause");
}
else if (secretn >= secret)
{
cout << "Your guess is higher than the generated number...\n";
guessn++;
}
else if ((secretn <= secret))
{
cout << "Your guess is lower than the generated number...\n";
guessn++;
}
}
if ((guessn == 6) && (maxguesses == 0))
{
cout<<endl;
cout << "Too many guesses!!!\nThe game will exit now,please try again."<<endl;
system("pause");
}
return 0;
}

No comments:

Post a Comment