error C4700: uninitialized local variable 'enemyHealth' used - c++

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.

Related

code for a simple fighting game but after a player health becomes 0 game continues its loop

so this is the entire code, it has a display function which does the displaying and processing of inputs and a main function which passes the display when the GameOver function is set to false
#include <iostream>
#include <conio.h>
#include <stdlib.h>
#include <cstdlib>
#include <ctime>
#define key_x 88
using namespace std;
bool GameOver = false;
void Display() {
int choose;
char ch;
system("color 04");
cout << "WELCOME" << endl;
for (int i = 1; i < 5; i++) {
cout << "Character " << i << endl;
}
cout << "choose character number: ";
cin >> choose;
if (choose > 4) {
cout << "Enter valid character number: ";
cin >> choose;
}
cout << "Selected Character is " << choose << endl;
system("pause");
system("cls");
srand((unsigned)time(0));
int random = (rand() % 4) + 1;
system("color 02");
cout << "ENEMY IS CHARACTER " << random << endl;
int hp1 = 100;
int hp2 = 100;
cout << "Character " << choose << "(" << hp1 << ")" << " VS. Character " << random << "(" << hp2 << ")" << endl;
while(!GameOver)
{
srand(time(0));
int rand1 = (rand() % 100) + 1;
int rand2 = (rand() % 100) + 1;
int NewHp1 = hp1 - rand1;
int NewHp2 = hp2 - rand2;
cout << "Press any key to attack" << endl;
ch = (_getch());
int value = ch;
while (value == key_x)
break;
cout << "Enemy has " << NewHp2 << " health left." << endl;
system("pause");
cout << "You have " << NewHp1 << " health left." << endl;
if (NewHp2 <= 0) {
cout << "YOU WIN!!" << endl;
break;
GameOver = true;
}
else if (NewHp1 <= 0) {
system("color 04");
cout << "YOU LOSE" << endl;
break;
GameOver = true;
}
else
{
continue;
}
}
}
int main() {
while(!GameOver)
Display();
}
after the hp goes below 0 the game just seems to continue taking the hp as 100 and restart, could anyone help me resolve this issue.
I know this code is slightly messy, I have just started learning cpp
break;
GameOver = true;
When the break is encountered, it breaks, so GameOver = true; doesn't run. Remove the break.
else
{
continue;
}
is superfluous. There's nothing left to run in this loop, so it will continue anyway. Remove this else block too.
And lastly, you forgot to update hp1 and hp2 with NewHp1 and NewHp2:
hp1 = NewHp1;
hp2 = NewHp2;
just before the end of the loop.

Accessing Class objects to compare with global variables

