Xcode C++ How to add a "Play Again?" function to my program - c++

my program is all finished but I want to know how to add a "Play again" feature that uses "Yes" or "No" input to decide whether to run the program again or to end it. I am a little unsure of where to place it in my program since I use a handful of while loops and if/else statements. Any insight would be appreciated, thanks! Here is my code:
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <ctime>
using namespace std;
int main() // Setting up the code to follow.
{
srand(static_cast<unsigned int>(time(0)));
int Weapon_Selection; // Creating variables for the player and computer's weapon selection.
int Comp_Weapon;
bool Battle = true; // The variable to begin the battle.
while(Battle) // The main while loop to run the program code.
{
int Player_Health = 100; // More variables for both the player and the computer.
int Comp_Health = 100;
int Cannon_Ammo = 3;
int Grenade_Ammo = 4;
int Comp_Cannon_Ammo = 3;
int Comp_Grenade_Ammo = 4;
while(Player_Health > 0 && Comp_Health > 0) // The while loop to continue running the program while both combatants are alive.
{
bool Invalid = true;
bool Comp_Invalid = true;
while(Invalid)
{
cout << "Select a weapon using number keys 1, 2, and 3.\n"; // Weapon selection input from the player.
cout << "1. Cannon (Ammo left: " << Cannon_Ammo << ")\n";
cout << "2. Grenade (Ammo left: " << Grenade_Ammo << ")\n";
cout << "3. Rifle\n";
cout << "\n";
cout << "You select: ";
cin >> Weapon_Selection;
srand(static_cast<unsigned int>(time(0)));
if (Weapon_Selection == 1 && Cannon_Ammo > 0)
{
Cannon_Ammo -= 1;
Invalid = false;
int Player_Dmg = rand() % 5 + 10; // Randomly generated damage range.
cout << "You caused " << Player_Dmg << " cannon damage to your enemy!\n";
Comp_Health -= Player_Dmg;
cout << "Your health is " << Player_Health << "\n";
cout << "The computer's health is " << Comp_Health << "\n";
cout << "\n";
break;
}
else if (Weapon_Selection == 2 && Grenade_Ammo > 0)
{
Grenade_Ammo -= 1;
Invalid = false;
int Player_Dmg = rand() % 5 + 7;
cout << "You caused " << Player_Dmg << " grenade damage to your enemy!\n";
Comp_Health -= Player_Dmg;
cout << "Your health is " << Player_Health << "\n";
cout << "The computer's health is " << Comp_Health << "\n";
cout << "\n";
break;
}
else if (Weapon_Selection == 3)
{
Invalid = false;
int Player_Dmg = rand() % 5 + 3;
cout << "You caused " << Player_Dmg << " rifle damage to your enemy!\n";
Comp_Health -= Player_Dmg;
cout << "Your health is " << Player_Health << "\n";
cout << "The computer's health is " << Comp_Health << "\n";
cout << "\n";
break;
}
else
cout << "You are out of ammo or you have entered an invalid number." << "\n"; // Output for wrong number input or no ammo.
cout << "\n";
}
if (Comp_Health <= 0) // Break point if the computer dies in battle.
break;
while(Comp_Invalid) // The computer's random weapon selection.
{
Comp_Weapon = rand() % 3 + 1;
if (Comp_Weapon == 1 && Comp_Cannon_Ammo > 0)
{
Comp_Cannon_Ammo -= 1;
Comp_Invalid = false;
int Comp_Dmg = rand() % 5 + 10; // Randomly generated damage range for the computer.
cout << "Your enemy used a cannon and caused " << Comp_Dmg << " damage to you!\n";
Player_Health -= Comp_Dmg;
cout << "Your health is " << Player_Health << "\n";
cout << "The computer's health is " << Comp_Health << "\n";
cout << "\n";
}
else if (Comp_Weapon == 2 && Comp_Grenade_Ammo > 0)
{
Comp_Grenade_Ammo -= 1;
Comp_Invalid = false;
int Comp_Dmg = rand() % 5 + 7;
cout << "Your enemy used a grenade and caused " << Comp_Dmg << " damage to you!\n";
Player_Health -= Comp_Dmg;
cout << "Your health is " << Player_Health << "\n";
cout << "The computer's health is " << Comp_Health << "\n";
cout << "\n";
}
else
{
Comp_Invalid = false;
int Comp_Dmg = rand() % 5 + 3;
cout << "Your enemy used a rifle and caused " << Comp_Dmg << " damage to you!\n";
Player_Health -= Comp_Dmg;
cout << "Your health is " << Player_Health << "\n";
cout << "The computer's health is " << Comp_Health << "\n";
cout << "\n";
}
}
}
if(Player_Health < 0) // End of battle output, regardless of who wins or loses.
cout << "You have been defeated by your enemy!" << "\n" << endl;
else
cout << "Congratulations, you beat your enemy!" << "\n" << endl;
}
cin.ignore(2);
return 0;
}

To illustrate #NathanOliver's comment:
int main(void)
{
bool play_again = true;
while (play_again)
{
Play_Game();
std::cout << "\nWant to play again (y / n)?";
char answer;
std::cin >> answer;
if (tolower(answer) != 'y')
{
play_again = false;
}
}
return 0;
}
You could also use a do-while loop as well.

Related

C++ Left Center Right Dice Game (Game Loop and connecting vectors/arrays to classes/header files)

