How to Carry Over Depleted Health to the next Loop? - c++

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

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.

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.

Moving object from a stack to an array C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Hey guys so I am writing some coursework and I am almost there, in my code I create a treasure chest and a bag for the player. When the Player is shown the items in the chest they are asked to keep the items which are then stored in there bag or discard the items.
While testing my code I have noticed that the item the player is being shown is not the one that then stores in the bag, almost like the bag is taking from an invisible stack. Then at the end when I call the players bag it still shows as empty as if no items where ever stored????
Please can someone tell me where I am going wrong and how I might resolve it???
These are the specific sections of code that is causing the bug:
void PrintTreasureChest()
{
//TreasureChest A;
int j;
for (j = 1; j < 5; j++)
{
cout << "Item " << j << " in your chest is: " << endl;
cout << "Name:" << (TreasureChest().Chest.top()).Name << endl;
cout << "Rarity out of 3: " << (TreasureChest().Chest.top()).Rarity << endl;
cout << "Part of a set: " << (TreasureChest().Chest.top()).Set << endl;
cout << " " << endl;
PlayerChoice(A);
TreasureChest().Chest.pop();
cout << " " << endl;
}
cout << " " << endl;
cout << "This chest is now empty" << endl;
cout << " " << endl;
cout << " " << endl;
cout << "Items in bag: " << endl;
//Game().ShowRucksack();
return;
}
void PlayerChoice()
{
char Answer;
cout << "If you want to keep the item press Y" << endl;
cout << "If you want to discard the item press N" << endl;
cin >> Answer;
while (Answer == 'Y' || Answer == 'y')
{
cout << "Item stored in your bag" << endl;
StoreItem();
return;
}
while (Answer == 'N' || Answer == 'n')
{
cout << "Item was discared from the Treasure Chest" << endl;
return;
}
while (Answer != 'y' || Answer != 'Y' || Answer != 'N' || Answer != 'n')
{
cout << "To decide press Y for accept OR press N for Decline" << endl;
cin >> Answer;
if (Answer == 'Y' || Answer == 'y') {
cout << "Item stored in your bag" << endl;
//store item in bag
return;
}
else (Answer == 'N' || Answer == 'n'); {
cout << "Item was discared from the Treasure Chest" << endl;
return;
}
return;
}
}
void StoreItem()
{
int dim = 10;
int P = index(Rucksack, dim);
Rucksack[P] = A.Chest.top();
cout << "Item placed in your Bag: " << Rucksack[P].Name << endl;
return;
}
Here is the whole code:
// Loot Class v11.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
#include <stack>
#include <vector>
#define LootNumber 14
using namespace std;
// the 3 arrays initialise the 3 stats of each item
string NameOption[] = { "Stone", "Leather Gloves", "Dragon Gauntlets", "Chair Leg", "Dragon Scale Helmet", "Pebble", "Rusted Breastplate", "Dragon Breastplate", "Empty Bottle", "Chainmail Trousers", "Dragon Skin Trousers", "Broken Stick", "Dagger", "Dragons Sword" };
int RarityOption[] = { 0, 1, 3, 0, 3, 0, 2, 3, 0, 2, 3, 1, 2, 3 };
bool SetOption[] = { 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1 };
// this class is grouping Name, Rarity and Set. Resulting in every Loot object made, contains 3 variables
class Loot
{
public:
string Name;
int Rarity;
bool Set;
// constructor initialises each of the feilds
Loot(string N, int R, bool S)
{
Name = N;
Rarity = R;
Set = S;
}
// default constructor
Loot()
{
Name = "Empty";
Rarity = 0;
Set = false;
}
// Prints a randomly selected item of loot to the screen, used to check randomisation and that all loot variables print in the correct order
void PrintLoot()
{
int i = rand() % LootNumber;
Loot A(NameOption[i], RarityOption[i], SetOption[i]);
cout << "Loot item: " << A.Name << endl;
cout << "Rarity out of 3: " << A.Rarity << endl;
cout << "Part of set: " << A.Set << endl;
}
};
// enables the creation of a container to stack Loot items in
class TreasureChest
{
public:
stack<Loot> Chest;
// stacks 4 random items in the chest
TreasureChest()
{
int i = rand() % LootNumber;
int j = rand() % LootNumber;
int k = rand() % LootNumber;
int h = rand() % LootNumber;
Chest.push(Loot(NameOption[j], RarityOption[j], SetOption[j]));
Chest.push(Loot(NameOption[k], RarityOption[k], SetOption[k]));
Chest.push(Loot(NameOption[i], RarityOption[i], SetOption[i]));
Chest.push(Loot(NameOption[h], RarityOption[h], SetOption[h]));
}
// prints full contents of Treasure Chest to screen
void ShowFullChest()
{
int i;
for (i = 1; i < 5; i++)
{
cout << "Item: " << i << endl;
cout << "Name:" << TreasureChest().Chest.top().Name << endl;
cout << "Rarity out of 3: " << TreasureChest().Chest.top().Rarity << endl;
cout << "Part of a set: " << TreasureChest().Chest.top().Set << endl;
TreasureChest().Chest.pop();
}
}
};
// Creates container for player to store their chosen Loot items
class PlayerRuckSack
{
public:
Loot Rucksack[10];
// default constructor initialising each array
PlayerRuckSack()
{
for (int i = 0; i < 10; i++)
{
Rucksack[i] = { "Empty", 0, false };
}
};
// prints contents of a rucksack to the screen to allow the player to see what they have collected
void ShowRucksack()
{
for (int i = 0; i < 10; i++)
{
cout << Rucksack[i].Name << " " << Rucksack[i].Set << " " << Rucksack[i].Rarity << " " << endl;
}
}
// replaces an each array with items of Loot and prints when all arrays have been replaced
int index(Loot x[], int n)
{
int i = 0;
int index;
while (x[i].Name != "empty" && 0 && false && i < n)
{
i++;
index = i;
return index;
}
while (i == n)
{
cout << "BAG FULL" << endl;
}
}
};
// For runing the game
class Game : public PlayerRuckSack
{
public:
string PlayerName;
TreasureChest A;
Game()
{
PlayerName = "User 1";
}
Game(string U)
{
PlayerName = U;
}
// intro message to start game
void StartGame()
{
cout << "Welcome to the Cave of Luck" << endl;
cout << "What is your name brave warrior" << endl;
cin >> PlayerName;
cout << PlayerName << " There are 3 Treasure Chests in this cave" << endl;
cout << "Treasure Chests contain many different items" << endl;
cout << "However it appears your bag is small and can only hold 10 items in total" << endl;
cout << "Choose wisley " << PlayerName << endl;
cout << "Good Luck!!" << endl;
cout << " " << endl;
cout << " " << endl;
}
//Gives player choise whether to keep or discard each loot item
void PlayerChoice()
{
char Answer;
cout << "If you want to keep the item press Y" << endl;
cout << "If you want to discard the item press N" << endl;
cin >> Answer;
while (Answer == 'Y' || Answer == 'y')
{
cout << "Item stored in your bag" << endl;
StoreItem();
return;
}
while (Answer == 'N' || Answer == 'n')
{
cout << "Item was discared from the Treasure Chest" << endl;
return;
}
while (Answer != 'y' || Answer != 'Y' || Answer != 'N' || Answer != 'n')
{
cout << "To decide press Y for accept OR press N for Decline" << endl;
cin >> Answer;
if (Answer == 'Y' || Answer == 'y') {
cout << "Item stored in your bag" << endl;
//store item in bag
return;
}
else (Answer == 'N' || Answer == 'n'); {
cout << "Item was discared from the Treasure Chest" << endl;
return;
}
return;
}
}
// Prints the top of TreasureChest to the screen plus uses Playerchoise() after each item is shown
void PrintTreasureChest()
{
//TreasureChest A;
int j;
for (j = 1; j < 5; j++)
{
cout << "Item " << j << " in your chest is: " << endl;
cout << "Name:" << (TreasureChest().Chest.top()).Name << endl;
cout << "Rarity out of 3: " << (TreasureChest().Chest.top()).Rarity << endl;
cout << "Part of a set: " << (TreasureChest().Chest.top()).Set << endl;
cout << " " << endl;
PlayerChoice(A);
TreasureChest().Chest.pop();
cout << " " << endl;
}
cout << " " << endl;
cout << "This chest is now empty" << endl;
cout << " " << endl;
cout << " " << endl;
cout << "Items in bag: " << endl;
//Game().ShowRucksack();
return;
}
// informs player another chest is coming
void NextChest()
{
cout << "Your next chest contains: " << endl;
cout << " " << endl;
}
// Prints end Game message
void EndGame()
{
cout << " " << endl;
cout << " " << endl;
cout << "You have opened all the Chests, come back soon to the Cave of Treasures" << endl;
cout << " THANKYOU FOR PLAYING" << endl;
}
void StoreItem()
{
int dim = 10;
int P = index(Rucksack, dim);
Rucksack[P] = A.Chest.top();
cout << "Item placed in your Bag: " << Rucksack[P].Name << endl; //B.Rucksack[P].Set << B.Rucksack[P].Rarity << endl;
return;
}
};
int main()
{
Game A;
//TreasureChest A;
PlayerRuckSack B;
//A.StartGame();
srand(time(NULL));
A.PrintTreasureChest();
for (int i = 0; i < 10; i++)
{
cout << B.Rucksack[i].Name << " " << B.Rucksack[i].Set << " " << B.Rucksack[i].Rarity << " " << endl;
}
//A.NextChest();
A.EndGame();
//TreasureChest A;
//PlayerRuckSack B;
//int dim = 10;
//int P = index(B.Rucksack, dim);
//B.Rucksack[P] = A.Chest.top();
//cout << "Item in your Bag " << B.Rucksack[P].Name << B.Rucksack[P].Set << B.Rucksack[P].Rarity << endl;
//cout << P << endl;
return 0;
}
I know why nothing is stored in your Rucksack
int index(Loot x[], int n)
{
int i = 0;
int index;
while (x[i].Name != "empty" && 0 && false && i < n)
{
i++;
index = i;
return index;
}
while (i == n)
{
cout << "BAG FULL" << endl;
}
}
Take a careful look at this line:
while (x[i].Name != "empty" && 0 && false && i < n)
&& 0 && false? Both 0 and false mean this is always false and the Rucksack will be reported as empty no matter what.
Then the code will fall out the bottom of index() without returning a value.
After that program behaviour is undefined because you use a return value that was not returned. Any craziness might come after that.
Fix that and come back with another question if you can't figure out your other problem.
It is currently a bit vague.

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.

