Home > front end >  Unable to trigger a duel to play out c
Unable to trigger a duel to play out c

Time:03-01

Working on an assignment to have a duel play out amongst three players with varying accuracy and needs them to shoot in order. Aaron has an accuracy of 1/3, Bob has an accuracy of 1/2, and Charlie never misses. A duel should loop until one is left standing. Here is my code so far and it only ever causes the first two players to miss and Charlie wins even when the random number generator should constitute a hit.

#include <iostream>
#include <ctime>
#include <cstdlib>

using std::cin;
using std::cout;
using std::endl;

void shoot(bool & targetAlive, double accuracy);
int startDuel();

int main()
{
    srand(time(NULL));
    startDuel();

    return 0;
}

void shoot(bool &targetAlive, double accuracy)
{
    double x;
    

    x = (((float)rand()/(float)(RAND_MAX))*1.0);
    if (x < accuracy)
    {
        cout << "target is hit!" << endl;
        targetAlive = false;
    }
    else
        cout << "missed!" << endl;
        cout << x << endl;
        targetAlive = true;
}

int startDuel()
{
    int a = 0, b = 0, c = 0;
    bool aaronAlive, bobAlive, charlieAlive;

    shoot(charlieAlive, 1.0/3);
    if (charlieAlive)
    {
        cout << "Aaron missed Charlie!" << endl;
        shoot(charlieAlive, 0.5);
        if (charlieAlive)
        {
            cout << "Bob missed Charlie so Charlie throws back!" << endl;
            cout << "Bob has been hit by Charlie!" << endl;
            bobAlive = false;
            shoot (charlieAlive, 1.0/3);
            if (charlieAlive)
            {
                cout << "Aaron missed Charlie, so Charlie throws back!" << endl;
                aaronAlive = false;
                cout << "The duel is over and Charlie wiped them all out" << endl;
                return (c  );
            }
        }
    }
    else if (!charlieAlive)
    {
        cout << "Aaron hit Charlie" << endl;
        do
        {
            shoot(aaronAlive, 0.5);
            shoot(bobAlive, 1.0/3);
            if (!aaronAlive)
            {
                cout << "Bob won!" << endl;
                return (b  );
            }
            else if (!bobAlive)
            {
                cout << "Aaron won!" << endl;
                return (a  );
            }
        }
        while((aaronAlive)&&(bobAlive));
    }
}

CodePudding user response:

look at the last line of shoot

void shoot(bool& targetAlive, double accuracy)
{
  double x;


  x = (((float)rand() / (float)(RAND_MAX)) * 1.0);
 if (x < accuracy)
 {
    cout << "target is hit!" << endl;
    targetAlive = false;
 } 
  else
    cout << "missed!" << endl;
 cout << x << endl;
 targetAlive = true;  <<<<====
}

no matter what happens before you reset alive to true before exiting

just remove that line

also move srand to main, you should only call it once.

  •  Tags:  
  • c
  • Related