You are declaring the variables as local to the function. That is why they are being reset every time you call the function. To preserve the values between function calls, you have to move the variables into members of the class instead.
Your Die
class is also not well designed, either. You should be seeding the generator only one time, so do it in the constructor, and then create the Die
object once, not on every loop iteration. And you are not using the last roll in the new roll, so there is no need to have a num
member in the class.
You should also separate the beetle logic from the Die
class. A dice does not control a game. A game uses a dice to make decisions. Your code should reflect that.
Try something more like this instead:
#include <iostream>
#include <ctime>
#include <stdlib.h>
using namespace std;
class Dice
{
public:
Dice();
int roll();
};
class Beetle
{
private:
int eyes;
int antennas;
int legs;
int wings;
int head;
int body;
public:
Beetle();
void takeATurn(Dice &dice);
};
Beetle::Beetle() :
eyes(0),
antennas(0),
legs(0),
wings(0),
head(0),
body(0)
{
}
Dice::Dice() // initialize the dice
{
srand((unsigned)time(0));
}
int Dice::roll() //roll one dice to get random number
{
int num = (rand() % 6)+1;
cout << num;
return num;
}
void Beetle::takeATurn(Dice &dice) //player is building the beetle
{
int num = dice.roll();
if ((num != 6) && (body < 1))
{
cout << endl << "You need a body first";
return;
}
switch (num)
{
case 1:
if (eyes < 2)
{
eyes++;
cout << endl << "You got an eye";
}
else
cout << endl << "Sorry, the beetle has only 2 eyes!";
break;
case 2:
if (antennas < 2)
{
antennas++;
cout << endl << "You got an antenna";
}
else
cout << endl << "No more than 2 antennas";
break;
case 3:
if (legs < 6)
{
legs++;
cout << endl << "You got a leg";
}
else
cout << endl << "Opps, you can't have more legs!";
break;
case 4:
if (wings < 2)
{
wings++;
cout << endl << "You got a wing";
}
else
cout << endl << "nope, the beetle got 2 wings only";
break;
case 5:
if (head < 1)
{
head++;
cout << endl << "You got the head";
}
else
cout << endl << "One head is enough";
break;
case 6:
if (body < 1)
{
body++;
cout << endl << "You got the body";
}
else
cout << endl << "You got the body already";
break;
}
}
}
int main()
{
int n = 0;
cout << "start?";
cin >> n;
if (n == 1)
{
Dice dice1;
Beetle beetle;
do
{
beetle.takeATurn(dice1);
cout << endl << "Repeat?: ";
cin >> n;
}
while (n == 1);
}
return 0;
}
solved Variable life-time in member-function, values keep reseting to `0`, why? [closed]