Im making a text store menu. I have a basic weapon class with a string for name and weapon sound, a bool for if you already own the item or not and a double for the price.
I'm trying to compare the double price in the class to the global variable p_balance (players balance) to
check if the player can afford the item
Here's the class
class Weapon
{
public:
string name, sound;
bool owned = false;
double price;
public:
Weapon() //Default Constructor
{
name = "name";
sound = "sound";
owned = owned;
price = 0;
}
Weapon(string i_name, string i_sound, bool i_owned, double i_price)//Constructor
{
name = i_name;
sound = i_sound;
owned = i_owned;
price = i_price;
void displayItems();
{
cout << name << " - " << price << "g." << endl;
}
}
};
(i know i know i should switch Weapon Weapons[i] to Weapon weapons[i] to make my life easier)
And here's my most recent attempt at accessing it
while (p_balance < Weapons[0].getPrice()) // Not enough gold
{
cout << "Sorry, it seems you don't have enough gold." << endl;
goto MainMenu;
}
I had tried to make a method within the class to get the price but that didnt work out, but thats why its calling on a method that doesnt exist
I've also toyed around with if loops but the were getting messy and displaying more info than i liked
After the owner money check, i have it perform a ownership check and check if something equipped to that items slot, but when I used nested if statements it displayed the result of all of them even if the first if (price) was failed so I figured maybe a while statement?
I'm not looking for the answer cause I want to learn but last time I posted here I got some great hints that really helped me out and I'm hitting the point of frustration with this so I figured I'd ask for help!
EDIT:
I took what you guys said into account and went back to the pseudo.
I'm quite pleased with how it is now:
#include <iostream>
#include <string>
using namespace std;
int p_choice;
double p_balance = 125;
//Simple Weapon Class
class Weapon
{
public:
int slot;
string name, sound;
bool owned = false;
double price;
public:
Weapon() //Default Constructor
{
slot = 0;
name = "name";
sound = "sound";
owned = owned;
price = 0;
}
Weapon(int i_slot, string i_name, string i_sound, bool i_owned, double i_price)//Constructor
{
slot = i_slot;
name = i_name;
sound = i_sound;
owned = i_owned;
price = i_price;
double* p_ptr;
p_ptr = &price;
void displayItems();
{
int x = 0;
cout << slot << " - " << name << " - " << price << "g." << endl;
}
}
};
int main()
{
int p_selection;
bool hasWeapon, offHand, inStore;
hasWeapon = false;
offHand = false;
inStore = true;
//Weapon Array
cout << "---------------------------------------------" << endl;
Weapon Weapons[6];
Weapons[0] = Weapon(1, "Great Sword of Greatening", "Tssng", false, 50);
Weapons[1] = Weapon(2, "Claw", "Thwack", false, 10);
Weapons[2] = Weapon(3, "Silent Pea-shooter", "Pew Pew", false, 15);
Weapons[3] = Weapon(4, "Loudening Silencer Attachment", "...", false, 5);
Weapons[4] = Weapon(5, "Tiger-Repelling Rock ", "Meooowraaarah", false, 25);
Weapons[5] = Weapon(6, "The Stick of Truth", "How do you kill that which has no life", false, 100);
cout << "---------------------------------------------" << endl;
cout << "Welcome to my store, traveller!" << endl;
cout << "How can I help you?" << endl;
//Menu
do
{
cout << "1. Buy" << endl;
cout << "2. Check Balance" << endl;
cout << "3. Exit" << endl;
cin >> p_choice;
if (p_choice == 1)
{
//Ask player which weapon the want to buy
cout << "Which item are you interested in?" << endl;
cout << "(Choose using 1-6)" << endl;
cin >> p_selection;
if (p_selection >= 1 && p_selection <= 6)
{
int i_choice = p_selection - 1;// Take one off the choice so it corresponds correctly to the object in the array
if (Weapons[i_choice].owned == false && p_balance >= Weapons[p_selection].price)// check if item is owned/can be bought
{
if (hasWeapon == false)// flip "Slot" flag
{
hasWeapon = true;
}
Weapons[i_choice].owned = true;// flip ownership flag
p_balance = p_balance - Weapons[i_choice].price; // update balance
cout << "Good eye, that's a fine item! Enjoy your " << Weapons[i_choice].name << endl;
}
else if (Weapons[i_choice].price > p_balance)
{
cout << "Seems you're a little short on gold..." << endl;
}
else if (Weapons[i_choice].owned == true)
{
cout << "Seems you don't know how to dual wield, why don't you pick something else." << endl;
}
}
}
// Check Balance
if (p_choice == 2)
{
cout << "Your balance is: " << p_balance << "g." << endl;
}
// Leave
if (p_choice == 3 && inStore == true)
{
cout << "Thanks for stopping by! Good luck out there!" << endl;
inStore = false;
}
else if (p_choice == 3 && hasWeapon == false)
{
cout << "You're gonna want a weapon out there, traveller" << endl;
}
} while (inStore == true);
//Scenario
bool scenario = true;
cout << "Inventory" << endl;
for (int x = 0; x < 6; x++)
{
if (Weapons[x].owned == true)
{
//convey slot
cout << "Press " << Weapons[x].slot << " to use your " << Weapons[x].name << endl;
cin >> p_choice;
}
}
do
{
for (int y = 0; y < 1; y++)
{
int use = p_choice - 1;
if (Weapons[use].owned == true)
{
cout << Weapons[use].sound << endl;
}
}
} while (scenario == true);
system("pause");
return 0;
}
Only issue is it plays the "sound" nonstop, that for loop was an attempt to have it run 1 time lol
Here's the final final product
#include <iostream>
#include <string>
using namespace std;
int p_choice;
double p_balance = 125;
//Simple Weapon Class
class Weapon
{
public:
int slot, durability;
string name, sound;
bool owned = false;
double price;
public:
Weapon() //Default Constructor
{
slot = 0;
name = "name";
sound = "sound";
owned = owned;
price = 0;
durability = 0;
}
Weapon(int i_slot, string i_name, string i_sound, bool i_owned, double i_price, int i_durability)//Constructor
{
slot = i_slot;
name = i_name;
sound = i_sound;
owned = i_owned;
price = i_price;
durability = i_durability;
void displayItems();
{
int x = 0;
cout << slot << " - " << name << " - " << price << "g." << endl;
}
}
};
int main()
{
int p_selection;
bool hasWeapon, offHand, inStore;
hasWeapon = false;
offHand = false;
inStore = true;
//Weapon Array
cout << "---------------------------------------------" << endl;
cout << "For Sale:" << endl;
Weapon Weapons[6];
Weapons[0] = Weapon(1, "Great Sword of Greatening", "Tssng", false, 50, 25);
Weapons[1] = Weapon(2, "Claw", "Thwack", false, 10, 15);
Weapons[2] = Weapon(3, "Silent Pea-shooter", "Pew Pew", false, 15, 20);
Weapons[3] = Weapon(4, "Loudening Silencer Attachment", "...", false, 5, 5);
Weapons[4] = Weapon(5, "Tiger-Repelling Rock ", "Meooowraaarah", false, 25, 30);
Weapons[5] = Weapon(6, "The Stick of Truth", "How do you kill that which has no life", false, 100, 50);
cout << "---------------------------------------------" << endl;
cout << "Welcome to my store, traveller!" << endl;
cout << "How can I help you?" << endl;
//Menu
do
{
cout << "1. Buy" << endl;
cout << "2. Check Balance" << endl;
cout << "3. Exit" << endl;
cin >> p_choice;
if (p_choice == 1)
{
//Ask player which weapon the want to buy
cout << "Which item are you interested in?" << endl;
cout << "(Choose using 1-6)" << endl;
cin >> p_selection;
if (p_selection >= 1 && p_selection <= 6)
{
int i_choice = p_selection - 1;// Take one off the choice so it corresponds correctly to the object in the array
if (Weapons[i_choice].owned == false && p_balance >= Weapons[p_selection].price)// check if item is owned/can be bought
{
if (hasWeapon == false)// flip weapon flag
{
hasWeapon = true;
}
Weapons[i_choice].owned = true;// flip ownership flag
p_balance = p_balance - Weapons[i_choice].price; // update balance
cout << "Good eye, that's a fine item! Enjoy your " << Weapons[i_choice].name << endl;
}
else if (Weapons[i_choice].price > p_balance)
{
cout << "Seems you're a little short on gold..." << endl;
}
else if (Weapons[i_choice].owned == true)
{
cout << "Seems you don't know how to dual wield, why don't you pick something else." << endl;
cout << "(You already own this item)" << endl;
}
}
}
// Check Balance
if (p_choice == 2)
{
cout << "Your balance is: " << p_balance << "g." << endl;
}
// Leave
if (p_choice == 3 && inStore == true)
{
cout << "Thanks for stopping by! Good luck out there!" << endl;
inStore = false;
}
else if (p_choice == 3 && hasWeapon == false)
{
cout << "You're gonna want a weapon out there, traveller" << endl;
}
} while (inStore == true);
//Scenario
bool scenario, equipped;
int attack, equip, choose;
equipped = false;
scenario = true;
do
{
Equip:
cout << "----------------------------------------------------" << endl;
cout << " Inventory" << endl;
for (int x = 0; x < 6; x++)
{
if (Weapons[x].owned == true)
{
//convey slot and display equippable items
cout << Weapons[x].slot << " - " << Weapons[x].name << " - Uses Left: " << Weapons[x].durability << endl;
}
}
cout << "----------------------------------------------------" << endl;
cout << endl;
cout << "What would you like to equip? (Select using the given number + Enter)" << endl;
cout << "(Press 9 to quit)" << endl;
cin >> choose;
equip = choose - 1;
if (choose == 9)
{
scenario = false;
}
else if (Weapons[equip].owned == true)
{
int action;
cout << "You have equipped " << Weapons[equip].name << endl;
Action:
cout << "Press 1 and Enter to use." << endl;
cout << "Press 2 and Enter to equip a new item" << endl;
cout << "Press 3 and Enter to go home" << endl;
cin >> action;
if (Weapons[equip].durability <= 0)// cant use broken items
{
cout << "That item appears to have broken!" << endl;
}
else if (action == 1 && Weapons[equip].durability >= 0)// attack and durability check
{
cout << Weapons[equip].sound << endl;
cout << endl;
Weapons[equip].durability--;// durability decrement
goto Action;
}
else if (action == 2)// change equip
{
goto Equip;
}
else if (action == 3)// exit
{
scenario = false;
}
}
} while (scenario == true);
cout << endl;
cout << "I wish you a safe journey home, traveller." << endl;
system("pause");
return 0;
}
Thanks again for the guidance.

