Uninitialized local variable in c++ dice game - c++

In this case, how would I solve this? I've looked at other posts with the same problem and I can't seem to apply it to this. I've solved this problem before but for some reason I can't remember how I did it.
#include <iostream>
#include <cstdlib>
#include <Windows.h>
#include<ctime>
using namespace std;
//Tristan Currie 11/20/14
//Dice Game
int main()
{
//variables
int die1, die2, dice_total, specialsum;
char rerun, reroll;
//intro
cout << "Welcome to the dice game! I will now explain the rules. \nIf you land on a 7 or 11 on the first role you win. \nIf your sum is 2, 3, or 12 you lose. \nAny other role becomes your special sum. If you roll your special sum before you roll a 7 then you win. \nIf when you roll you get a 7 before your special sum then you lose. ";
cout << "\n\nIf you would like to start the game, press enter to do your first roll. ";
cin.get();
cout << "\n\nRolling Dice...";
//Suspend program for 2 seconds
Sleep(2000);
//seed random number generator using the system clock
srand(static_cast<unsigned int>(time(0)));
//generate a random number between 1 and 6
die1 = rand() % 6 + 1;
die2 = rand() % 6 + 1;
dice_total = die1 + die2;
cout << "Done!" << endl << "Dice #1 = " << die1 << "\nDice #2 = " << die2 << "\nDice Total = " << dice_total;
cin.get();
if ((dice_total == 7) || (dice_total == 11)) {
cout << "Congratulations! You have won the game, press enter to end the program. ";
cin.get();
reroll = 'n';
}
else if ((dice_total == 2) || (dice_total == 3) || (dice_total == 12)) {
cout << "You lost. Press enter to exit. ";
cin.get();
reroll = 'n';
}
else if ((dice_total != 2) || (dice_total != 3) || (dice_total != 12) || (dice_total != 7) || (dice_total != 11)) {
cout << "This is your special sum: " << dice_total << endl;
dice_total = specialsum;
reroll = 'y';
}
while (reroll == 'y') {
cout << "\n\nRolling Dice...";
//Suspend program for 2 seconds
Sleep(2000);
//seed random number generator using the system clock
srand(static_cast<unsigned int>(time(0)));
//generate a random number between 1 and 6
die1 = rand() % 6 + 1;
die2 = rand() % 6 + 1;
dice_total = die1 + die2;
cout << "Done!" << endl << "Dice #1 = " << die1 << "\nDice #2 = " << die2 << "\nDice Total = " << dice_total;
cin.get();
if (dice_total == specialsum) {
cout << "Congratulations! You have won the game, press enter to end the program. ";
cin >> rerun;
cin.get();
reroll = 'n';
}
else if (dice_total == 7) {
cout << "What a shame, you have lost the game, press enter to exit the gane. ";
cin >> rerun;
cin.get();
reroll = 'n';
}
else {
reroll = 'y';
}
}
}

Well, I got an answer in the comments. I mixed up the order of this line: dice_total = specialsum;

int specialsum = 0;
Initializing integer variables to zero, or to a known value. Defining your variable like this, "int specialsum;" ,it gets lost.
Also try specialsum= dice_total; instead of dice_total=specialsum; because "dice_total" would be equal to zero all the time. Hope this helped.

Related

Need help understanding " rand() % 67 < 10"

