This question already has an answer here:
- Same random numbers every loop iteration 4 answers
Hello programming community, I wanna generate a little fighter game, where two fighters fight against each other (or even more later). So first of all i show you how the output of the fight looks like:
Fighter1 attacks Fighter2 with 11 damage!
Fighter2 counterattacks Fighter1 with 24 damage!
Fighter2 attacks Fighter1 with 24 damage!
Fighter1 counterattacks Fighter2 with 11 damage!
Fighter1 attacks Fighter2 with 11 damage!
Fighter2 counterattacks Fighter1 with 24 damage!
Fighter2 attacks Fighter1 with 24 damage!
Fighter1 counterattacks Fighter2 with 11 damage!
Fighter1 attacks Fighter2 with 11 damage!
Fighter2 counterattacks Fighter1 with 24 damage!
As you probably can see, they have the value 11 and 24, but they never ever generate a new random and always take that. So here is my code:
Random function
int Fighter::randomval(int min, int max)
{
srand(time(NULL));
int d = (min + (std::rand() % (max - min + 1)));
//std::cout << d << std::endl;
return d;
}
Attack (warrior is a subclass from Fighter):
void Warrior::attack(Fighter * victim)
{
int attack = 0;
attack = randomval(0, offensePoints);
//chance 1/6
if (randomval(1,6) == 1)
{
//double hitpoints
attack *= 2;
std::cout << "SUPERATTACK: ";
}
std::cout << this->name << " attacks " << victim->getname() << " with" << attack << " damage!" << std::endl;
recievedmg(victim, attack);
}
Counterattack:
void Warrior::counterattack(Fighter * victim)
{
int counterattack = 0;
counterattack = randomval(0, defensePoints);
std::cout << this->name << " counterattacks " << victim->getname() << " with " << counterattack << " damage!" << std::endl;
recievedmg(victim, counterattack);
}
Fight function in main:
int turn = 0;
while(fighters[name1]->isalive() && fighters[name2]->isalive())
{
if (turn == 0)
{
fighters[name1]->attack(fighters[name2]);
if (fighters[name2]->isalive())
{
fighters[name2]->counterattack(fighters[name1]);
}
turn = 1;
}
else if (turn == 1)
{
fighters[name2]->attack(fighters[name1]);
if (fighters[name1]->isalive())
{
fighters[name1]->counterattack(fighters[name2]);
}
turn = 0;
}
}
cout << "Winner is: ";
if (fighters[name1]->isalive())
{
cout << fighters[name1]->getname() << endl;
delete fighters[name2];
fighters.erase(name2);
}
else
{
cout << fighters[name2]->getname() << endl;
delete fighters[name1];
fighters.erase(name1);
}
Aucun commentaire:
Enregistrer un commentaire