C++ returning value from function - c++

I'm trying to return a value from a function but all it return is the value 1.
It's suppose to have 5 arguments in the computeCivIndex(), even if I hard coded the values the output I receive would still be 1.
Why is this so ?
float LocationData::computeCivIndex()
{
civNum1 = 45.0 / 100;
civNum2 = 20 + 50;
civNum3 = civNum2 / 200;
civNum4 = civNum1 - civNum3;
civNum5 = 5 + 10;
return civNum;
}
//display data
void LocationData::displaydata()
{
cout << "CIV value: " << computeCivIndex << endl;
}

You miss () in cout << "CIV value: " << computeCivIndex() << endl;.
For importance of braces you can check this link.

cout << "CIV value: " << computeCivIndex << endl;
seems to be printing the value of the function (not the return value). You need to put the function brackets in:
cout << "CIV value: " << computeCivIndex() << endl;

//convert sunType to sunTypePercentage
float LocationData::computeCivIndex(string st, int earth, int moons, float particle, float plasma)
{
float sunTypePercent;
if(st == "Type 0")
{
sunTypePercent = 80.0;
}
else if(st == "Type B")
{
sunTypePercent = 45.0;
}
else if(st == "Type A")
{
sunTypePercent = 60.0;
}
else if(st == "Type F")
{
sunTypePercent = 75.0;
}
else if(st == "Type G")
{
sunTypePercent = 90.0;
}
else if(st == "Type K")
{
sunTypePercent = 80.0;
}
else if(st == "Type M")
{
sunTypePercent = 70.0;
}
// calculate CIV Value
float civNum,civNum1,civNum2,civNum3,civNum4,civNum5;
civNum1 = sunTypePercent / 100;
civNum2 = plasma + particle;
civNum3 = civNum2 / 200;
civNum4 = civNum1 - civNum3;
civNum5 = earth + moons;
civNum = civNum4 * civNum5;
return civNum;
}
//display data
void LocationData::displaydata()
{
cout << "suntype: " << sunType << endl;
cout << "earth: " << noOfEarthLikePlanets << endl;
cout << "moons: " << noOfEarthLikeMoons << endl;
cout << "particle: " << aveParticulateDensity << endl;
cout <<"density: " << avePlasmaDensity << endl;
cout << "CIV value: " << computeCivIndex()<< endl;
}
This is the actual code which i'm having problem with. For the computeCivIndex() function it is actually a static under the public LocationData class in my LocationData.h file which look something like this.
static float compute CivIndex(string st, int earth, int moons, float particle, float plasma);
so in order to retrieve the value from the function should I do this instead?
cout << "CIV value: " << LocationData.computeCivIndex() << endl;

Related

Shapes and their point ids. Shape ids are different but point ids are consecutively incremented

