Guess the random number game - c++

I am making a number guessing game and I do not know how to incorporate a certain number of guesses the users has to get the correct answer. I want the user to have only 3 guesses to guess the number but after 3 guesses, they lose if they do NOT get it correct. Here is my code below:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand ( time(NULL) );
cout << "Select a difficulty: 1) Easy, 2) Medium, 3) Hard " << endl;
int userlevel;
int userinput;
int randomNumber;
cin >> userlevel;
{
if (userlevel==1)
cout << "You chose Easy: 3 chances to guess correctly" << endl;
cout << "Pick a number between 1 and 10: " << endl;
cin >> userinput;
randomNumber = rand() % 10 + 1;
if (randomNumber==userinput)
cout << "You, guessed correctly! You win!" << endl;
else
cout << "I'm sorry, that is not correct. You lose." << endl;
}
{
if (userlevel==2)
cout << "You chose Medium: 4 chanaces to guess correctly" << endl;
cout << "Pick a number between 1 and 50: " << endl;
cin >> userinput;
randomNumber = rand() % 50 + 1;
if (randomNumber==userinput)
cout << "You, guessed correctly! You win!" << endl;
else
cout << "I'm sorry, that is not correct. You lose." << endl;
}
{
if (userlevel==3)
cout << "You chose Hard: 5 chances to guess correctly" << endl;
cout << "Pick a number between 1 and 100: " << endl;
cin >> userinput;
randomNumber = rand() % 100 + 1;
if (randomNumber==userinput)
cout << "You, guessed correctly! You win!" << endl;
else
cout << "I'm sorry, that is not correct. You lose." << endl;
}
return 0;
}

You should look into while-loops. It would be used like this:
int main() {
//...everything above this in yours is good
int Number_to_guess = (rand() % 10 + 1);
int NChances = userlevel + 2;
cout << "You have " << NChances << " chances to guess right.\n";
while (NChances != 0)
{
cout << "Guess: ";
cin >> userinput;
if (userinput == Number_to_Guess) {
cout << "You win! Congrats!\n";
break; // this will break out of the while-loop
}
NChances--; // this will count down the chances left
}
if (NChances == 0) {
cout << "Sorry, you lose. Try again next time!\n";
}
return 0;
}

The main think you're missing here is a loop around the guess limit. So after you figure out what level they are, you can say something like the following pseudocode:
While (counter <= 3)
*Your If Statements*
counter = counter +1
Make sure that in the if statement where they guessed the number right, you break them out of the loop early.
Finally, it might make more sense to guess a number before you enter the loop. So, something like they pick the difficulty, the random number is picked depending on what they say, and then the loop begins. The way it is now, a new random number will be created each time through the loop. I'm not sure if that's intended.

Related

How create a guessing game with letters. For example I need to guess a letter from the word fallout. Which functions are useful