I am trying to practice my C++ in order to grasp a better understanding in class, as I am a beginner and a little behind, and I came across a zombie game that someone posted online.
Anyways, I understand most of the code, however I do not understand "if(rand() & 67 < 10)".
I can interpret "rand() % 10 + 1", in which the code will generate a number, or in this case zombies, between 1 and 10.
Thinking at first that the zombies would cap at 67, given the player had chosen a high number, but I don't believe that is its function, but again, I'm not entirely sure...
Here is an example of the code I am looking at:
I'm sure its something simple, however I am still confused on its purpose. Even after trying to learn its function my running the game
Here is the whole code just in case:
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
using namespace std;
int createZombie() { // createZombie function OPEN
if(rand() % 67 < 10)
return 11;
else
return rand() % 10 + 1;
} // createZombie fuction CLOSED
// #################### MAIN FUNCTION ############################
int main() { // main function OPEN
srand(time(NULL));
char enter;
// game stats
int playerAlive = true;
int playerSkill = 9;
int playerScore = 1;
string playerName = "";
int zombieCount = 0;
int zombiesKILLed = 0;
// title
cout << "Welcome to Zombie War." << endl << "Press [ENTER] to start ";
cin.get();
// player name
cout << "Please enter your name: ";
cin >> playerName;
// ask how many zombies
cout << "How many zombies do you wish to fight? ";
cin >> zombieCount;
cout <<"Get ready to fight for you life, " << playerName << "!" << endl;
// main game loop
while(playerAlive && zombiesKILLed < zombieCount) { // while loop OPEN
// create a random zombie
int zombieSkill = createZombie();
// battle sequence
if(zombieSkill > 10) { // if statment OPEN
cout << endl << "Here comes a huge zombie! " << endl;
} // if statement CLOSED
else { // else statement OPEN
cout << endl << "Here comes Zombie " << zombiesKILLed + 1 << endl;
} // else statement CLOSED
cout << "Fighting... " << endl;
sleep(2);
// zombies killed the player
if(playerSkill < zombieSkill) { // if statement OPEN
playerAlive = false;
cout << "You have died." << endl;
} // if statement CLOSED
else { // else statment OPEN
// PLAYER KILLED THE ZOMBIE
if(playerSkill - zombieSkill > 7) { // if statement OPEN
cout << "You wasted the Zombie! " << endl;
playerScore = playerScore * 2;
} // if statment CLOSED
else if (playerSkill - zombieSkill > 5) { // else if statement OPEN
cout << "You decapitated the Zombie!" << endl;
playerScore = playerScore * 2;
} // else if statement CLOSED
else if (playerSkill - zombieSkill > 0) { // else
if statement OPEN
cout << "You Killed the Zombie!" << endl;
playerScore = playerScore * 2;
} // else if statment CLOSED
else { // else statment OPEN
cout << "You killed the zombie, but suffered injuries." << endl;
} // else statment CLOSED
zombiesKILLed++;
} // else statment CLOSE
cout << endl;
sleep(1);
} // while loop CLOSED
if(zombiesKILLed == zombieCount) { // if statement OPEN
// victory
cout <<"Your have survived the onslaught!" << endl;
} // if statement CLOSED
else { // else statement OPEN
// LOST
cout << "You did not survive the zombie war" << endl;
} // else statement CLOSED
cout << "Zombies killed: " << zombiesKILLed << endl;
cout << "Final score: " << playerScore << endl << endl;
} // main function CLOSED
Splitting the command into two parts for easy understanding:
Part I-
rand() % 67
= generate any random number from 0-66
= remainder of division of any number by 67
= N (say)
Part II
if( rand() % 67 < 10)
= if( N < 10)

Printing a scoreboard with a sliding arrow C++ beginner