Why Do I have an '=' sign output and 2 smiley faces instead of the correct output? C++

this is an update to show chages, details below.
here is a link to snap shot of output
https://dl.dropboxusercontent.com/u/34875891/wrongoutput.PNG
#include <iostream>
#include <iomanip>
#include <string>
#include <cstring>
using namespace std;
//create HotelRoom class
class HotelRoom
{
private:
char* ptr_guest;
char room_number[3];
int room_capacity;
int occupancy_status;
double daily_rate;
public:
HotelRoom(char roomNumber[], int roomCapacity, double roomRate, char* ptr_name, int occupancyStatus);
~HotelRoom();
void Display_Number();
void Display_Guest();
int Get_Capacity();
int Get_Status();
double Get_Rate();
int Change_Status(int);
double Change_Rate(double);
};
HotelRoom::HotelRoom(char roomNumber[], int roomCapacity, double roomRate, char* ptr_name, int occupancyStatus)
{
strcpy(room_number, roomNumber);
room_capacity = roomCapacity;
daily_rate = roomRate;
ptr_guest = new char[strlen(ptr_name) + 1];
strcpy(ptr_guest, ptr_name);
occupancy_status = occupancyStatus;
}
HotelRoom::~HotelRoom()
{
cout << endl;
cout << "Destructor Executed";
cout << endl;
delete [] ptr_guest;
}
void HotelRoom::Display_Guest()
{
char* temp = ptr_guest;
while(*temp != '\0')
cout << *temp++;
}
void HotelRoom::Display_Number()
{
cout << room_number;
}
int HotelRoom::Get_Capacity()
{
return room_capacity;
}
int HotelRoom::Get_Status()
{
return occupancy_status;
}
double HotelRoom::Get_Rate()
{
return daily_rate;
}
int HotelRoom::Change_Status(int roomStatus)
{
if(roomStatus <= room_capacity )
{
occupancy_status = roomStatus;
return occupancy_status;
}
else
occupancy_status = -1;
}
double HotelRoom::Change_Rate(double newRate)
{
daily_rate = newRate;
return daily_rate;
}
int main()
{
cout << setprecision(2)
<< setiosflags(ios::fixed)
<< setiosflags(ios::showpoint);
//Declare variables to hold data
char roomNumber[3] = {'1','3','\0'};
char guestName[20];
double roomRate = 89.00;
int roomCapacity = 4;
int occupancyStatus = 0;
int status;
int checkOut;
int newCustomer;
//Ask for user input
cout << "What is the guest's name: ";
cin.getline(guestName, 20);
cout << endl;
cout << "How many guests will be staying in the room: ";
cin >> status;
HotelRoom HotelRoom1(roomNumber, roomCapacity, roomRate, guestName, status);
//Display Rooom information
cout << endl;
cout << endl;
if(HotelRoom1.Change_Status(status))
{
cout << endl;
cout << "Guest's Name: ";
HotelRoom1.Display_Guest();
cout << endl;
cout << endl;
cout << "The capacity of this room is " << HotelRoom1.Get_Capacity() << endl;
cout << endl;
cout << "There are " << HotelRoom1.Get_Status() << " guests staying in the room";
}
cout << endl;
cout << endl;
cout << "Your room number is " << HotelRoom1.Display_Number();
cout << endl;
cout << endl;
cout << "The rate for this room is " << HotelRoom1.Get_Rate();
cout << endl;
cout << endl;
//chech this guest out?
cout << "Check this guest out? ('1 = yes' '0' = no) ";
cin >> checkOut;
switch(checkOut)
{
case 1:
HotelRoom1.Change_Status(0);
for(int i = 0; i < 3; ++i )
{
cout << endl;
}
cout << "You have checked out of room number " << HotelRoom1.Display_Number();
cout << endl;
cout << endl;
cout << "The capacity of this room is " << HotelRoom1.Get_Capacity();
cout << endl;
cout << endl;
cout << "There are currently " << HotelRoom1.Get_Status() << " occupants";
cout << endl;
cout << endl;
cout << "The rate of this room was " << HotelRoom1.Get_Rate();
break;
}
//check in new guest?
cout << endl;
cout << endl;
cout << "Check in new guest? ('1 = yes' '0' = no) ";
cin >> newCustomer;
for(int i = 0; i < 3; ++i )
{
cout << endl;
}
switch (newCustomer)
{
case 1:
HotelRoom HotelRoom2(roomNumber, roomCapacity, roomRate, guestName, status);
HotelRoom1.Change_Rate(175.00); //Change rate of room
cout << endl;
cout << "What is the guest's name: ";
cin.getline(guestName, 20);
cout << endl;
cout << "How many guests will be staying in the room: ";
cin >> status;
cout << endl;
cout << endl;
//Display new guest information
if(HotelRoom1.Change_Status(status))
{
cout << endl;
cout << endl;
cout << "The capacity of this room is " << HotelRoom1.Get_Capacity() << endl;
cout << endl;
cout << "There are " << HotelRoom1.Get_Status() << " guests staying in the room";
}
cout << endl;
cout << endl;
cout << "Your room number is " << HotelRoom1.Display_Number();
cout << endl;
cout << endl;
cout << "The rate for this room is " << HotelRoom1.Get_Rate();
cout << endl;
cout << endl;
break;
}
cout << endl;
system("PAUSE");
return 0;
}
this is an update to show chages, details below.
here is a link to snap shot of output
https://dl.dropboxusercontent.com/u/34875891/wrongoutput.PNG
char HotelRoom::Display_Guest()
{
cout << ptr_guest;
}
string HotelRoom::Display_Number()
{
cout << room_number;
}
int HotelRoom::Change_Status(int roomStatus)
{
if(roomStatus <= room_capacity )
{
occupancy_status = roomStatus;
return occupancy_status;
}
else
occupancy_status = -1;
}
These functions claim to be returning values. The first two are not, the last is not under certain conditons. Calling the first two is undefined behavior. Calling Change_Status with roomStatus > room_capacity is also undefined behavior.
There may be other problems with the code, but the elephant in the room is the undefined behavior. Any other debugging while you have undefined behavior is theoretically a waste of time.