I am creating a guessing game. I need to ask the user to input a letter from a word like fallout. The have that letter they had inputted be correct or incorrect. I am using functions like srand(time(NULL)), rand(), psw.length. once the user inputs a letter and if they are wrong a life is deducted live--.
If they get it right they can move on to the next question with a full 5 lives. I don't know what functions I am missing if I need an array etc.
I have tried applying the rand() && psw.length together in order to at least try to randomize the letter choice so that the user might have a chance to guess the random letter from the word "fallout" but to no avail.
I have made some progress I started with the numerical portion of the code instead of focusing on the whole thing at once. Then now I have to start on the alphabetical portion of the code itself I am organizing my thoughts to simpler terms.
Now onto the alphabetical functions of the code....I now need to randomize letters for the user to answer with the correct letter of the word using functions.
I am trying to make the second answer2 = rand() % word2.length function work could anyone help me here it automatically runs the code giving a positive score to the user....
include <iostream>
#include <string>
#include <time.h>
#include <cstdlib>
using namespace std;
int lives = 3;
int guess;
int guess2;
int answer = 0;
int answer2 = 0;
int i;
int score = 0;
char letter, letter2;
string word = "fallout";
string word2 = "psw";
int main()
{
srand(time(NULL));
cout << "Welcome to the guessing game!" << endl;
cout << "*****************************" << endl;
system("PAUSE");
system("cls");
answer = rand() % 2 + 1;
lives = 3;
do {
cout << "What is a number between 1 and 2? Can you guess it in\n" << endl << lives << endl << "tries?" << endl;
cin >> guess;
if (guess == answer)
{
cout << "You won!!" << endl;
score++;
}
else if (lives == 0)
{
cout << "Your score" << endl << score;
system("PAUSE");
return 0;
}
else
{
cout << "Incorrect try again!" << endl;
lives--;
system("PAUSE");
system("cls");
}
} while (guess != answer);
cout << "You won your score is" << score << endl;
system("PAUSE");
system("cls");
answer = rand() % 3 + 1;
lives = 3;
do {
cout << "What is a number between 1 and 3? Can you guess it in" << endl << lives << "tries?" << endl;
cin >> guess;
if (guess == answer)
{
cout << "You won!!" << endl;
score++;
}
else if (lives == 0)
{
cout << "Your score" << endl << score;
system("PAUSE");
return 0;
}
else
{
cout << "Incorrect try again!" << endl;
lives--;
system("Pause");
system("cls");
}
} while (guess != answer);
cout << "You won your score is" << score << endl;
system("PAUSE");
system("cls");
answer = rand() % 5 + 1;
lives = 3;
do {
cout << "What is a number between 1 and 5? Can you guess it in\n" << endl << lives << "tries?" << endl;
cin >> guess;
if (guess == answer)
{
cout << "You won!!" << endl;
score++;
}
else if (lives == 0)
{
cout << "Your score" << endl << score;
system("PAUSE");
return 0;
}
else
{
cout << "Incorrect try again!" << endl;
lives--;
system("cls");
}
} while (guess != answer);
cout << "You won your score is " << score << endl;
system("PAUSE");
system("cls");
answer = rand() % word.length();
lives = 3;
do
{
cout << "Select the correct letter in the word '" << word << "': ";
cin >> guess;
if (guess == letter)
{
cout << "You Won!" << endl;
score++;
}
else if (lives == 0)
{
cout << "The correct answer is:" << endl;
cout << word[answer];
}
else
{
cout << "Incorrect Try Again" <<
lives--;
}
} while (guess != letter);
cout << "You won your score is " << score << endl;
system("PAUSE");
system("cls");
How can I make this code run well can anybody help me I just need advice on this function here... It keep giving the user a score++ automatically. Is their a simple fix for this. I am a rookie so if there is a basic trick here it would help!
answer2 = rand() % word2.length();
lives = 3;
do
{
cout << "Select the correct letter in the word '" << word2 << "': ";
cin >> guess2;
if (guess2 == letter2)
{
cout << "You Won!" << endl;
score++;
}
else if (lives == 0)
{
cout << "The correct answer is:" << endl;
cout << word2[answer2];
}
else
{
cout << "Incorrect Try Again" <<
lives--;
}
} while (guess2 != letter2);
cout << "You won your score is " << score << endl;
system("PAUSE");
system("CLS");
}
First of all, in C++ you have some different ways to randomize a value. rand() highly not recommended.
From cppreference:
There are no guarantees as to the quality of the random sequence produced. In the past, some implementations of rand() have had serious shortcomings in the randomness, distribution and period of the sequence produced (in one well-known example, the low-order bit simply alternated between 1 and 0 between calls). rand() is not recommended for serious random-number generation needs, like cryptography.
Instead, you can use:
#include <random>
int main() {
/*...*/
// Seed with a real random value, if available
std::random_device r;
// Choose a random mean between 1 and 6
std::default_random_engine e1(r());
std::uniform_int_distribution<int> uniform_dist(1, 7);
answer = uniform_dist(e1);
/*...*/
return 0;
}
Read more about random: https://en.cppreference.com/w/cpp/numeric/random
For loop - Condition problem: for (int i = 0; i < guess; i++) - The condition here seems wrong. Why does this loop runs until i is bigger then the user guess? I think a better way for your target is to use while loop, until the user have no lives:
int lives = 5;
size_t guess_number = 1;
/*...*/
while (lives) {
cout << "Guess" << guess_number++ << endl;
/*...*/
}
Stop the loop: Whenever the user successfully guess the letter (or the letter's place in the word), you might considering random a new letter, a new word, or just stop the game and exit the loop (with break).
The word FALLOUT: Currently, in your code, the word fallout ia a variable name, and not a variable content. start with replacing this name to something like word_to_guess, and put the value fallout into it.
string fallout;
to:
string word_to_guess = "fallout";
Now that you have done it, you can make you code more generic to another words, by choosing a random number between 1 to word_to_guess.size():
std::uniform_int_distribution<int> uniform_dist(1, word_to_guess.size());
Now you want to convert user's guess and computer's guess to letters:
/**
* guess >= 1 - The user have to guess a letter from the beginning of the word (and not before it).
* guess <= word_to_guess.size() - The user can't guess a letter that not exists in the word.
* word_to_guess[guess - 1] == word_to_guess[answer - 1] - Compare the user's letter to the computer's letter
*
* word_to_guess[answer - 1] - You might consider to replace this with word_to_guess[answer], and just random
* a number from 0 to word_to_guess.size() - 1
*/
if (guess >= 1 && guess <= word_to_guess.size() && word_to_guess[guess - 1] == word_to_guess[answer - 1]) {
cout << "You Won" << endl;
break; // Or random new letter/word etc...
}

Random generated number result doesn't match with the user input

I'm having a problem with the random generated number result not matching with the user input and it only outputs the first statements instead of falling to else if the user guessed wrong.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
int bank = 10;
int heads = 0;
int tails = 1;
char response;
string headsTails;
int coinToss = rand() % 2;
srand(static_cast<int>(time(0)));
cout << "Welcome to the coin flip game. It cost a dollar to play. " << endl;
cout << "If you guess correctly you will win $2.00 dollars " << endl;
cout << "Do you want to play? (Y/N) " << endl;
cin >> response;
while (toupper(response) == 'Y')
{
cout << "Your bank is $" << bank << " dollars." << endl;
cout << "Enter head or tails (H/T)" << endl;
cin >> response;
coinToss = rand() % 2;
headsTails = coinToss ? "Heads" : "Tails";
if (coinToss == heads || coinToss == tails)
{
cout << "Winner! The coin flip came up " << headsTails << endl;
cout << "Would you like to play again? (Y/N) " << endl;
cin >> response;
bank += 2;
}
else
{
cout << "Sorry, you lose. The coin flip came up " << headsTails <<
endl;
cout << "Would you like to play again? (Y/N) " << endl;
cin >> response;
bank -= 1;
}
}
cout << "Thanks for playing! Your bank is " << bank << endl;
cout << "Please come again! " << endl;
return 0;
}
if (coinToss == heads || coinToss == tails)
That condition is wrong, it will always evaluate to true since you set coinToss to 0 or 1 yourself.
You have to use the response variable you ask of the user, something like:
int guess = response == 'T' ? 1 : 0; // convert the user input to the same values used throughout the program.
if(guess == coinToss)
//won..
else
//lost..