Requirement:
Shape ID: 0 (say rectangle)
Point IDs in rectangle: 0, 1, 2 and 3.
Shape ID: 1 (say square)
Point IDs in square: 0, 1, 2 and 3.
I wrote a code by for creating a shape and adding points to each shape. Classes Shape and LBP are defined.
Problem:
The point IDs are not starting from '0' in shape 1. Ideally, the point IDs in shape 1 (square )should start from 0 rather than 1. I feel that is the program appending the newly created point to the point set of the previous shape object i.e. shape 0 (rectangle).
Shape ID: 0 (say rectangle)
Point IDs: 0
Shape ID: 1 (say square)
Point IDs: 1
Question: How to make the point ids start from '0' for every new shape created?
The classes defined are as shown below.
MasterDefine.h
#include<iostream>
using namespace std;
class LBP
{
private:
double x, y;
int pointID;
static int pointCount;
public:
void setLBP(double, double);
void getLBP(double&, double&);
void addLBPatEnd();
void addLBPatLocation();
void delLBPatEnd();
void delLBPatLocation(int);
void setLBPID();
int getLBPID();
void goToNode(int);
int getNoOfPoints();
LBP(double, double);
~LBP();
LBP* next, * prev;
};
class Shape
{
private:
int shapeID;
static int shapeCount;
public:
void setShapeID();
int getShapeID();
LBP* points;
Shape();
};
Main.cpp
#include"MasterDefine.h"
int LBP::pointCount = 0;
int Shape::shapeCount = 0;
LBP* lbp, *firstPt, *lastPt;
void printLBPForward();
void printLBPReverse();
void delLBP(int);
void delAllLBPs();
int main()
{
cout << endl << "Hello world" << endl;
Shape* shape0 = new Shape;
cout << endl << "Shape id is " << shape0->getShapeID() << endl; //gives id of shape0
LBP* s0p0 = new LBP(22, 33); //point 0 of shape 0
shape0->points = s0p0;
Shape* shape1 = new Shape;
cout << endl << "Shape id is " << shape1->getShapeID() << endl; //gives id of shape1
LBP* s1p0 = new LBP(10, 5);//point 0 of shape 1
shape1->points = s1p0;
cout << endl << "point id is " << s1p0->getLBPID() << endl;
return 1;
}
LBP.cpp
#include"MasterDefine.h"
//#include "LBP.h"
LBP* lbpFirst, *lbpLast;
void LBP::getLBP(double& getX, double& getY)
{
getX = x;
getY = y;
}
void LBP::addLBPatEnd()
{
// cout << endl << "add lbp at end " << endl;
// cout << endl << "Pointer value in member function " << this << endl;
LBP* tempNode;
if (getNoOfPoints() == 1)
{
tempNode = this;
tempNode->next = NULL;
tempNode->prev = NULL;
lbpFirst = tempNode;
}
if (getNoOfPoints() == 2)
{
tempNode = this;
lbpFirst->next = tempNode;
lbpFirst->prev = tempNode;
tempNode->next = tempNode->prev = lbpFirst;
lbpLast = tempNode;
}
if (getNoOfPoints() > 2)
{
tempNode = this;
lbpLast->next = tempNode;
tempNode->next = lbpFirst;
lbpFirst->prev = tempNode;
tempNode->prev = lbpLast;
lbpLast = tempNode;
}
//goToNode();
}
void LBP::delLBPatEnd()
{
LBP* tempNodeDel;
tempNodeDel = lbpFirst;
do
{
tempNodeDel = tempNodeDel->next;
} while (tempNodeDel->getLBPID() != pointCount - 2);
cout << endl << "tempNodeDel id is " << tempNodeDel->getLBPID() << endl;
tempNodeDel->next = lbpFirst;
lbpFirst->prev = tempNodeDel;
}
void LBP::delLBPatLocation(int NodePos)
{
LBP* TempNodePosDel, *TempNodePosDelPrev, *TempNodePosDelNext;
TempNodePosDel = lbpFirst;
do
{
TempNodePosDel = TempNodePosDel->next;
} while (TempNodePosDel->getLBPID() != NodePos);
cout<<endl<<"NodeID that is to be deleted is "<<TempNodePosDel->getLBPID()<<endl;
cout << endl << "TempNodePosDel" << TempNodePosDel << endl;
TempNodePosDelPrev = TempNodePosDel->prev;
TempNodePosDelNext = TempNodePosDel->next;
cout << endl << "TempNodePosDelPrev id is " << TempNodePosDelPrev->getLBPID() << endl;
cout << endl << "TempNodePosDel id is " << TempNodePosDel->getLBPID() << endl;
cout << endl << "TempNodePosDelNext id is " << TempNodePosDelNext->getLBPID() << endl;
TempNodePosDelPrev->next = TempNodePosDelNext;
TempNodePosDelNext->prev = TempNodePosDelPrev;
cout << endl << "************************************" << endl;
cout << endl << "TempNodePosDelPrev " << TempNodePosDelPrev << endl;
cout << endl << "TempNodePosDelPrev->next " << TempNodePosDelPrev->next << endl;
cout << endl << "TempNodePosDelNext->prev " << TempNodePosDelNext->prev << endl;
cout << endl << "TempNodePosDelNext " << TempNodePosDelNext << endl;
cout << endl << "************************************" << endl;
}
void LBP::setLBPID()
{
pointID = pointCount;
}
int LBP::getLBPID()
{
return pointID;
}
void LBP::goToNode(int)
{
}
int LBP::getNoOfPoints()
{
return pointCount;
}
LBP::LBP(double setX, double setY)
{
x = setX;
y = setY;
setLBPID();
pointCount++;
addLBPatEnd();
}
LBP::~LBP()
{
cout << endl << "In destructor " << endl;
int NodePosForDel;
NodePosForDel = this->getLBPID();
if (NodePosForDel != 1)
{
delLBPatLocation(NodePosForDel);
}
/*delLBPatEnd();*/
cout << endl << "this pointer in destructor " << this << endl;
pointCount--;
}
Shape.cpp
#include"MasterDefine.h"
void Shape::setShapeID()
{
shapeID = shapeCount;
}
int Shape::getShapeID()
{
return shapeID;
}
Shape::Shape()
{
setShapeID();
shapeCount++;
}
Console output:
Shape id is 0
point id is 0
Shape id is 1
point id is 1
Can anyone help me in this? I am definitely missing something. I can't figure it out.
Question: How to make the point ids start from '0' for every new shape created?
Since your static int pointCount; member is static, it's the same member variable for all instances of class LBP, and because the instances share the member, upon creating a new instance, it has access to the changes made to this variable by all previous instances here:
LBP::LBP(double setX, double setY)
{
...
pointCount++;
...
}
This value is definitely not supposed to be stored statically, and it's neither responsibility of a vertex to store number of all vertices in a shape. Make a non-static variable of class Shape for example and keep that information there:
class Shape
{
private:
size_t verticesNum;
...

cargo transportation system we are not sure how to display the last part of our task

Here is our code for the task we are almost finishing just the last part we are stuck at
"Fastest: 3 trips (1 Van, 3 Mini-lorry, $645) "
we are not sure how to display the values in the bracket we only able to display 3 trips.
Is there a way to also display the values in the bracket stated as well?
we use
int min = *min_element(vTrips.begin(), vTrips.end());
cout << "Fastest: " << min << " trips" << endl;
but this only display the 3 trips.
#include <iostream>
#include <vector>
#include <iterator>
#include <fstream>
#include<algorithm>
using namespace std;
class CTS //cargo transport system
{
int i;
int cargo, lorryprice, vanprice, lorrysize, vansize, allOps;
public:
void set_cargo(int);
void set_lorryprice(int);
void set_vanprice(int);
void set_lorrysize(int);
void set_vansize(int);
};
void CTS::set_cargo(int total_cargo) {
cargo = total_cargo;
}
void CTS::set_lorryprice(int lorryP) {
lorryprice = lorryP;
}
void CTS::set_vanprice(int vanP) {
vanprice = vanP;
}
void CTS::set_lorrysize(int lorryS) {
lorrysize = lorryS;
}
void CTS::set_vansize(int vanS)
{
vansize = vanS;
}
int main()
{
int cargo, lorryprice, vanprice, lorrysize, vansize, options, i, no_lorry, no_van, cost, trips;
ifstream infile;
infile.open("size.txt");
if (infile.is_open()) {
infile >> cargo;
infile >> lorryprice;
infile >> vanprice;
infile >> lorrysize;
infile >> vansize;
}
CTS run;
run.set_cargo(cargo);
run.set_lorryprice(lorryprice);
run.set_vanprice(vanprice);
run.set_lorrysize(lorrysize);
run.set_vansize(vansize);
infile.close();
options = (cargo / lorrysize) + 1;
no_lorry = (cargo / lorrysize);
no_van = (cargo / vansize) + 3;
if (cargo % lorrysize == 0) {
no_van = -3;
}
if (cargo % lorrysize != 0) {
no_van = ((cargo % lorrysize) / 10) - 3;
}
/*it = numbervan.begin();
for (auto ir = numbervan.rbegin(); ir != numbervan.rend(); ++ir) {
cout << *ir << endl;
}*/
vector<int> vCost, vVan, vTrips, vLorry;
vector <int>::iterator it;
for (i = 1; i < options + 1; i++)
{
int numberlorry = no_lorry;
cout << "Option " << i << ":" << endl;
cout << "Number of Mini-Lorries : " << no_lorry-- << endl;
if (no_van >= -3) {
no_van += 3;
}
cout << "Number of Vans : " << no_van << endl;
int numbervan = no_van;
if (numberlorry > numbervan) {
trips = numberlorry;
}
else {
trips = numbervan;
}
cout << "Trips Needed : " << trips << endl;
cost = (numberlorry * lorryprice) + (no_van * vanprice);
cout << "Total Cost : $" << cost << endl;
vCost.push_back(cost);
vLorry.push_back(numberlorry);
vVan.push_back(numbervan);
vTrips.push_back(trips);
}
int counter = vCost.size() - 1;
//std::vector<int>::reverse_iterator ir = vCost.rbegin();
for (i = 1; i < 4; i++) {
//cout << "Lowest #" << i << ": "<<cost<<endl;
cout << "Lowest #" << i << ": $" << vCost[counter] << "(" << vVan[counter] << " Vans, " << vLorry[counter] << " Mini-Lorry, " << vTrips[counter] << " Trips)" << endl;
counter--;
}
int min = *min_element(vTrips.begin(), vTrips.end()); // this line of code we figured out how to
cout << "Fastest: " << min << " trips" << endl; //display the number of trips using algorithm
return 0;
}
Your design is awkward; you create an instance of CTS run; and never use it.
Assuming that you do your calculations right, you need to know at what index you found min. If you store the iterator returned by min_element(), you can get an index by subtracting vTrips.begin() from it. Then the corresponding elements in your vCost, vLorry and vVan vectors will contain the data you want.
However, it would be easier if you define a struct containing your pre-calculated values, and push that into some vector. In that case, all related data is kept together.

I can't get a value except 0 from my fixed array as input

I got a task from my lecture to make association program from my data mining class, and i'm using c++ in microsoft visual studio 2017 since that is the only language i understand.
I'm trying to get support result but all i got is 0. i use an algorithm i got from some sites, but i can't implement it to my code because the value is 0.
I think the problem is in the input data reading, the one with for(int i=0;i<n;i++).
this is my code :
#include<iostream>
#include<string>
using namespace std;
int main()
{
float n = 5, support1 = 0, support2 = 0, support3 = 0;
string item1, item2;
//dataset fixed
string tra1[5] = { "milk", "beer" , "coffee" , "sugar" , "detergen" };
string tra2[5] = { "egg", "flour" , "milk" , "sugar" };
string tra3[5] = { "coffee", "butter" , "cigarette" , "sugar" };
string tra4[5] = { "doritos", "tea" , "coconut oil" , "soap" };
string tra5[5] = { "detergen", "milk" , "sugar" , "coca cola" };
cout << "item 1 : "; cin >> item1;//for example coffee
cout << "item 2 : "; cin >> item2;//for example sugar
cout << endl << "------------------------------" << endl;
//i think this is where the problem is
for (int i = 0;i < n;i++)
{
//tra1
if (item1 == tra1[5]) { support1 + 1; }
if (item2 == tra1[5]) { support2 + 1; }
if (item1 == tra1[5] && item2 == tra1[5]) { support3 + 1; }
//tra2
if (item1 == tra2[5]) { support1 + 1; }
if (item2 == tra2[5]) { support2 + 1; }
if (item1 == tra2[5] && item2 == tra2[5]) { support3 + 1; }
//tra3
if (item1 == tra3[5]) { support1 + 1; }
if (item2 == tra3[5]) { support2 + 1; }
if (item1 == tra3[5] && item2 == tra3[5]) { support3 + 1; }
//tra4
if (item1 == tra4[5]) { support1 + 1; }
if (item2 == tra4[5]) { support2 + 1; }
if (item1 == tra4[5] && item2 == tra4[5]) { support3 + 1; }
//tra5
if (item1 == tra5[5]) { support1 + 1; }
if (item2 == tra5[5]) { support2 + 1; }
else if (item1 == tra1[5] && item2 == tra5[5]) { support3 + 1; }
}
//print how many times are coffee and sugar purchased
cout << "Transaction done " << item1 << " : " << support1 << endl;
cout << "Transaction done " << item2 << " : " << support2 << endl;
cout << "Transaction done " << item2 << " dan " << item2 << " : " << support3 << endl;
cout << endl << "------------------------------" << endl;
float result1,result2,result3;
result1 = (support1 / n) * 100;
result2 = (support2 / n) * 100;
result3 = (support3 / n) * 100;
cout << "Item 1 : " << item1 << "\t" << "Item 2 : " << item2 << endl;
cout << "support " << item1 << " : " << result1 << endl;
cout << "support " << item2 << " : " << result2 << endl;
cout << "support " << item1 << " dan " << item2 << " : " << result3 << endl;
return 0;
}
in your code, inside the loop you keep referencing tra2[5] . I think you mean to use tra2[i] instead. The way you have it now you're only looking at one past the last item in your arrays (arrays are 0-based. Valid indices are [0-4])
2 things, you’re for loop is trying to access the 6th index of the array when it’s only initialized to have 5 indicis.
2nd the support1,2,3 variables are initialized to 0 but you never actually increment those variables, which are used as part of your final calculation.
Your for loop needs to change to have “support1 + 1” be “support1+=1”.

Combat Game - C++, Given a Spawner Class, How can I spawn stronger enemy every round

I have a problem in my OOP homework. I have to code a 1 v 1 battle.
This is a Survival Game where in the player fights continuously with enemies until the player dies. The Player gets stronger as he advances through. The enemy also grows stronger every round.
I have created two Classes, The Unit and the Spawner.
We cannot use Inheritance nor Polymorphism.
We Have to use only the simple definition of the class.
My problem is that i cannot think of a SIMPLE way to make the class Spawner spawn a stronger enemy every round.
I have thought of overloading the Unit's Contructor but i have trouble manipulating that.
Would anyone please help?
Here's my Unit Header file (Unit.h):
#pragma once
#include <string>
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
// Class Types
const string CLASS_WARRIOR = "Warrior" ;
const string CLASS_ASSASSIN = "Assassin";
const string CLASS_MAGE = "Mage" ;
// Class Choices
const int CHOICE_WARRIOR = 1;
const int CHOICE_ASSASSIN = 2;
const int CHOICE_MAGE = 3;
// Multipliers
const double MULTIPLIER_DAMAGE = 0.50f;
const double MULTIPLER_HEAL = 0.30f;
// Advantage
const bool ADVANTAGE = true;
// Win Bonus
const int BONUS_THREE = 3;
const int BONUS_FIVE = 5;
// Minimum and maximum values
const int HIT_RATE_MAX = 80;
const int HIT_RATE_MIN = 20;
const int DAMAGE_MIN = 1;
// Hit or miss
const bool ATTACK_HIT = true;
const bool ATTACK_MISS = false;
class Unit
{
public:
// Constructors
Unit(string name, int classChoice);
// Getters and setters
string getName();
string getClass();
int getHp();
int getMaxHp();
int getPower();
int getVitality();
int getAgility();
int getDexterity();
int getDamage();
int getHeal();
int getBonusDamage();
bool getFirstToAttack();
bool getHit();
void setClassStats(const int classChoice);
// Primary Actions
void attack(Unit* target);
// Secondary Actions
void check(const Unit* target); // Inspects the enemy
void lvlUp(); // Grants this Unit Bonus Stats on Victory
private:
// Info
string mName;
string mClass;
// Basic Stats
int mHp;
int mMaxHp;
int mPower;
int mVitality;
int mAgility;
int mDexterity;
// Derived Stats
int mDamage;
int mHitrate;
int mHeal;
int mBonusDamage;
// Miscellaneous
bool mAdvantage; // If the player has the advantage
string mTargetClass;// This Unit keeps in mind the class of this Unit's Opponent for reference
int mChanceOfHit; // The random chance if the attack will Hit/Miss
bool mFirstToAttack;//if this unit will attack first
bool mHit; // if the attack is a hit or miss
};
Here's my Unit.cpp file (Unit.cpp):
#include "Unit.h"
Unit::Unit(string name, int classChoice)
{
mName = name;
setClassStats(classChoice);
}
string Unit::getName()
{
return mName;
}
string Unit::getClass()
{
return mClass;
}
int Unit::getHp()
{
return mHp;
}
int Unit::getMaxHp()
{
return mMaxHp;
}
int Unit::getPower()
{
return mPower;
}
int Unit::getVitality()
{
return mVitality;
}
int Unit::getAgility()
{
return mAgility;
}
int Unit::getDexterity()
{
return mDexterity;
}
int Unit::getDamage()
{
return mDamage;
}
int Unit::getHeal()
{
return mHeal;
}
int Unit::getBonusDamage()
{
return mBonusDamage;
}
bool Unit::getFirstToAttack()
{
return mFirstToAttack;
}
bool Unit::getHit()
{
return mHit;
}
void Unit::setClassStats(const int classChoice)
{
if (classChoice == CHOICE_WARRIOR) {
mClass = CLASS_WARRIOR;
mMaxHp = 20;
mHp = mMaxHp;
mPower = 15;
mVitality = 10;
mAgility = 7;
mDexterity = 7;
return;
}
else if (classChoice == CHOICE_ASSASSIN) {
mClass = CLASS_ASSASSIN;
mMaxHp = 15;
mHp = mMaxHp;
mPower = 17;
mVitality = 8;
mAgility = 12;
mDexterity = 10;
return;
}
else if (classChoice == CHOICE_MAGE) {
mClass = CLASS_MAGE;
mMaxHp = 30;
mHp = mMaxHp;
mPower = 12;
mVitality = 12;
mAgility = 9;
mDexterity = 8;
return;
}
throw exception("Error! Class not part of this game. ");
}
void Unit::attack(Unit * target)
{
// Determine Whether the attack will Hit/Miss Based on the hit rate
mChanceOfHit = rrand() % 100 + 1;
if (mChanceOfHit > mHitrate) {
mHit = ATTACK_MISS;
return;
}
// Deducts the targets Hp by the Damage given by this Unit (if the attack didn't miss)
target->mHp -= mDamage;
mHit = ATTACK_HIT;
// if target HP is negative, set it to zero
if (target->mHp < 0) target->mHp = 0;
}
void Unit::check(const Unit * target)
{
// The Unit Keeps in Mind his target's Class
if (target->mClass == CLASS_WARRIOR) mTargetClass = CLASS_WARRIOR;
else if (target->mClass == CLASS_ASSASSIN) mTargetClass = CLASS_ASSASSIN;
else if (target->mClass == CLASS_MAGE) mTargetClass = CLASS_MAGE;
// Checks if the Unit is Advantageous Against his Target
if (mClass == CLASS_WARRIOR) {
if (target->mClass == CLASS_ASSASSIN) mAdvantage = ADVANTAGE;
else mAdvantage = false;
}
else if (mClass == CLASS_ASSASSIN) {
if (target->mClass == CLASS_MAGE) mAdvantage = ADVANTAGE;
else mAdvantage = false;
}
else if (mClass == CLASS_MAGE) {
if (target->mClass == CLASS_WARRIOR) mAdvantage = ADVANTAGE;
else mAdvantage = false;
}
// Determine if this Unit Will Attack first
if (mAgility >= target->mAgility) mFirstToAttack = true;
else mFirstToAttack = false;
// Determines Damage, Bonus Damage ( If Applicable ), and Hit Rate Based on targets stats
mDamage = mPower - target->mVitality;
if (mDamage < DAMAGE_MIN) mDamage = DAMAGE_MIN;
mBonusDamage = mDamage * MULTIPLIER_DAMAGE;
// Evaluates Damage Based on advantage
if (mAdvantage) mDamage += mBonusDamage;
mHitrate = ((float)mDexterity / (float)target->mAgility) * 100;
// Clamps the Hit Rate within the Hit Rate Range
if (mHitrate > HIT_RATE_MAX) mHitrate = HIT_RATE_MAX;
else if (mHitrate < HIT_RATE_MIN) mHitrate = HIT_RATE_MIN;
}
void Unit::lvlUp()
{
// Determine Win Bonus Based on the target that he kept in mind
if (mTargetClass == CLASS_WARRIOR) {
mMaxHp += BONUS_THREE;
mVitality += BONUS_THREE;
}
else if (mTargetClass == CLASS_ASSASSIN) {
mAgility += BONUS_THREE;
mDexterity += BONUS_THREE;
}
else if (mTargetClass == CLASS_MAGE) {
mPower += BONUS_FIVE;
}
// Heals the player 30% of his Maximum HP
mHeal = mMaxHp * MULTIPLER_HEAL;
mHp += mHeal;
}
Here's my Spawner Header file (Spawner.h):
#pragma once
#include "Unit.h"
class Spawner
{
public:
Spawner();
~Spawner();
void spawn(Unit*& unit);
private:
Unit* mUnit;
int mRandomClass;
};
Here's my Spawner.cpp file (Spawner.cpp):
#include "Spawner.h"
Spawner::Spawner()
{
}
Spawner::~Spawner()
{
delete mUnit;
mUnit = NULL;
}
void Spawner::spawn(Unit *& unit)
{
mRandomClass = rand() % 3 + 1;
unit = new Unit("Enemy", mRandomClass);
mUnit = unit;
}
And finally here is my main.cpp:
#include "Unit.h"
#include "Spawner.h"
// Create player
Unit* createPlayer();
// Display Stats
void displayStats(Unit* unit);
// Play 1 round
void playRound(Unit*player, Unit* enemy);
// Simulate 1 attack (implement Higher agility gets to atttack first)
void combat(Unit* player, Unit* enemy);
void main()
{
srand(time(NULL));
Unit* player = createPlayer();
Unit* enemy = NULL;
Spawner *spawner = new Spawner();
int round = 1;
while (true) {
cout << "Round " << round << endl;
spawner->spawn(enemy);
player->check(enemy);
enemy->check(player);
playRound(player, enemy);
// if player is dead, end the game
if (player->getHp() == 0) break;
// else, add stats
player->lvlUp();
delete enemy;
enemy = NULL;
cout << "You defeted an enemy" << endl;
system("pause>nul");
system("cls");
round++;
}
cout << "You were defeted! " << endl;
cout << "You survived until Round " << round << endl;
displayStats(player);
delete player;
player = NULL;
delete spawner;
spawner = NULL;
system("pause>nul");
system("cls");
}
Unit* createPlayer()
{
Unit* unit = NULL;
string name;
int classChoice;
cout << "Enter your Name: ";
getline(cin, name);
system("cls");
cout << "Pick a class: " << endl
<< "\t [ 1 ] Warrior" << endl
<< "\t [ 2 ] Assassin" << endl
<< "\t [ 3 ] Mage" << endl
<< endl;
cin >> classChoice;
while (classChoice > 3 || classChoice <= 0) {
cout << "INVALID INPUT! Please try again" << endl;
cout << "Pick a class: " << endl
<< "\t [ 1 ] Warrior" << endl
<< "\t [ 2 ] Assassin" << endl
<< "\t [ 3 ] Mage" << endl
<< endl;
cin >> classChoice;
}
unit = new Unit(name, classChoice);
return unit;
}
void displayStats(Unit* unit)
{
cout << "=========================================================================================" << endl
<< "Name: " << unit->getName() << " \t \t \t HP: " << unit->getHp() << " / " << unit->getMaxHp() << endl
<< "Class: " << unit->getClass() << endl
<< "==========================================================================================" << endl
<< "POW: " << unit->getPower() << endl
<< "VIT: " << unit->getVitality() << endl
<< "AGI: " << unit->getAgility() << endl
<< "DEX: " << unit->getDexterity() << endl
<< endl;
}
void playRound(Unit*player, Unit* enemy)
{
while (player->getHp() > 0 && enemy->getHp() > 0) {
displayStats(player);
displayStats(enemy);
system("pause>nul");
combat(player, enemy);
system("cls");
}
}
void combat(Unit* player, Unit* enemy)
{
if (player->getFirstToAttack()) {
player->attack(enemy);
if (player->getHit() == ATTACK_MISS) cout << player->getName() << "'s Attack Missed! " << endl;
else if (player->getHit() == ATTACK_HIT) cout << player->getName() << " dealt " << player->getDamage() << " Damage" << endl;
system("pause>nul");
if (enemy->getHp() == 0) return;
enemy->attack(player);
if (enemy->getHit() == ATTACK_MISS) cout << enemy->getName() << "'s Attack Missed! " << endl;
else if (enemy->getHit() == ATTACK_HIT) cout << enemy->getName() << " dealt " << enemy->getDamage() << " Damage" << endl;
system("pause>nul");
return;
}
else if (enemy->getFirstToAttack()) {
enemy->attack(player);
if (enemy->getHit() == ATTACK_MISS) cout << enemy->getName() << "'s Attack Missed! " << endl;
else if (enemy->getHit() == ATTACK_HIT) cout << enemy->getName() << " dealt " << enemy->getDamage() << " Damage" << endl;
system("pause>nul");
if (player->getHp() == 0) return;
player->attack(enemy);
if (player->getHit() == ATTACK_MISS) cout << player->getName() << "'s Attack Missed! " << endl;
else if (player->getHit() == ATTACK_HIT) cout << player->getName() << " dealt " << player->getDamage() << " Damage" << endl;
system("pause>nul");
return;
}
}
Add a "level" to the Unit class, and use the level to increase the stats of the unit (for example level 2 could mean the stats are multiplied by 1.5 or some such). Pass the level as an argument to the constructor similar to the units class.
You need to make your spawner aware of how many enemies it has spawned:
// this belongs into your class definition, it should start at zero
int mCurrentSpawn;
So set it to zero in your constructor:
Spawner::Spawner()
{
mCurrentSpawn = 0;
}
Then reference it when you spawn an enemy:
void Spawner::spawn(Unit *& unit)
{
mRandomClass = rand() % 3 + 1;
unit = new Unit("Enemy", mRandomClass);
mUnit = unit;
mCurrentSpawn++;
int levelUps = mCurrentSpawn - 1;
while(levelUps > 0)
{
mUnit->lvlUp();
levelUps--;
}
}

Returns garbage value instead of 0 or 1 in c++

I am trying to return integer from the following method in c++:
int check_for_chef(string str1,string str2,int M,int N)
{
if ( N == -1 )
{
cout << "I am returning 1." <<endl;
return 1;
}
else if ( N > M )
{
cout << " I am returning 0." <<endl;
return 0;
}
else
{
if ( str1[M] == str2[N])
{
location[N] = M;
cout << "location is: "<<location[N]<<endl;
check_for_chef(str1,str2,M - 1, N - 1);
}
else
{
check_for_chef(str1,str2,M - 1, N);
}
}
}
But, what I am getting while returning is :
Returned value is: 35668224
Whole code is here:
#include <iostream>
#include <string>
using namespace std;
int location[4];
int check_for_chef(string str1,string str2,int M,int N)
{
if ( N == -1 )
{
cout << "I am returning 1." <<endl;
return 1;
}
else if ( N > M )
{
cout << " I am returning 0." <<endl;
return 0;
}
else
{
if ( str1[M] == str2[N])
{
location[N] = M;
cout << "location is: "<<location[N]<<endl;
check_for_chef(str1,str2,M - 1, N - 1);
}
else
{
check_for_chef(str1,str2,M - 1, N);
}
}
}
int main()
{
int count = 0;
string original_string;
cin >> original_string;
string chef = "CHEF";
int M = original_string.size();
int N = 4;
while ( 1 )
{
cout << "Returned value is: " << check_for_chef(original_string,chef,M - 1, N - 1);
cout << " i am in while."<<endl;
count++;
original_string.erase(location[3],1);
cout << "the original_string : " << original_string <<endl;
original_string.erase(location[2],1);
cout << "the original_string : " << original_string <<endl;
original_string.erase(location[1],1);
cout << "the original_string : " << original_string <<endl;
original_string.erase(location[0],1);
cout << "the original_string : " << original_string <<endl;
cout << "the original_string : " << original_string <<endl;
M = original_string.size();
cout << "size is :" << M <<endl;
if ( M < N )
break;
}
cout << count <<endl;
}
Please help me to solve this problem.
I don't see two more return in the code
I have added in the commented lines below:
int check_for_chef(string str1,string str2,int M,int N)
{
if ( N == -1 )
{
cout << "I am returning 1." <<endl;
return 1;
}
else if ( N > M )
{
cout << " I am returning 0." <<endl;
return 0;
}
else
{
if ( str1[M] == str2[N])
{
location[N] = M;
cout << "location is: "<<location[N]<<endl;
return check_for_chef(str1,str2,M - 1, N - 1); // here 1st RETURN
}
else
{
return check_for_chef(str1,str2,M - 1, N); // here 2nd RETURN
}
}
}
Your code does not return anything expicitly in the else branch.
Values in x84 usually are returned via EAX register, so if you do not return anything - it behaves like an uninitialized variable.