William
William

Reputation: 415

How to Calculate Accuracy %

I have the following scenario. I have a game in Unity where a player is provided with varying amount of targets (we'll say 125 as an example). The accuracy is multi-class in that there is Perfect(bullseye), Great, Good, Miss (where miss is the target is missed entirely, no points awarded). I'm trying to find the right way to calculate a correct accuracy percentage in this scenario. If the player hits every target (125) as Perfect, the accuracy would be 100%. If they hit 124 Perfect and 1 Great, while every target was hit the accuracy percentage would still drop (99.8%). What would be the correct way to calculate this? Balanced Accuracy? Weighted Accuracy? Precision?

I'd like to understand the underlying calculation, not just how to implement this in code.

I appreciate any help I can get with this.

Upvotes: 0

Views: 922

Answers (1)

Sisus
Sisus

Reputation: 729

This can be calculated by assigning each accuracy a score between 0 and 100 (percentage) and then calculating the average score or arithmetic mean for all the shots.

You could use an enum to define the scores for the different accuracies.

public enum Accuracy
{
    Perfect = 100,
    Great = 80,
    Good = 50,
    Miss = 0
}

Then to calculate the average you just need to sum all the accuracy scores together and divide the result by the total number of shots.

int sum = 0;
foreach(Accuracy shot in shotsTaken)
{
    sum += (int)shot;
}

double average = (double)sum / shotsTaken.Count;

Calculating the average can be simplified using System.Linq.

public class Tally
{
    private readonly List<Accuracy> shotsTaken = new List<Accuracy>();

    public void RecordShot(Accuracy shot) => shotsTaken.Add(shot);

    public string CalculateAverageAccuracy() => shotsTaken.Average(shot => (int)shot).ToString("0.#") + "%";
}

You can test the results using this code:

[MenuItem("Test/Tally")]
public static void Test()
{
    var tally = new Tally();
    for(int i = 0; i < 124; i++)
    {
        tally.RecordShot(Accuracy.Perfect);
    }
    tally.RecordShot(Accuracy.Great);
    Debug.Log(tally.CalculateAverageAccuracy());
}

Result:

enter image description here

Upvotes: 1

Related Questions