How do i tell my app "stop running" after set amount rounds?

So i'm making a turn based dice game that's modeled after this game called "underground chinchiro" which was taken from an anime called "Kaiju". I need to set a limit to my program so that it only runs for a set number of rounds,
I'm only a beginner in coding so sorry for anything unusual you see in my code.
#include <iostream>
#include <string>
#include <time.h>
using namespace std;
void roll_3_dice(int &dice1, int &dice2, int &dice3)
{
dice1 = rand() % 6 + 1;
dice2 = rand() % 6 + 1;
dice3 = rand() % 6 + 1;
return;
}
int main()
{
int cash = 90000;
int wager;
int r;
//dealer's die
int dealer1;
int dealer2;
int dealer3;
// your die
int mdice1;
int mdice2;
int mdice3;
for (int i = 0; i < 10; i++)
{
cout << "Wager up boy!"<< endl;
cin >> wager;
while (wager < 100 || wager > 90000)
{
cout << "Minimum wager is 100; Maximum wager is 90000 ";
cin >> wager;
}
cout << "You wagered: " << wager << endl;
cout << "You have " << cash - wager << " remaining" << endl;
cash = cash - wager;
cout << endl;
cout << "Dealer will now roll the dice" << endl;
roll_3_dice(dealer1, dealer2, dealer3);
cout << "Dealer rolled the following: " << endl;
cout << dealer1 << "-" << dealer2 << "-" << dealer3 << endl;
cout << "It's your turn to roll the dice." << endl;
cout << endl;
cout << "Press any key to roll the dice" << endl;
cin >> r;
roll_3_dice(mdice1, mdice2, mdice3);
cout << "You rolled the following: " << endl;
cout << mdice1 << "-" << mdice2 << "-" << mdice3 << endl;
system ("pause");
}
}
Take a look at for loops. For loops will allow you to run your code for a set number iteration.
e.g. iterate over some code 7 times.
int number_of_iterations = 7;
for(int i = 0; i < number_of_iterations; i++) {
// Your code that you would like to iterate over goes here.
}
EDIT:
As has been specified by the OP (in comments below), the issue is appears to be with the program not stopping to receive input from the user through each iteration of the for loop.
This could be for a number of reasons. My best guess would be that the stdin buffer is not clear and that std::cin continues to read in from the buffer. This could be solver by calling cin.clear() before reading in your input.
is time to learn how to use constants...
define one doing
const int max_round = 5;
and the do a while so long round is <= than max_round
Your problem is pretty unclear. Edit your code, find the section where problems occurring and paste that part only.
like:
while(cin>>wager)
{
if(condition fails)
{
break;
}
}