I am working on a program to code a game called Devil's Dice. I have the logic of code working perfectly, but I am struggling to print the scoreboard to show the games progress. The details of the assignment are below, followed by my code. I don't know where to begin printing the scoreboard as shown in the image I linked.
In our version of Devil's Dice the rules will be as follows:
The player repeatedly rolls a 6-sided die until either a 1 is rolled or the player decides to "hold".
If the player rolls a 1, they lose any points accumulated this turn and the devil gets a turn.
If the player rolls any other number, it is added to their turn total and the player's turn continues.
If a player chooses to "hold", their current turn total is added to their score and the devil gets a turn.
Devil's Logic
If the score is tied or the devil is winning, he will keep rolling until he has at least 21 points (unless he has already reached 100 points)
If the player is winning, the devil will keep rolling until he has at least 30 points (unless he has already reached 100 points)
If the devil rolls a 1, he also loses the points he has accumulated on his turn
If the player chooses to "forfeit", they lose and the game is over.
The player must score 100 points before the devil manages to do so in order to win.
For example, the player, Ann, begins a turn with a roll of 5. Ann could hold and score 5 points, but chooses to roll again. Ann rolls a 2, and could hold with a turn total of 7 points, but chooses to roll again. Ann rolls a 1, and must end her turn without scoring. The devil then rolls the sequence 4-5-3-5-5, chooses to hold, and adds his turn total of 22 points to his score.
There are a few other details about the game logic but i am confident i have it working correctly. I am just wondering how to get a menu with a moving arrow as shown below.
My code looks like this:
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main() { //just for a school grading program//
#ifdef JARVIS
srand(0);
#else
srand(time(NULL));
#endif
// Call your functions to play your game here...
char userInput;
int diceRoll;
int turnScore = 0;
int totalScore = 0;
int devilScore = 0;
bool isItDevilsTurn = false;
bool winner = false;
int devilWins = 0;
int playerWins = 0;
cout << "---- Welcome to Devil's Dice! ----" << endl;
cout << "Hold[h], roll[r], or forfeit[f]: " << endl;
while (!winner) {
if (!isItDevilsTurn) {
cin >> userInput;
if (userInput == 'h')
{
totalScore = totalScore + turnScore;
cout << "You banked " << turnScore << " points and have a total of " << totalScore << " points" << endl;
isItDevilsTurn = true;
turnScore = 0;
}
if (userInput == 'r')
{
diceRoll = rand() % 6 + 1;
if (diceRoll > 1)
{
cout << "You rolled a " << diceRoll << "!" << endl;
turnScore = turnScore + diceRoll;
}
else
{
cout << "You rolled a 1 :(" << endl;
turnScore = 0;
isItDevilsTurn = true;
}
}
if (totalScore >= 100) {
winner = true;
cout << "You Win!" << endl;
playerWins = playerWins + 1;
}
if (userInput == 'f') {
cout << "Game Over!" << endl;
}
}
else
{
int devilGoal = 21;
if (totalScore > devilScore)
{
devilGoal = 30;
}
while (isItDevilsTurn)
{
diceRoll = rand() % 6 + 1;
if (diceRoll > 1 && turnScore < devilGoal)
{
cout << "devil rolled " << diceRoll << endl;
turnScore = turnScore + diceRoll;
}
else if (diceRoll > 1 && turnScore > devilGoal)
{
devilScore = devilScore + turnScore;
cout << "devil holds " << turnScore << " points and now has " << devilScore << " points" << endl;
isItDevilsTurn = false;
turnScore = 0;
}
else
{
cout << "devil rolled a 1" << endl;
isItDevilsTurn = false;
turnScore = 0;
}
if (devilScore >= 100)
{
cout << "Devil Wins!" << endl;
devilWins = devilWins + 1;
winner = true;
}
}
}
}
cout << "Total Wins: " << playerWins << endl;
cout << "Total Losses: " << devilWins << endl;
fstream output("games.txt");
output << playerWins << " " << devilWins << endl;
return 0;
}
I'm sorry, I'm not too good with tabs, so you just make it looks like you need to. I used a ternary operator to understand if I need to write number or a tab in cuurent line
printf("\tPlayer\t\t\tDevil\n");
printf("\t------\t\t\t-----\n");
for(int i = 10; i >= 0; --i){
printf((totalScore < (i+1)*10 && totalScore >=i*10) ? "%d >" : "\t", totalScore);
printf("--%d", i*10);
printf((turnScore < (i+1)*10 && turnScore >=i*10) ? "< %d" : "\t\t\t", turnScore);
printf((devilTotal < (i+1)*10 && devilTotal >=i*10) ? "%d >" : "\t", devilTotal);
printf("--%d", i*10);
printf((devilTurn < (i+1)*10 && devilTurn >=i*10) ? "< %d" : "\t\t", devilTurn);
printf("\n");
}
How it works? first printf() I evaluate totalScore, if it's less then next value and more than current I print it, otherwise just print tab. Second printf() prints current value. Third printf() evalutes turnScore, if it's less then next value and more than current I print it, otherwise just print 2 tabs.
Same for devil.
It would be the same with cin and cout, it's just that I feel more confident with printf(). If it looks right, all you need to do is work with alignments.

C++ 'Word Jumble'

