2

I've been learning c# and I want to start an experimental console application project of an American Football Simulator. It is vital for this project to have chances.

Example: there's a 20% chance the kicker will succeed in a field goal kick over 45 yards.

I've looked around on here and noticed people using randoms, but is that really the most efficient way to go about doing this?

Random chance = new Random(1, 100);
If (Yards > 45)
{
    If (chance <= 20)
    {
        // Field goal success
    }
    else
    {
        // Field goal fail
    }
}

What would be the best way to go about doing this?

Vivek Jain
  • 3,811
  • 6
  • 30
  • 47
Donavon
  • 323
  • 2
  • 6
  • 11

1 Answers1

1

It's very simple. Just do this:

private Random _rnd = new Random();
public bool RandomSuccess(double probability)
{
    return _rnd.NextDouble() < probability;
}

Then use it like this:

if (Yards > 45)
{
    if (RandomSuccess(0.2))
    {
        // Field goal success
    }
    else
    {
        // Field goal fail
    }
}
Aheho
  • 12,622
  • 13
  • 54
  • 83
Enigmativity
  • 113,464
  • 11
  • 89
  • 172