Random Number Game

I'm making a small game in C++ where a user will type "roll" and the program should generate 5 numbers between 1-6. The objective of the game is to get all the numbers the same.
My problem I am having is fully understanding how to format the different algorithms need for a project like this and what type of different syntax's that allowed through the language.
I am a student learning this language and will appreciate any help anyone is willing to offer!
The code below is not finished in anyway and just wanted some extra advice!
Code:
// Random Number Game
// ***
// ***
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <vector>
using namespace std;
using std::cout;
using std::cin;
using std::endl;
using std::string;
int main()
{
// Intro Instruction
cout << "Welcome to Random Number game!\n";
cout << "The objective of this game to get all 5 dice the same number.\n";
// Variables
char roll;
int dice1, dice2, dice3, dice4, dice5;
cout << "To begin the game please type roll. ";
cin >> roll;
srand((unsigned)time(0));
// Stating Low and High Numbers (Dice numbers)
int lowerrange = 1;
int upperrange = 7;
upperrange = 6;
dice1 = rand() % 6;
dice2 = rand() % 6;
dice3 = rand() % 6;
dice4 = rand() % 6;
dice5 = rand() % 6;
if ((roll == 'roll') || (roll == 'Roll'))
{
cout << dice1;
cout << dice2;
cout << dice3;
cout << dice4;
cout << dice5;
}
system("pause");
return 0;
}
Here is a possible solution.
The idea is to use a loop to repeatedly asking from user to "roll" the dices, for testing purposes only I put 3 dices here, but you can extend to 5 dices.
I maintain a boolean variable that will be true if and only if all the dices has the same value, if that the case, the program will break out from loop, and will print a successful message.
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Intro Instruction
cout << "Welcome to Random Number game!\n";
cout << "The objective of this game to get all 5 dice the same number.\n";
string command;
int magic = 0;
do
{
cout << "To begin the game please type roll: ";
cin >> command;
if(command == "roll")
{
int dice1 = rand() % 6 + 1;
int dice2 = rand() % 6 + 1;
int dice3 = rand() % 6 + 1;
cout << "First Dice: " << dice1 << endl;
cout << "Second Dice: " << dice2 << endl;
cout << "Third Dice: " << dice3 << endl;
cout << "Which Dice do you want to keep? : (Enter 1, 2 or 3)" << endl;
int keep_dice;
cin >> keep_dice;
if(keep_dice == 1)
{
magic = dice1;
break;
}
else if(keep_dice == 2)
{
magic = dice2;
break;
}
else if(keep_dice == 3)
{
magic = dice3;
break;
}
}
}
while(true);
cout << "You choose the number: " << magic << ". Roll the other dices until you get for both this number." << endl;
do
{
cout << "Type roll: ";
cin >> command;
if(command == "roll")
{
int dice1 = rand() % 6 + 1;
int dice2 = rand() % 6 + 1;
cout << "First Dice: " << dice1 << endl;
cout << "Second Dice: " << dice2 << endl;
if(dice1 == magic && dice2 == magic)
{
break;
}
}
}
while(true);
cout << "You won !" << endl;
}
Alternative Solution:
My idea is to create a function that will accept two parameters: num_dice the remaining dices to be rolled if you have 5 dices that will be 4, if you have n dices this will be n-1 and so on.
The other parameter will be the lucky number that the user will choose (easy with an if or with switch statement)
You will then repeat that with the same logic within your function until you get your n-1 dices equal to lucky number.
Moreover, think that my code may need a bit alteration, so that the first roll of all dices will happen once and not repeatedly, and then with the function you will do the repeat "job".
To check if all the dices are the same, use the code below:
int magicValue = dice1;
cout << "You got:" << endl;
cout << "Dice 1: " << dice1 << endl;
cout << "Dice 2: " << dice2 << endl;
cout << "Dice 3: " << dice3 << endl;
cout << "Dice 4: " << dice4 << endl;
cout << "Dice 5: " << dice5 << endl;
if(dice2 == magicValue && dice3 == magicValue
&& dice4 == magicValue && dice5 == magicValue){
cout << "Congratulations! You Win!" << endl;
} else {
cout << "Sorry, try again next time!" << endl;
}
What this does is it sets magicValue to dice1 and checks if all other dice variables are equal. Not the fanciest way to do it, but I hope this helps you!
Since you have at the top ‘Using namespace std`
You don’t have to specify using std::cout or anything like that.
Also you can just assign upperrange to 6 right away.
Besides this jut put it in a loop if you want, add some more output so they know they can keep playing.

C++ only 2 loop iterations

I'm studying at university and we started programming in C++. I had some basic concepts about Java (variables, loops and more easy things) and I tried to practice on my own with Microsoft Visual Studio, but I had a problem, this is my code, is a program that tries to guess the number you are thinking of.
void main(){
srand(time(NULL));
int number=1+rand()%100;
int highLow;
bool a;
a = true;
cout << "Think a number between 1 and 100 and I will guess it" << endl;
system("PAUSE");
cout << "\nIs it ";
cout << number;
cout << "?" << endl;
cout << "If the number is lower press 1, higher 2 and correct 3" << endl;
cin >> highLow;
while (a)
{
if (highLow == 1)
{
number = 1 + rand() % number;
cout << "\nIs it ";
cout << number;
cout << "?" << endl;
cin >> highLow;
}
else if (highLow == 2)
{
number = rand() % (100 - number+1)+number;
cout << "\nIs it ";
cout << number;
cout << "?" << endl;
cin >> highLow;
}
else if (highLow == 3)
cout << "I win this time" << endl;
a = false;}
}
The problem is that it should ask the user as many times as needed to guess the number, but it only does 2 times, then stops. Can you help me please?
If only you had indented your code properly…
The last a = false; statement executes no matter what, because it's outside the scope of the last else if statement. Basically, this:
else if (highLow == 3)
cout << "I win this time" << endl;
a = false;
means the following:
else if (highLow == 3) {
cout << "I win this time" << endl;
}
a = false;
You need to add some curly braces where appropriate.