Having a dumb: comparing four values

This works but I know there must be a smarter way of doing it. The scores are integers. If I dump them into a list or array, I lose the link with the color that put them there. (It doesn’t help me if, say, 15 is the .max if the code can’t remember which color 15 came from originally).

    void CalculateResultFromTotalScore()
    {
        //This compares the result scores to determine the winning color.

        if (redScore > greenScore && redScore > blueScore && redScore > yellowScore)

I would keep track of the scores in a Dictionary. You can then use a Linq function to get the item from the Dictionary with the highest value. Note that Linq functions are generally more expensive than basic operations, but for one-off tasks like figuring out who won, it’s okay. Just don’t run GetHighestScoringPlayer in Update or anything, but check it only after incrementing a score.

using System.Collections.Generic;
using UnityEngine;
using System.Linq;

public class PlayerScoreStuff : MonoBehaviour
{
    public enum PlayerColor {
        Red,
        Yellow,
        Green,
        Blue
    }

    private Dictionary<PlayerColor, int> scores = new Dictionary<PlayerColor, int>();

    public void IncrementScore(PlayerColor playerColor, int score) {
        scores[playerColor] += score;
    }

    public PlayerColor GetHighestScoringPlayer()
    {
        return scores.Aggregate((a, b) => a.Value > b.Value ? a : b).Key;
    }
}
2 Likes

THANK YOU.

This became doubly helpful because I’ve been messing around with a function to evaluate if there’s a tie. Two birds, one stone!

1 Like

Oh, you know… that’s a situation I hadn’t considered. Not sure what that function would do in the case that two values were equal. You might have to dig in a bit and refine it some.

Glad it’s got you moving, though!

1 Like

If you don’t want to get into linq, you can make a struct or simple class which has both the score and color together, and then loop through them in a list or array still. Then you won’t lose track of the color with the score. Just off the top of my head:

public class Score
{
    public enum ScoreColor {None, Red, Green, Blue, Yellow};
    public ScoreColor MyColor = ScoreColor.None;
    public int MyScore = 0;
}
public List<Score> ScoreList;  //Somehow fill this with a list of scores

public Score GetWinner()
{
    Score winner = null;
    foreach (Score s in ScoreList)
    {
        if (winner == null)
        {
            winner = s;
        }
        else
        {
            if (s.MyScore > winner.MyScore)
            {
                winner = s;
            }
        }
    }
    Debug.Log("Winner: " + winner.MyColor.ToString());
    return winner;
}

This is so wonderfully creative. Thank you for taking the time to write out the mock up code!

1 Like