Random Number Game - c++

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.

Related

How can I store the random numbers outputed by my funtion?

at the moment I'm trying to add up the numbers for my hand and the hit cards, the issue is I created a function for my random number generator so that I can keep calling it into my dice game and the blackjack game, I would normally add the number generator to a variable and call it a day but I made it into a function instead. I am still new to c++.
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
void RandomNumber() { cout << (rand() % 10) + 1; }
void blackjack(int total) {
int startstakes = 15;
int stakes;
int hand;
cout << "Welcome to the Blackjack(21) table\n"
<< "How much are you adding to your initial 15 chip stake - ";
cin >> stakes;
cout << "New stake - " << stakes + 15 << " remaining chips - "
<< total - (stakes + 15) << endl;
cout << "Here is your hand - ";
RandomNumber();
cout << " and ";
RandomNumber();
cout << "Hit me cards: 0 - 0 - 0\n"
<< "Total = ";
system("pause>0");
}
int main() {
int total = 0;
int choice;
srand((unsigned)time(NULL));
cout << "Welcome to Royal Casino!!!, How much money do you wish to "
"convert? ";
cin >> total;
cout << "Excelent you currently have " << total << " Chips.\n"
<< "Let's Begin!\n\n"
<< "We have to tables available today\n";
cout << "1) Blackjack (21)\n"
<< "2) Dice\n"
<< "Both have an entry fee of 15 Chips\n"
<< "Select a table - ";
cin >> choice;
if (choice == 1) {
blackjack(total);
}
if (choice == 2) {
dice();
}
system("pause");
}
So the issue is that you should return the value instead of printing it. Like this (note the return type has changed from void to int)
int RandomNumber() {
return (rand() % 10) + 1;
}
A function which returns a value is much more flexible than a function which prints a value.
Now you can use a function call RandomNumber() pretty much the same way as a variable. E.g.
cout << RandomNumber() << " and " << RandomNumber();
or
int var = RandomNumber();

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...
}

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;
}
}

Guess the random number game

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.

How do I display a list of previous guesses before a user guesses a new number, using an array?

