I am learning c++ ahead of some classes on it. I have written a few text based rpgs and now I am trying to integrate random numbers to be used in fight mechanics and storyline variables.
It seems that the random number is generating on compile only for me. Perhaps I am using the wrong function.
Also please be very critical of my "style". I do not want to develop bad habits if I can help it.
// Skeleton fight
// Uses rng, and loops to fight a skeleton
#include <iostream>
#include <ctime>
#include <cstdlib>
usingnamespace std;
int main()
{
srand(time(0));
int randomNumber = rand();
int skelLife;
int playerHit;
int swing;
skelLife = 100;
cout << "\n\nYou stumble across a skeleton in the woods." << endl;
cout << "You reach into your pack and pull out a sword.\n" << endl;
while (skelLife >=0)
{
cout << "\nDo you swing at the skeleton or do you flee?\n" << endl;
cout << "1 - Swing\n" << endl;
cout << "2 - Flee\n" << endl;
cin >> swing;
switch (swing)
{
case 1:
cout << "\nYou swing at the skeleton with your sword.\n" << endl;
playerHit = (randomNumber) % 10 + 1;
skelLife = skelLife - playerHit;
cout << "You hit the skeleton for " << playerHit << " damage.\n" << endl;
if (skelLife >=0)
{
cout << "The skeleton staggers but doesn't fall.\n\n";
}
else
{
cout << "You have defeated the skeleton\n";
}
break;
case 2:
cout << "You run away.\n" << endl;
break;
}
}
return 0;
}
yes, on line 13 a single rand()om number is assigned to the variable randomNumber and not changed afterwards, so you're using the same number all the time.
As for yur question you generate the random number only once at the very beginning of the program
int randomNumber = rand();
So it is not being changed.
As for programming style then
1. You should declare variables only in those declrative regions where they are used. For example variable swing is used only in the block scope of the while loop. So it should be declared in this declarative region.
2. You should not use "magic numbers" as 100 or as 1 or 2 in the switch statement. It is better to define either a named itegrl constant or an enumeratoe.