How to Carry Over Depleted Health to the next Loop?

I have this program where instantiate player character, enemy characters, and their weapoons. The player characters choose who to attack, and the enemies attack the players at random. They have have their own health, positions, and weapon damage set at random. I also have a Weapon function dodamage(), which decreases the player's healthpoints by weapon damage. In main(), I set a while(true) loop where each character attacks and depletes health. The problem is each loop after the first, the health, and damage are the same as the beginning. They never change after the first loop. I was wondering how I could carry resulting damage over to the next loop until health reaches <=0.
Main.cpp
void playerAttack(Character c1, Character c2, Weapon w, string target)
{
if (target == "1")
{
w.DoDamage(c1.healthPoints, w.Damage);
if (c1.healthPoints <= 0)
c1.die();
}
else if (target == "2")
{
w.DoDamage(c2.healthPoints, w.Damage);
if (c2.healthPoints <= 0)
c2.die();
}
}
void enemyAttack(Character c1, Character c2, Weapon w)
{
srand(time(NULL));
int randTarget = rand() % 2 + 1;
if (randTarget = 1)
{
w.DoDamage(c1.healthPoints, w.Damage);
if (c1.healthPoints <= 0)
c1.die();
}
else if (randTarget = 2)
{
w.DoDamage(c1.healthPoints, w.Damage);
if (c2.healthPoints <= 0)
c2.die();
}
}
int main()
{
PlayerCharacter p1, p2;
EnemyCharacter e1, e2;
Weapon p1W = p1.currentWeapon;
Weapon p2W = p2.currentWeapon;
Weapon e1W = e1.currentWeapon;
Weapon e2W = e2.currentWeapon;
string enemyTarget, playerTarget;
p1.printCharacter();
p2.printCharacter();
e1.printCharacter();
e2.printCharacter();
while (true)
{
cout << "Player One. Choose your Target (1 or 2)" << endl;
cin >> playerTarget;
playerAttack(e1, e2, p1W, playerTarget);
cout << "Enemy One Attacks" << endl;
enemyAttack(p1, p2, e1W);
cout << "Player Two. Choose your Target (1 or 2)" << endl;
cin >> playerTarget;
playerAttack(e1, e2, p2W, playerTarget);
cout << "Enemy Two Attacks" << endl;
enemyAttack(p1, p2, e2W);
}
if (p1.isDead && p2.isDead)
cout << "Game Over!" << endl;
else if (e1.isDead && e2.isDead)
cout << "You Win!" << endl;
system("pause");
return 0;
}
Weapon.cpp
void Weapon::printWeapon()
{
srand(time(NULL));
cout << "Weapon: " << WeaponType[randomName] << endl;;
cout << "Type: " << object->WeaponName[randomType] << endl;
cout << "Damage: " << Damage << endl;;
}
int Weapon::DoDamage(int health, int damage)
{
int resultHealth = health - damage;
cout << "Damage - " << damage << endl;
cout << "Health: " << resultHealth << endl << endl;
health = resultHealth;
return health;
}
Character.cpp (Base class fro playercharacter and enemycharacter)
Character::Character()
{
srand(time(NULL));
populatePosition(3);
}
void Character::printCharacter()
{
srand(time(NULL));
healthPoints = rand() % 100;
cout << "Enter First Name" << endl;
cin >> firstName;
cout << "Enter Last Name" << endl;
cin >> lastName;
cout << endl;
cout << firstName << " " << lastName << ": " << endl;
cout << "Health: " << healthPoints << endl;
cout << "Position: "<<endl;
for (auto p:position)
{
cout << p << ", " << endl;
}
cout << endl;
}
void Character::populatePosition(int vectorSize)
{
for (int i = 0; i < vectorSize; i++)
{
f = rand() % 20;
position.push_back(f);
}
}
void Character::die()
{
cout << firstName << " " << lastName << " is dead " << endl << endl;
isDead = true;
}
The issue is that DoDamage never updates anything outside of it's scope.
You're passing health by value, so the results of DoDamage never get used. You're also not catching the results of the return value, which could also be used to update the value.
To fix it, either A, make the heath parameter of DoDamage be pass by reference
int Weapon::DoDamage(int & health, int damage)
{
int resultHealth = health - damage;
cout << "Damage - " << damage << endl;
cout << "Health: " << resultHealth << endl << endl;
health = resultHealth;
return health;
}
references are basically like pointers to data, but you don't have to remember to dereference them, the compiler will remember that for you. You just have to remember that the value coming in is at the same address as the value that you're working with.
Or B, use the value being returned to re-assign the healthpoints of the character in the attack functions.
e.g:
w.DoDamage(c1.healthPoints, w.Damage);
could look like:
c1.healthPoints = w.DoDamage(c1.healthPoints, w.Damage);

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

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.

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.