I have a small problem. I have attempted to make the game 'Word Jumble' with a scoring system. But sometimes, when the computer guesses a word, then it'll say: The word is: blank here. There should be a jumbled word there. When I try any word, it just subtracts 1.#INF points.
Code:
#include<iostream>
#include<string>
#include<stdlib.h>
#include<time.h>
using namespace std;
const int size=10;
string Words[size] = {
"consecutive",
"alternative",
"consequently",
"jumbled",
"computer",
"charger",
"food",//I'm hungry
"library",
"strawberry",
"carrier"
};
string Hints[size] = {
"Following continuously.",
"Something available as another opportunity.",
"As a result.",
"This word is rather jumbled, isn't it ;)",
"The enitiy you are reading this off of",
"My phone battery is running low",
"I'm hungry, I need some _",
"Where can I go get a book?",
"It's red, and not a berry."
"Either carries stuff, or is what your data company is called."
};
void main()
{
string word,hint;
double points=0;
bool correct=false,playAgain=true;
cout << "Welcome to Word Jumble!\n";
cout << "The objective of this game is to guess the jumbled word, correctly.\n";
cout << "Say 'quit' to quit, or 'hint' for a hint.\n";
while (playAgain==true)
{
correct = false;
int guesses = 0;
srand(static_cast<unsigned int>(time(0)));
int num = rand() % size + 1;
word = Words[num];
hint = Hints[num];
string jumble = word;
int length = jumble.size();
for (int i = 0; i < length*2; ++i)
{
int index1 = (rand() % length);
int index2 = (rand() % length);
char temp = jumble[index1];
jumble[index1] = jumble[index2];
jumble[index2] = temp;
}
cout << "The word is: " << jumble << endl;
double tempPoints=0;
while (correct==false)
{
string theGuess;
cout << "Guess the word: ";
cin >> theGuess;
guesses++;
while (!cin)
{
cin.sync();
cin.clear();
cout << "Ivalid entry, try again: ";
cin >> theGuess;
}
if (theGuess == word)
{
cout << "Correct! You guessed the word in only " << guesses << " tries!\n";
tempPoints += jumble.size()*1.5;
tempPoints -= (guesses - 1) / 4.0;
points += tempPoints;
cout << "You have been awarded " << tempPoints << " points this round for a total of " << points << "!\n";
correct = true;
cout << "Would you like to play again? (y or n): ";
char tempYN;
cin >> tempYN;
while (!cin || tempYN != 'y' && tempYN != 'n')
{
cin.sync();
cin.clear();
cout << "Invalid entry.\nWould you like to play again? (y or n): ";
cin >> tempYN;
}
if (tempYN == 'y')
{
playAgain = true;
}
else
{
playAgain = false;
}
}
else if (theGuess == "hint")
{
tempPoints -= (1.0 / (jumble.size())) * 40;
cout << "Hint: " << hint << endl;
correct = false;
playAgain = true;
}
else if (theGuess == "quit")
{
correct = true;
playAgain = false;
}
else
{
double sub = (1.0 / (jumble.size())) * 20;
cout << "Incorrect word, deducting "<<sub<<" points\n";
tempPoints -= sub;
playAgain = true;
correct = false;
}
};
};
cout << "Goodbye\n";
}
In the line:
int num = rand() % size + 1;
You are saying to select a random number between 0 and 9 then add 1.
If the random number is 9 the + 1 will make it 10. This means that you are trying to access a value in the array Words and Hints at index 10. Since arrays are 0 indexed and it's size is 10 that means you only have elements at 0 - 9.
You also will never get the first string in the arrays.

Generating numbers outside of my range C++ (way too large)

I decided for fun to try and make a simple program that "sort of" simulates blackjack in a dumbed down way. It's basically done, except for the fact that the randomly generated numbers are WAY too large. I don't care about the bias srand/rand has (for now) I just want to get it working properly.
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>
using namespace std;
int genRandInt (int low, int high) {
int randnum = low + (rand() % (high - low + 1));
return randnum;
}
int main()
{
srand(time(NULL));
int computerScore;
int score;
int card;
while (int playAgain = 1)
{
cout << "Enter 0 to hold or 1 to hit: ";
int play;
cin >> play;
if (play == 0)
{
computerScore = genRandInt(1, 31);
if (score < computerScore)
{
cout << "Your score is " << score << " and the computer's score is " << computerScore << "! You lose.\n";
}
if (score > 21)
{
cout << "Your score is " << score << " which is greater than 21. Bust!\n";
}
if (score > computerScore && score <= 21)
{
cout << "Your score is " << score << " and the computer's score is " << computerScore << "! You win!\n";
}
cout << "Would you like to play again? 1 for yes, 0 for no. : ";
cin >> playAgain;
}
if (play == 1)
{
card = genRandInt(1, 11);
score = score + card;
cout << "Your score is: " << score << "\n";
}
}
return 0;
}
Any ideas?
You use int score; uninitialized in
if (score < computerScore)
or
score = score + card;
depending on the if(play == 0) or if(play == 1) condition.
It happens to have some junk as its memory content, the compiler does not initializes to zero for you. In fact, it is undefined behaviour to use un-initialized variables. Initialize it before the first usage, preferable in the definition itself,
int score = 0;
Also, compile with warnings on (-Wall -Wextra for g++/clang++), since the compiler will easily warn about these mistakes.
Try running this and seeing if you have the same issues. I just added some print statements to try and debug it, and it stopped showing me really big numbers..
EDIT:
//ADD
int score = 0;
//
if (play == 1)
{
cout << "printing in the PLAY = 1 "<< score << endl;
card = genRandInt(1, 11);
score = score + card;
cout << "Your score is: " << score << "\n";
}