So i have to code the dice game LCR for a final prject but am having some trouble. First off, I know the code is sloppy and really redundant, that's why im looking for help. I couldn't figure out how to connect the 'chips' int vector and 'name' array into the player.h file. I basically need help writing methods for the chip passing to make the code less redundant. But another problem of mine is having the game loop until just one person has chips. Thanks for any help or advice.
LeftCenterRight.cpp
#include <iostream>
#include <string>
#include <time.h>
#include "Dice.h"
#include "Player.h"
#include <vector>
#include <algorithm>
using namespace std;
void Player::gameRules()
{
cout << ("\n-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-\n\n");
cout << ("Left Center Right is a multiplayer dice game");
cout << ("With a minimum of three players.");
cout << ("Dice containing letters L, C, R along\n"
"with dots on the remaining side are rolled each turn");
cout << ("\n-----Each Player starts with three chips-----\n");
cout << (">> For each L rolled, the player must pass one chip to the player to their left\n"
">> For each R rolled, the player must pass one chip to the player to their right\n"
">> For each C rolled, the player must pass a chip into the center pot (out of play)\n"
">> Dots are neutral and require no action");
cout << ("If a player has three or more chips, he/she rolls all three dice\n"
"If a player only has two chips, he/she rolles onlt two dice\n"
"If a player only has one chip, he/she rolls only one die\n"
"If a player is out of chips, he/she is still in the game,\n"
"\tbut does not roll any dice and passes their turn"
"\n\n >>> The last player with chips is the winner <<<");
cout << ("\n\n-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-\n");
};
int main()
{
int result = 0;
int currPlayer = 1;
srand((unsigned)time(NULL));
int numPlayers;
cout << "How many players are playing? (Please enter 3 or more): " << endl;
cin >> numPlayers;
if (numPlayers <= 2)
{
while (numPlayers <= 2)
{
cout << "More players needed.";
cout << "How many players are player?: ";
cin >> numPlayers;
}
}
std::string* names = new string[numPlayers]; // getting names and index is seat number
for (int i = 0; i < numPlayers; i++)
{
cout << "Please enter your name player " << i+1 << endl;
cin >> names[i];
std::string playerName = names[i];
}
vector<int>chips[1]; // intial 3 chips
for (int i = 0; i < numPlayers; i++)
{
int InitialChips = 3;
chips->push_back(InitialChips);
}
Player::gameRules();
int sum = 0;
for (int i = 0; i < chips->size(); i++)
{
int num = chips->at(i);
sum+=num;
}
int thePot = 0;
int i = 0;
while (sum > 0)
{
if ( i >=4 )
{
i = 0;
}
string currPlayer = names[i];
int currSeat = i;
cout << "It's " << currPlayer << "'s Turn!" << endl;
cout << "[1] Roll Dice [2] Quit :";
int choice;
cin >> choice;
if (choice == 1)
{
if (chips->at(currSeat) == 0)
{
break;
}
if (chips->at(currSeat) >= 3)
{
for (int k = 0; k <= 3; k++)
{
int outcome = Dice::rollDice();
if (outcome == 1)
{
int currChips = chips->at(i);
chips->at(i) = (currChips - 1);
cout << ">> -1 chip to " << names[i] << endl;
cout << ">> " << names[i] << " now has " << chips->at(i) << " chip(s)" << endl;
if (i == 0)
{
int j = (numPlayers - 1);
int currChips2 = (chips->at(j));
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
else
{
int j = i - 1;
int currChips2 = (chips->at(j));
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
}
if (outcome == 2)
{
int currChips = chips->at(i);
chips->at(i) = (currChips - 1);
cout << ">> -1 chip to " << names[i] << endl;
cout << ">> " << names[i] << " now has " << chips->at(i) << " chip(s)" << endl;
if (i == chips->size())
{
int j = chips->at(0);
int currChips2 = chips->at(0);
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
else
{
int j = i + 1;
int currChips2 = (chips->at(j));
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
}
if (outcome == 3)
{
thePot++;
cout << ">> +1 chip to the Center Pot" << endl;
cout << "There are now " << thePot << " chip(s) in the Center Pot " << endl;
int currChips = chips->at(i);
chips->at(i) = (currChips - 1);
cout << ">> -1 chip to " << names[i] << endl;
cout << ">> " << names[i] << " now has " << chips->at(i) << " chip(s)" << endl;
break;
}
else if ((outcome == 4) || (outcome == 5) || (outcome == 6))
{
break;
}
}
}
// ^^basically copied and pasted most of the while loop for the other two numbers of dice to roll^^
// had redundant code for if the player had 2 chips, to roll two dice only ^^
// also redundant code for only one chip, to roll one die. ^^
}
}
else if (choice == 2)
{
break;
}
else
{
cout << ">> Input Error";
cout << "[1] Roll Dice [2] Quit";
cin >> choice;
}
i++;
}
return 0;
}
Dice.h
#pragma once
using namespace std;
class Dice
{
public:
static int rollDice();
static int diceOutcome;
};
int Dice::rollDice()
{
int diceOutcome;
diceOutcome = (rand() % 6) + 1;
switch (diceOutcome)
{
default:
cout << "Error, retry";
case 1:
if (diceOutcome == 1)
{
cout << " --- " << endl;
cout << "You rolled a | L | Move 1 chip left." << endl;
cout << " --- " << endl;
return 1;
}
break;
case 2:
if (diceOutcome == 2)
{
cout << " --- " << endl;
cout << "You rolled a | R | Move 1 chip right." << endl;
cout << " --- " << endl;
return 2;
}
break;
case 3:
if (diceOutcome == 3)
{
cout << " --- " << endl;
cout << "You rolled a | C | Move 1 chip to the center." << endl;
cout << " --- " << endl;
return 3;
}
break;
case 4:
if (diceOutcome == 4)
cout << " --- " << endl;
cout << "You rolled a | * | No action needed." << endl;
cout << " --- " << endl;
return 0;
break;
case 5:
if (diceOutcome == 5)
cout << " --- " << endl;
cout << "You rolled a | * | No action needed." << endl;
cout << " --- " << endl;
return 0;
break;
case 6:
if (diceOutcome == 6)
cout << " --- " << endl;
cout << "You rolled a | * | No action needed." << endl;
cout << " --- " << endl;
return 0;
break;
}
}
To be fair, I'm quite new to programming, but I have been working on this project for days and kept running into conatiner problems and storing the name and chip values independently. So i've tried a lot of different things, probably not correctly though so I'm open to anything.

How to fix my C++ fighting game with Run-Time Check Error?

I have been receiving an issue that I do not understand. The issue is:
Run-Time Check Failure #3 - The variable 'win' is being used without being initialized.
I am struggling to comprehend where my error is within the code. From what I understand the run time error comes from win not being initialized meaning it hasn't been used or set, however, it clearly is set in the fightScene() function.
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include "Character.h"
#include "Item.h"
#include "Blacksmith.h"
using namespace std;
void startup();
void createCharacter();
void existCharacter();
void secondFighter();
void fightScene();
int fightMoves(int att, int sp, int num);
void roundWon();
void characterLost();
void use_bar();
void newlines();
void changeCase(string &convert);
void bSmith();
Character existingCharacter[4] = { Character("Shabu", 10, 10, 10, 0, "Empty"), Character("Calil", 15, 15, 15, 0, "Empty"), Character("Goltero", 20, 20, 20, 0, "Empty"), Character("Balrogg", 30, 30, 30, 0, "Empty") };
Character cCharacter[2] = { Character(), Character() };
Character cCharacterSave("Empty", 20, 0, 0, 100, "Empty");
Item bars(0, 0, 0);
int timesWon = 0;
int purposeIgnore = 0;
char repeat = 'y';
int main() {
startup();
while (repeat == 'y' || repeat == 'Y') {
fightScene();
if (repeat == 'y' || repeat == 'Y')
secondFighter();
}
return 0;
}
void startup() {
int playerChoice;
cout << "**************************" << endl;
cout << "* Loading Game *" << endl;
cout << "**************************" << endl;
cout << "Which Would You Prefer?" << endl;
cout << "1: New Character..." << endl;
cout << "2: Load Character..." << endl;
do {
cout << "Enter Selection: ";
cin >> playerChoice;
} while (playerChoice <= 0 || playerChoice >= 3);
if (playerChoice == 1)
createCharacter();
else if (playerChoice == 2)
existCharacter();
return;
}
void createCharacter() {
string Name;
string inventory;
int h, att, sp, gc;
cout << "***************************" << endl;
cout << "* Creating New Player *" << endl;
cout << "***************************" << endl;
cout << "What Shall We Call You?" << endl;
cout << "Enter Name Here: ";
cin >> Name;
changeCase(Name);
cout << Name << ", let's set your stats!" << endl;
cout << "Set your ATTACK between 1 - 10" << endl;
do {
cout << "Enter Attack Here: ";
cin >> att;
} while (att <= 0 || att >= 11);
cout << "Set your SPEED between 1 - 10" << endl;
do {
cout << "Enter Speed Here: ";
cin >> sp;
} while (sp <= 0 || sp >= 11);
h = 20;
gc = 100;
cout << "The HEALTH stat wil increase over time, but as of now, " << Name << ", has " << h << " health!" << endl;
cout << Name << " you have been granted " << gc << " gold!" << endl;
cCharacter[0] = Character(Name, h, att, sp, gc, inventory);
cin.ignore();
return;
}
void existCharacter() {
string characterChoice;
cout << "***********************" << endl;
cout << "* Existing Player *" << endl;
cout << "***********************" << endl;
for (int i = 0, j = 1; i >= 0 && i <= 3; i++, j++) {
cout << j << ": " << existingCharacter[i].getName();
cout << "\t" << "Health: " << existingCharacter[i].getHealth();
cout << "\t" << "Attack: " << existingCharacter[i].getAttack();
cout << "\t" << "Speed: " << existingCharacter[i].getSpeed();
}
cout << "Enter Selection: ";
cin.ignore();
getline(cin, characterChoice);
changeCase(characterChoice);
if (characterChoice == "1" || characterChoice == "Shabu") {
cCharacter[0] = existingCharacter[0]; cCharacterSave.setHealth(existingCharacter[0].getHealth());
}
else if (characterChoice == "2" || characterChoice == "Calil") {
cCharacter[0] = existingCharacter[1]; cCharacterSave.setHealth(existingCharacter[1].getHealth());
}
else if (characterChoice == "3" || characterChoice == "Goltero") {
cCharacter[0] = existingCharacter[2]; cCharacterSave.setHealth(existingCharacter[2].getHealth());
}
else if (characterChoice == "4" || characterChoice == "Balrogg") {
cCharacter[0] = existingCharacter[3]; cCharacterSave.setHealth(existingCharacter[3].getHealth());
}
else {
cout << "Program Failure....Invaid Input!" << endl;
}
secondFighter();
return;
}
void secondFighter() {
string cFighter;
cout << "***************" << endl;
cout << "* Fighter *" << endl;
cout << "***************" << endl;
cout << "Choose Who To Fight!" << endl;
for (int i = 0, j = 1; i >= 0 && i <= 3; i++, j++) {
cout << j << ": " << existingCharacter[i].getName();
cout << "\t" << "Health: " << existingCharacter[i].getHealth();
cout << "\t" << "Strength: " << existingCharacter[i].getAttack();
cout << "\t" << "Speed: " << existingCharacter[i].getSpeed();
cout << endl;
}
cout << "Enter Selection: ";
if (purposeIgnore >= 1)
cin.ignore();
getline(cin, cFighter);
changeCase(cFighter);
if (cFighter == "1" || cFighter == "Shabu")
cCharacter[1] = existingCharacter[0];
else if (cFighter == "2" || cFighter == "Calil")
cCharacter[1] = existingCharacter[1];
else if (cFighter == "3" || cFighter == "Goltero")
cCharacter[1] = existingCharacter[2];
else if (cFighter == "4" || cFighter == "Balrogg")
cCharacter[1] = existingCharacter[3];
else { cout << "Invalid Input! Program Failure....Please Close and Restart" << endl; }
return;
}
void fightScene() {
int fight_choice;
int i = 0;
int j = 5;
bool win;
if (timesWon >= 1)
j = 6;
while (cCharacter[0].getHealth() > 0 && cCharacter[1].getHealth() > 0) {
newlines();
cout << "\t\t" << cCharacter[0].getName() << " choose ";
if (i == 0)
cout << "an attack.";
else
cout << "another attack.";
do {
cout << "\n\n\t\t<1. Punch / 2. Kick>\n\t\t<3. Slam / 4. Drop kick>";
if (j == 6)
cout << "\n\t\t<5. Items>";
cout << endl << "\t\t";
cin >> fight_choice;
} while (fight_choice <= 0 || fight_choice >= j);
if (fight_choice == 1) {
cCharacter[1].setHealth(cCharacter[1].getHealth() - fightMoves(cCharacter[0].getAttack(), cCharacter[0].getSpeed(), 1));
cout << "\n\t\tYou Punched " << cCharacter[1].getName() << ", his health is now: ";
if (cCharacter[1].getHealth() <= 0)
{
cout << "0" << endl << endl; cCharacter[1].setHealth(-1);
}
else
cout << cCharacter[1].getHealth() << endl << endl;
}
else if (fight_choice == 2) {
cCharacter[1].setHealth(cCharacter[1].getHealth() - fightMoves(cCharacter[0].getAttack(), cCharacter[0].getSpeed(), 2));
cout << "\n\t\tYou Kicked " << cCharacter[1].getName() << ", his health is now: ";
if (cCharacter[1].getHealth() <= 0)
{
cout << "0" << endl << endl; cCharacter[1].setHealth(-1);
}
else
cout << cCharacter[1].getHealth() << endl << endl;
}
else if (fight_choice == 3) {
cCharacter[1].setHealth(cCharacter[1].getHealth() - fightMoves(cCharacter[0].getAttack(), cCharacter[0].getSpeed(), 3));
cout << "\n\t\tYou Slamed " << cCharacter[1].getName() << " on the ground, his health is now: ";
if (cCharacter[1].getHealth() <= 0)
{
cout << "0" << endl << endl; cCharacter[1].setHealth(-1);
}
else
cout << cCharacter[1].getHealth() << endl << endl;
}
else if (fight_choice == 4) {
cCharacter[1].setHealth(cCharacter[1].getHealth() - fightMoves(cCharacter[0].getAttack(), cCharacter[0].getSpeed(), 4));
cout << "\n\t\tYou Drop Kicked " << cCharacter[1].getName() << ", his health is now: ";
if (cCharacter[1].getHealth() <= 0)
{
cout << "0" << endl << endl; cCharacter[1].setHealth(-1);
}
else
cout << cCharacter[1].getHealth() << endl << endl;
}
else if (timesWon >= 1 && fight_choice == 5) { // Bars
use_bar();
}
// Second fighter attack
srand(time(NULL));
int ran_pick = rand() % 5 + 1;
if (cCharacter[1].getHealth() < 0) {
ran_pick = 0;
win = 1;
}
else if (cCharacter[1].getHealth() > 0) {
cout << "\n\t\t<" << cCharacter[1].getName() << "'s turn>" << endl;
win = 0;
}
if (ran_pick == 0)
continue;
else if (ran_pick == 1) {
cCharacter[0].setHealth(cCharacter[0].getHealth() - fightMoves(cCharacter[1].getAttack(), cCharacter[1].getSpeed(), 1));
cout << "\n\t\t" << cCharacter[1].getName() << " punched you! Your health is now: ";
if (cCharacter[0].getHealth() <= 0)
{
cout << "0" << endl << endl; cCharacter[0].setHealth(-1);
}
else
cout << cCharacter[0].getHealth() << endl << endl;
}
else if (ran_pick == 2) {
cCharacter[0].setHealth(cCharacter[0].getHealth() - fightMoves(cCharacter[1].getAttack(), cCharacter[1].getSpeed(), 2));
cout << "\n\t\t" << cCharacter[1].getName() << " kicked you! Your health is now: ";
if (cCharacter[0].getHealth() <= 0)
{
cout << "0" << endl << endl; cCharacter[0].setHealth(-1);
}
else
cout << cCharacter[0].getHealth() << endl << endl;
}
else if (ran_pick == 3) {
cCharacter[0].setHealth(cCharacter[0].getHealth() - fightMoves(cCharacter[1].getAttack(), cCharacter[1].getSpeed(), 3));
cout << "\n\t\t" << cCharacter[1].getName() << " slammed you on the ground! Your health is now: ";
if (cCharacter[0].getHealth() <= 0)
{
cout << "0" << endl << endl; cCharacter[0].setHealth(-1);
}
else
cout << cCharacter[0].getHealth() << endl << endl;
}
else if (ran_pick == 4) {
cCharacter[0].setHealth(cCharacter[0].getHealth() - fightMoves(cCharacter[1].getAttack(), cCharacter[1].getSpeed(), 4));
cout << "\n\t\t" << cCharacter[1].getName() << " drop kicked you! Your health is now: ";
if (cCharacter[0].getHealth() <= 0)
{
cout << "0" << endl << endl; cCharacter[0].setHealth(-1);
}
else
cout << cCharacter[0].getHealth() << endl << endl;
}
else if (ran_pick == 5)
cout << "\t\t" << cCharacter[1].getName() << " missed you! Your health is still: " << cCharacter[0].getHealth() << endl << endl;
if (cCharacter[0].getHealth() > 0) {
cout << "\n\t\t";
system("PAUSE"); // Lets them read the attacks
}
i++; // Increases i to change some wording
}
if (win == 1)
roundWon();
else
characterLost();
return;
}
int fightMoves(int st, int sp, int num) {
srand(time(NULL));
int rand_num;
int addition;
switch (num) {
case 1: {
rand_num = rand() % 40 + 1;
addition = (st + sp) / rand_num;
cout << "\n\t\tDamage inflicted: " << addition;
return addition; break;
}
case 2: {
rand_num = rand() % 20 + 1;
addition = (st + sp) / rand_num;
cout << "\n\t\tDamage inflicted: " << addition;
return addition; break;
}
case 3: {
rand_num = rand() % 30 + 1;
addition = (st + sp) / rand_num;
cout << "\n\t\tDamage inflicted: " << addition;
return addition; break;
}
case 4: {
rand_num = rand() % 30 + 1;
addition = (st + sp) / rand_num;
cout << "\n\t\tDamage inflicted: " << addition;
return addition; break;
}
}
}
int start()
{
while (repeat == 'y' || repeat == 'Y') {
fightScene();
if (repeat == 'y' || repeat == 'Y')
secondFighter();
}
return 0;
}
void roundWon() {
srand(time(NULL));
timesWon++;
purposeIgnore++;
cCharacter[0].setHealth(cCharacterSave.getHealth());
cCharacter[1].setHealth(100);
int item_won = rand() % 3 + 1;
cout << "\t\tYou won!";
cout << "\n\n\t\tYou have been rewarded ";
if (item_won == 1) {
cout << "a small protein bar! (+20 health)";
bars.bar_small++;
}
else if (item_won == 2) {
cout << "a medium protein bar! (+30 health)";
bars.bar_medium++;
}
else if (item_won == 3) {
cout << "a large protein bar! (+40 health)";
bars.bar_large++;
}
cout << "\n\n\t\tItems can be used in game at the cost of a turn.";
cout << "\n\n\t\t";
system("PAUSE"); // Lets them read
int ability_gain[3] = { rand() % 10 + 1, rand() % 10 + 1, rand() % 10 + 1 };
cCharacter[0].setHealth(ability_gain[0] += cCharacter[0].getHealth());
cCharacterSave.setHealth(cCharacter[0].getHealth());
cCharacter[0].setAttack(ability_gain[1] += cCharacter[0].getAttack());
cCharacter[0].setSpeed(ability_gain[2] += cCharacter[0].getSpeed());
cout << "\n\t\tYour health is now: " << cCharacter[0].getHealth();
cout << "\n\t\tYour strength is now: " << cCharacter[0].getAttack();
cout << "\n\t\tYour speed is now: " << cCharacter[0].getSpeed();
cout << "\n\n\t\tWould you like to fight another person? (y/n) ";
cin >> repeat;
return;
}
void characterLost() {
cCharacter[0].setHealth(cCharacterSave.getHealth());
cCharacter[1].setHealth(100);
purposeIgnore++;
cout << "\n\n\t\tYou have lost.";
cout << "\n\t\tWould you like to fight another person? (y/n) ";
cin >> repeat;
return;
}
void use_bar() {
int choose_bar;
char another_bar;
do {
cout << "\n\n\t\tWhich bar would you like to use? ";
cout << "\n\t\t 1: Small Bar: " << bars.bar_small;
cout << "\n\t\t 2: Medium Bar: " << bars.bar_medium;
cout << "\n\t\t 3: Large bar: " << bars.bar_large;
do {
cout << "\n\n\t\tI choose: ";
cin >> choose_bar;
} while (choose_bar <= 0 || choose_bar >= 4);
if (choose_bar == 1 && bars.bar_small >= 1) {
cCharacter[0].setHealth(cCharacter[0].getHealth() + 20);
bars.bar_small--;
cout << "\n\n\t\tYour health is now: " << cCharacter[0].getHealth();
}
else if (choose_bar == 2 && bars.bar_medium >= 1) {
cCharacter[0].setHealth(cCharacter[0].getHealth() + 30);
bars.bar_medium--;
cout << "\n\n\t\tYour health is now: " << cCharacter[0].getHealth();
}
else if (choose_bar == 3 && bars.bar_large >= 1) {
cCharacter[0].setHealth(cCharacter[0].getHealth() + 40);
bars.bar_large--;
cout << "\n\n\t\tYour health is now: " << cCharacter[0].getHealth();
}
else
cout << "\n\t\tNot enough bars!";
cout << "\n\n\t\tWould you like to use another bar? (y/n) ";
cin >> another_bar;
} while (another_bar == 'y' || another_bar == 'Y');
return;
}
void newlines() {
cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
}
void changeCase(string &convert) {
for (int i = 0; convert[i]; i++) {
if (isupper(convert[i]))
convert[i] = tolower(convert[i]);
else
continue;
}
convert.at(0) = toupper(convert.at(0));
return;
}
void bSmith()
{
Blacksmith shopKeeper; //The shop keeper
int responce; //Menu navigation
cout << "*******************************" << endl;
cout << "* Welcome to the Blacksmith *" << endl;
cout << "*******************************" << "\n" << endl;
cout << "*****************************" << endl;
cout << "* 1: Purchase Items *\n";
cout << "* 2: Sell Items *\n";
cout << "* 3: List Your Items *\n";
cout << "* 4: Currency *\n";
cout << "* 5: Exit *\n";
cout << "*****************************" << endl;
do
{
cout << "Enter Option Here: ";
cin >> responce;
switch (responce)
{
case 1:
shopKeeper.buyItem(cCharacter[0]);
cout << endl;
break;
case 2:
cout << "*****************************" << endl;
cout << "* Items To Sell *" << endl;
cout << "*****************************" << endl;
shopKeeper.sellItem(cCharacter[0]);
cout << endl;
break;
case 3:
cout << "*****************************" << endl;
cout << "* Character Inventory *" << endl;
cout << "*****************************" << endl;
cCharacter[0].listInv();
cout << endl;
break;
case 4:
cout << "*****************************" << endl;
cout << "* Current Gold Currency *" << endl;
cout << "*****************************" << endl;
cout << "\t" << cCharacter[0].getCurrency() << endl;
cout << endl;
break;
case 5:
cout << "*****************************" << endl;
cout << "* Thanks for shopping *" << endl;
cout << "*****************************" << endl;
return;
default:
cout << "Please enter valid data." << "\n";
break;
}
cout << "*****************************" << endl;
cout << "* 1: Purchase Items *\n";
cout << "* 2: Sell Items *\n";
cout << "* 3: List Your Items *\n";
cout << "* 4: Currency *\n";
cout << "* 5: Exit *\n";
cout << "*****************************" << endl;
} while (responce != 5);
return;
}
All I can see that sets win is this part of the code,
if (cCharacter[1].getHealth() < 0) {
ran_pick = 0;
win = 1;
}
else if (cCharacter[1].getHealth() > 0) {
cout << "\n\t\t<" << cCharacter[1].getName() << "'s turn>" << endl;
win = 0;
}
However, if cCharacter[1].getHealth()==0, win will be left unset.

error C4700: uninitialized local variable 'enemyHealth' used

So I'm having some trouble figuring out why exactly I'm getting this error.
I've been programming for about a week now and made this VERY simple game.
I just can't figure out why it's spouting off this error.
Any help is appreciated.
#include <iostream>
#include <string>
#include <random>
#include <ctime>
#include <windows.h>
using namespace std;
void battleResults(int enemyHealth);
void battleLoop(int health, int enemyHealth, string selection);
void characterSelection(int health, int enemyHealth, string selection);
int main()
{
// MUH STRINGS
string selection;
string enemy;
// MUH INTS
int health;
int enemyHealth;
cout << "***ULTIMATE COMBAT SIMULATOR***\n";
cout << "***CODED BY OCELOT TOES 2017***\n";
Sleep(1000);
characterSelection(health, enemyHealth, selection);
battleLoop(health, enemyHealth, selection);
battleResults(enemyHealth);
system("PAUSE");
return 0;
}
void characterSelection(int health, int enemyHealth, string selection)
{
string enemy;
cout << "Please choose your race, human or monster!\n";
cin >> selection;
if ((selection == "human") || (selection == "Human"))
{
cout << "***HEALTH***\nHuman = 1000 Monster = 625\n";
cout << "You have higher health, but lower attack!\nYou also deal a
small amount of damage even when blocking.\n";
enemy = "monster";
selection = "human";
health = 1000;
enemyHealth = 625;
}
else if ((selection == "monster") || (selection == "Monster"))
{
cout << "***HEALTH***\nHuman = 1000 Monster = 625\n";
cout << "You have higher attack, but lower health!\n";
enemy = "human";
selection = "monster";
health = 625;
enemyHealth = 1000;
}
else
{
cout << "I'm too lazy to make the game figure out typing errors or just
turds, so now you can exit :)\n";
system("PAUSE");
}
Sleep(1000);
cout << "Okay, so you're a " << selection << ".\n";
Sleep(1000);
cout << "You're fighting a " << enemy << ".\n";
Sleep(1000);
cout << "Let's get this fight started!\n";
}
void battleLoop(int health, int enemyHealth, string selection)
{
// RNG BABY
static mt19937 randomGenerator(time(NULL));
uniform_int_distribution<int> humanAttack(100, 150);
uniform_int_distribution<int> monsterAttack(175, 275);
uniform_real_distribution<float> defenseMultiplier(0.25f, 0.50f);
string uiCombatStatus;
int aCombatStatus;
int damageDealt;
int damageReceived;
while ((health > 0) && (enemyHealth > 0))
{
cout << "What would you like to do?\nAttack or Defend: " << endl;
cin >> uiCombatStatus;
if ((uiCombatStatus == "attack") || (uiCombatStatus == "Attack"))
{
aCombatStatus = 1;
}
else if ((uiCombatStatus == "defend") || (uiCombatStatus == "Defend"))
{
aCombatStatus = 0;
}
if ((aCombatStatus == 1) && (selection == "human"))
{
damageDealt = humanAttack(randomGenerator);
damageReceived = monsterAttack(randomGenerator);
cout << "You chose to attack! You attack for: " << damageDealt <<
".\n";
cout << "The enemy hits you for: " << damageReceived << ".\n";
enemyHealth = enemyHealth - damageDealt;
health = health - damageReceived;
cout << "Enemy's health is at: " << enemyHealth << ".\n";
cout << "Your health is: " << health << ".\n";
}
else if ((aCombatStatus == 0) && (selection == "human"))
{
damageDealt = humanAttack(randomGenerator) - 70;
damageReceived = monsterAttack(randomGenerator) *
defenseMultiplier(randomGenerator);
cout << "You chose to defend! You dealt a small amout of damage: "
<< damageDealt << ".\n";
cout << "The enemy hits you for: " << damageReceived << ".\n";
enemyHealth = enemyHealth - damageDealt;
health = health - damageReceived;
cout << "Enemy's health is at: " << enemyHealth << ".\n";
cout << "Your health is: " << health << ".\n";
}
if ((aCombatStatus == 1) && (selection == "monster"))
{
damageDealt = monsterAttack(randomGenerator);
damageReceived = humanAttack(randomGenerator);
cout << "You chose to attack! You attack for: " << damageDealt <<
".\n";
cout << "The enemy hits you for: " << damageReceived << ".\n";
enemyHealth = enemyHealth - damageDealt;
health = health - damageReceived;
cout << "Enemy's health is at: " << enemyHealth << ".\n";
cout << "Your health is: " << health << ".\n";
}
else if ((aCombatStatus == 0) && (selection == "monster"))
{
damageReceived = humanAttack(randomGenerator) *
defenseMultiplier(randomGenerator);
cout << "You chose to defend!\n";
cout << "The enemy hits you for: " << damageReceived << ".\n";
health = health - damageReceived;
cout << "Enemy's health is at: " << enemyHealth << ".\n";
cout << "Your health is: " << health << ".\n";
}
}
}
void battleResults(int enemyHealth)
{
if (enemyHealth <= 0)
{
cout << "***YOU WIN!***" << endl;
}
else
{
cout << "***YOU LOSE!***" << endl;
}
}
In main, you created an uninitialised variable named enemyHealth, and passed it to a function.
Then, in that function, you gave the resulting copy a value. Then you returned from the function.
Back in main, you're using the old, uninitialised variable again.
Then, you pass it to another function, which attempts to read the value.
However, that value is indeterminate because, contrary to your belief, you never set it!
I think perhaps you intended to pass by reference instead, so it's just the one variable at all times.
This is actually a compiler warning that's been promoted to an error by some setting. But that's good!
By the way, indenting your code will make it so that we can read it without sacrificing life expectancy.

XCode C++ Program not running proper loops

I am having issues with my program and am looking for some help. My program is supposed to randomly choose who gets to go first, the user or the computer. The program does that just fine, when I input the weapon I want to use it does the proper calculations and subtracts the right amount of randomly generated damage from the computer's health and vice versa if the computer gets to go first. Whether it is the user or the computer going first, after you press enter the program just stops. It is supposed to keep going until either the user or the computer's health reaches zero. I was wondering if I could get some assistance as to where my code is preventing this from happening. Any help would be appreciated, I am a novice with the C++ language. Thank you!
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <ctime>
using namespace std;
int main() // Setting the "stage" for the code to follow.
{
int Player_Health = 100; // Creating the necessary variables for the program.
int Comp_Health = 100;
int Turn;
int Weapon_Selection;
int Comp_Weapon;
int Cannon_Dmg;
int Grenade_Dmg;
int Rifle_Dmg;
int Player_Cannon_Ammo = 3;
int Player_Grenade_Ammo = 4;
int Comp_Cannon_Ammo = 3;
int Comp_Grenade_Ammo = 4;
srand(static_cast<unsigned int>(time(0)));
Turn = rand() % 2; // Randomizing who gets to go first.
while(Player_Health >= 0 && Comp_Health >= 0)
{
if(Turn == 0) // Player gets to go first.
{
cout << "You get to go first!\n";
cout << "Select a weapon using number keys 1, 2, or 3.\n";
cout << "1. Cannon\n";
cout << "2. Grenade\n";
cout << "3. Rifle\n";
cout << "\n";
cout << "You select: ";
cin >> Weapon_Selection;
while((Weapon_Selection < 1 || Weapon_Selection > 3) || (Weapon_Selection == 1 && Player_Cannon_Ammo == 0)
|| (Weapon_Selection == 2 && Player_Grenade_Ammo == 0))
{
cout << "Please enter a valid option.\n";
cout << "You select: ";
cin >> Weapon_Selection;
}
switch(Weapon_Selection)
{
case 1: // Player chooses to shoot the cannon.
Cannon_Dmg = 10 + rand() % 6;
Comp_Health = Comp_Health - Cannon_Dmg;
cout << "You caused " << Cannon_Dmg << " damage to your enemy.\n";
cout << "Your health is " << Player_Health << endl;
cout <<" The computer's health is " << Comp_Health << endl;
Player_Cannon_Ammo = Player_Cannon_Ammo - 1;
break;
case 2: // Player chooses to lob a grenade.
Grenade_Dmg = 7 + rand() % 6;
Comp_Health = Comp_Health - Grenade_Dmg;
cout << "You caused " << Grenade_Dmg << " damage to your enemy.\n";
cout << "Your health is " << Player_Health << endl;
cout << "The computer's health is " << Comp_Health << endl;
Player_Grenade_Ammo = Player_Grenade_Ammo - 1;
break;
case 3: // Player chooses to shoot the rifle.
Rifle_Dmg = 3 + rand() % 6;
Comp_Health = Comp_Health - Rifle_Dmg;
cout << "You caused " << Rifle_Dmg << " damage to your enemy.\n";
cout << "Your health is " << Player_Health << endl;
cout << "The computer's health is " << Comp_Health << endl;
break;
}
}
else // Computer gets to go first.
{
Comp_Weapon = rand() % 3;
switch(Comp_Weapon) // Computer randomly selects a weapon.
{
case 1:
Cannon_Dmg = 10 + rand() % 6;
Player_Health = Player_Health - Cannon_Dmg;
cout << "Your enemy used a cannon and caused " << Cannon_Dmg << " damage to you.\n";
cout << "Your health is " << Player_Health << endl;
cout << "The computer's health is " << Comp_Health << endl;
Comp_Cannon_Ammo = Comp_Cannon_Ammo - 1;
break;
case 2:
Grenade_Dmg = 7 + rand() % 6;
Player_Health = Player_Health - Grenade_Dmg;
cout << "Your enemy used a grenade and caused " << Grenade_Dmg << " damage to you.\n";
cout << "Your health is " << Player_Health << endl;
cout << "The computer's health is " << Comp_Health << endl;
Comp_Grenade_Ammo = Comp_Grenade_Ammo - 1;
break;
case 3:
Rifle_Dmg = 3 + rand() % 6;
Player_Health = Player_Health - Rifle_Dmg;
cout << "Your enemy used a rifle and caused " << Rifle_Dmg << " damage to you.\n";
cout << "Your health is " << Player_Health << endl;
cout << "The computer's health is " << Comp_Health << endl;
break;
}
}
if (Comp_Health < 0)
cout << "Congratulations, you beat your enemy!" << endl;
if (Player_Health < 0)
cout << "You have been defeated by your enemy!" << endl;;
cin.ignore(2);
return 0;
}
}
Looks like several issues.
How does Turn get changed from it initial value? Looks like whoever goes first will go until the other player is out of health
rand%3 will return 0,1 or 2. The switch is for 1,2,3. The 0 case is ignored.
The return statement is inside the while loop and the program hangs on the cin.ignore(2) line
I fixed these issue up and the program appears to be more or less working.
--Matt
Move the return statement outside of the while loop.
Using a debugger would catch this.

how to make a continous loop with second while statement

okay here is my code for a game called pig. I having trouble because the code for the computers turn will only got through one time and once the second turn is reached the first line is only printed. is there any soluction to this or am I just screwed?
`int main () {
int humanTurn=0;
int humanTotalScore=0;
int computerTotalScore=0;
int computerTurn=3;
float diceRoll = 0;
int score = 0;
int computerScore = 0;
int answer = 0;
int humanScore = 0;
int pause = 0;
float computerDiceRoll = 0;
srand(time(0));
cout << "Welcome to the game of pig, the first player to reach to 100 wins."<< endl;
cout << "if you roll a one no score will be recorded and your turn will go the computer"<< endl;
cout << " If you choose to hold, the total score accumilated will be recorded" << endl;
while ((humanTotalScore < 100) && (computerTotalScore < 100)) {
cout << endl;
cout << endl;
cout << "press 1 to roll or 2 to save your score: ";
cin >> answer;
for (int i=0; i<1; i++) {
diceRoll = rand() % 6 + 1;
}
if ((diceRoll > 1) && ( answer == 1)){
cout << endl;
cout << endl;
cout << "your current roll is: " << diceRoll << endl;
cout << endl;
cout << endl;
score += diceRoll;
cout << "Score for this turn is: " << score << endl;
cout << "your total score is: " << humanTotalScore << endl;
cout << endl;
cout << endl;
}
else if (answer == 2){
cout << "your score of: " << score << " will be saved" << endl;
humanTotalScore += score;
score = 0;
}
else {
cout << endl;
cout << endl;
cout << "you rolled a ONE. You lose your turn and any points that were with it" <<endl;
cout << endl;
cout << endl;
score = 0;
computerTurn = score;
}
if ((computerTurn == 0) || (answer == 2)){
computerDiceRoll = rand() % 6 + 1;
here is code that is giving me loop problems.
while ((computerDiceRoll > 1)&& (computerScore <= 20)){
if (computerDiceRoll == 1){
computerScore = 0;
computerTurn = 1;
cout << "Computer rolled a ONE, it is now your turn." << endl;
}
computerDiceRoll = rand() % 6 + 1;
cout << endl;
cout << endl;
cout << "computers roll is : " << computerDiceRoll << endl;
cout << endl;
cout << endl;
computerScore += computerDiceRoll;
if (computerScore >20){
computerTotalScore += computerScore;
computerTurn = 1;
}
cout << "computer current score is : " << computerScore << endl;
cout << "computer total score is: " << computerTotalScore << endl;
cout << endl;
cout << endl;
}
}
}
} `