PDA

View Full Version : C++ function help


Lawn Gnome
03-21-2006, 03:25 AM
k im trying to make a txt game. i have problems with my exp check function tho. first the code.

/*Level Up Function*/
void level_up()
{
MaxHp=MaxHp+50;
hp=MaxHp;
lvl=lvl+1;
dmg=dmg+5;
cout<<"\n\nYou Gain A Level!!"<<endl;
cout<<"You Are Now Level "<<lvl<<endl;
cin.get();
cin.ignore();
system("cls");
}
/*End Level Up Function*/
/*EXP Check*/
void exp_check()
{
if(exp>=10)
{
level_up();
}
else if(exp>=40)
{
level_up();
}
//will add more later
}
/*End EXP Check*/

this is both my level up and exp check code. i need a way to make it so with the exp check it wont level up everytime it checks becuse the exp is higher then or = to 10. but i cant figure out how to do it. i need so when it levels up the first time, to skip that and go to the second exp needed to level.

oracleguy
03-21-2006, 07:10 AM
I kinda think I get what you are asking but it isn't totally clear. Are you trying to make it so if it checks your experience and you have enough to go to the next level, it calls the level up function but only the first time and doesn't call it every time?

If that is the case, there are a couple ways to approach the problem, it really depends on how you have the rest of your program setup. But one way is to make a struct for the different levels, e.g.:


struct level
{
int lvl;
int neededExp;
};


And then you could make an array of the different levels, e.g:

const int NUM_LEVELS = 4;

...

level levels[NUM_LEVELS];
...

And then when you have your check experience function, have it check to see if the player has enough experience for the next level, if they do, call the level up function and increment their current level which you would also need to keep track of in a variable.

oracleguy
03-21-2006, 07:33 AM
And actually I just thought of another simple method.

If just have your level variable you could use that as part of the logic. Like so:


if(exp>=10 && current_level == 0)
{
level_up();
}
else if(exp>=40 && current_level == 1)
{
level_up();
}


However this then means you'll have a very large if..else if block in your function. If you use the other method you wouldn't have that. I'd probably still use the other one, I just thought I'd point this out nonetheless.

TR-VandaL
03-24-2006, 02:55 AM
Even simpler way might be to the required XP to be a multiple of the level (ie 10*lvl. that would make it a linear curve which would make things kinda easy depending on how you set up the gaining of XP. In that case you could square or even cube the level first (ie exp >=(10*lvl^2) ... but then you'd need the Math header file).