C++ programming Craps game simulation

Write a C++ program that simulates the casino game of craps. These are the rules of the game:
• If a player throws a 7 or 11 (sum of two dice) on the first roll, the player wins the game.
• If a player throws a 2, 3 or 12 (sum of two dice) on the first roll, the player loses the game.
• If a player throws a 4, 5, 6, 8, 9 or 10 (sum of two dice) on the first roll, s(he) neither wins nor loses but creates a “point.” If this is the case, the player keeps rolling the dice until the point (4, 5, 6, 8, 9 or 10) is thrown again, and the player wins the game. However, if the player throws a 7 (sum of two dice) before the “point” is thrown, the player loses the game.
You will create a function called rollDice that will, when called, roll two dice and return a random number between 2 and 12. Each time rollDice is called, the program should output the result of the roll
The program will ask the player ” Another game? Y(es) or N(o)?” and terminate whenever any key other than Y or y is pressed.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
int dice1, dice2 = 0;
int rollDice;
char repeat = 'y';
cout << "**********************************************************"<< endl;
cout << "******** Welcome to the Kyung Bae Choi Casino ********"<< endl;
cout << "********* Step up to the table and place your bets! ******"<< endl;
cout << "**********************************************************"<< endl;
while (repeat == 'y' || repeat == 'Y')
{
dice1 = rand() % 6 + 1;
dice2 = rand() % 6 + 1;
rollDice = dice1 + dice2;
cout << "Your rolled " << rollDice;
if (rollDice == 7 || rollDice == 11)
{
cout << ". Winner !" << endl ;
}
else if (rollDice == 2 || rollDice == 3 || rollDice == 12)
{
cout << ". You lose!" << endl;
}
else if (rollDice == 4 || rollDice == 5 ||rollDice == 6 ||rollDice == 8 || rollDice == 9 || rollDice == 10)
{
dice1 = rand() % 6 + 1;
dice2 = rand() % 6 + 1;
int sum2 = dice1 + dice2;
if( sum2 == rollDice )
{
cout << ". Winner !" << endl;
break;
}
else if( sum2 == 7 )
{
cout << ". You Lose!" << endl;
break;
}
}
cout <<"Another game? Y(es) or N(o)" << endl;
cin >> repeat;
while (repeat == 'n' || repeat == 'N')
{
cout << "Thank you for playing!"<< endl;
}
return 0;
}
}
This does output only 7. so, it keep saying Your rolled 7. Winner !
Another game? Y(es) or N(o). And, if i put y, the program ends. or if i put n, the program output the "thank you for playing!" endlessly.
what is problem??
How can I make it continually re-rolling the dice until the player rolls the winning "point" or rolls a seven.
You're missing the "...." in the coutstatement. So, the compiler is fooled to belive that Thank, you,... are instructions [keywords/variables] which is actually wrong.
change
cout << Thank you for playing!<< endl;
to
cout <<"Thank you for playing!"<< endl;
Thumb Rule:
Always try to look into the information provided by the compiler during error/warning meessage. Here, the line number 58. It is really helpful to pinpoint the erroneous instructuion.
EDIT:
Please do not edit the current qusetion and add a completely new query. Reatain the previous version and metion the EDIT. Otherwise, it makes the previous answers irrelevant.
You're missing quotes in cout << Thank you for playing!<< endl;.
cout << "Thank you for playing!" << endl;
Also, your logic for testing repeat == 'n' or 'N' is wrong:
You should use an if statement, not a while loop.
You should quit the program only if the user enters 'N' or 'n'.
To notice the second error, it is helpful to use a standard indentation style.
Use Double qoutes (") while printing a string..
cout <<"Thank you for playing!"<< endl;
And One more thing as suggested by #irrelephant in his answer
use
if(repeat == 'n' || repeat == 'N') //Use if condition
{
cout << Thank you for playing!<< endl;
return 0; // exit only when user enter `n` or `N`
}
If you use return 0; outside then no matter what user has entered Y or N, program will terminate.