I am creating a guessing game. I need to display the users' previous guesses every time the user makes another guess. I am using an array and pointers. The code below only displays the most recent thing entered by the user. I need it to display a list of previous inputs. The part of the code that includes the pointer seems to be where my issue is located, but I don't know exactly where?
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
void arrayTable(int[]);
int reviewGuess(int Answer, int userGuess);
int _tmain(int argc, _TCHAR* argv[])
{
int guessNum = 3; // Declares how many guesses the user can take.
int userGuess = 0;
int Answer;
char Choice;
int *pointer = NULL;
srand(time(NULL));
Answer = rand() % 20 + 1; //Gives a random number ranging from 1 to 20
do{
int x;
cout << " ____________________________________________________\n";
cout << " | |\n";
cout << " | I want to play a game |\n"; // Displays a welcome message
cout << " | I am thinking of a number between 1 through 20. |\n";
cout << " | Can you guess the number in less than " << guessNum << " tries ? |\n";
cout << " | Press '1' to play. |\n";
cout << " | Press '2' if you want to EXIT!!! |\n";
cout << " |__________________________________________________|\n";
cin >> x;
switch (x)
{
case 1:
for (int i = 0; i < guessNum; i++) //Counter, for loop, stops when condition is met.
{
cout << " This is guess# " << i + 1 << " : "; //Takes the user input
cin >> userGuess;
int guessNum = 1;
pointer = new int[guessNum];
for (int i = 0; i < guessNum; i++) //Store the user guesses
{
*(pointer + i) = userGuess;
}
cout << "Here is a list of your guesses" << endl;
for (int i = 0; i < guessNum; i++) // Display the user guesses.
{
cout << " Guess# " << i + 1 << " is " << *(pointer + i) << endl;
}
reviewGuess(Answer, userGuess); //Calls the function
}
cout << " ------------------> <----------------------\n";
cout << " ------------------> You Lost!!! <----------------------\n";
cout << " ------------------> <----------------------\n";
cout << " You have exceeded the amount of guesses you were given.\n";
cout << " The correct Answer is : " << Answer << endl;
break;
case 2:
cout << "-------------->Thank You.\n";
cout << "-------------->Have a good day.\n";
break;
system("pause");
return 0;
}
cout << "would you like to play again (y/n)?";
cin >> Choice;
} while (Choice == 'y');
system("pause");
return 0;
}
int reviewGuess(int Answer, int userGuess)
{
if (userGuess != Answer)
{
if (userGuess > Answer)
cout << " -----> 1 \n";
else
cout << " -----> -1 \n";
}
else
{
cout << " -----> 0 \n";
cout << " Good JOb, you have guessed the right number. \n";
system("pause");
return 0;
}
}
review the changes, and don't just copy and paste.
to access pointer array members, you can use the index [].
you are already in a for loop, so you dont want to create another for loop getting input, that would be 3 x 3 requests for data.
you were storing the data into an int, not into the array you created with pointer.
pointer isn't a very good name, when its an array of guesses. try calling it something more readable.
once it ran, if the user won, it still triggered losing code. you need to break out before accessing that code the way you have it set up. i created a bool, and changed your reviewguess method to return a bool whether they won or not. break out on exiting. note the double use of breaks; its in a for loop in a switch. you have to break out of the foor loop, and then break out of the switch. you cannot just put it after the for loop, as it will then keep asking for input if they win, and then report they won at the end.
note the use of the global constant to keep track of how many guesses. you were declaring and initializing the same variables all over the place. initialize with the type keyword once, at the start, and if you need the variable in the loop, initalize it before the loop so you dont try to reinitialize every iteration.
logic was reversed as far as higher or lower with reviewGuess
Not a bad start, keep your head up, and i hope i could help you out!
this is my first time answering a question.
Code:
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
void arrayTable(int[]);
bool reviewGuess(int, int);
int _tmain(int argc, _TCHAR* argv[])
{
const int MAX_NUMBER_GUESSES = 3;// Declares how many guesses the user can take.
int currentGuessNum = 0;
int userGuess = 1;
int Answer;
char Choice;
int x;
int *arrGuesses = NULL;
bool gameWon = false;
srand(time(NULL));
//Gives a random number ranging from 1 to 20
do {
Answer = rand() % 20 + 1; //Gives a random number ranging from 1 to 20
//you want this in the loop otherwise you always have same answer
cout << " ____________________________________________________\n";
cout << " | |\n";
cout << " | I want to play a game |\n"; // Displays a welcome message
cout << " | I am thinking of a number between 1 through 20. |\n";
cout << " | Can you guess the number in less than " << MAX_NUMBER_GUESSES << " tries ? |\n";
cout << " | Press '1' to play. |\n";
cout << " | Press '2' if you want to EXIT!!! |\n";
cout << " |__________________________________________________|\n";
cin >> x;
switch (x)
{
case 1:
userGuess = 1;
arrGuesses = new int[MAX_NUMBER_GUESSES];
for (int i = 0; i < MAX_NUMBER_GUESSES; i++) //Counter, for loop, stops when condition is met.
{
cout << " This is guess# " << userGuess << " : " << endl; //Takes the user input
cin >> arrGuesses[i];
cout << "Here is a list of your guesses" << endl;
for (int i = 0; i < userGuess; i++) // Display the user guesses.
{
cout << " Guess# " << i+1 << " is " << arrGuesses[i] << endl;
}
gameWon = reviewGuess(Answer, arrGuesses[i]); //Calls the function
if (gameWon)
{
break;
}
userGuess++;
}
if (gameWon)
{
break;
}
cout << " ------------------> <----------------------\n";
cout << " ------------------> You Lost!!! <----------------------\n";
cout << " ------------------> <----------------------\n";
cout << " You have exceeded the amount of guesses you were given.\n";
cout << " The correct Answer is : " << Answer << endl;
break;
case 2:
cout << "-------------->Thank You.\n";
cout << "-------------->Have a good day.\n";
break;
system("pause");
return 0;
}
cout << "would you like to play again (y/n)?";
cin >> Choice;
} while (Choice == 'y');
system("pause");
return 0;
}
bool reviewGuess(int Answer, int userGuess)
{
if (userGuess != Answer)
{
if (userGuess < Answer)
cout << " -----> 1 \n";
else
cout << " -1 <----- \n";
return false;
}
else
{
cout << " -----> 0 \n";
cout << " Good JOb, you have guessed the right number. \n";
system("pause");
return true;
}
}