Home > front end >  Finding a more effective solution to using if statements with multiple outcomes
Finding a more effective solution to using if statements with multiple outcomes

Time:12-22

I am using C# to make a script that can handle and use FEN string notations to create unique chess positions. Given a string, it has to check each character to see whether it is a r, n, k, q, p etc to figure out which piece needs to be drawn. To do this, I use a lot of if statements and was wondering if there was any simpler/cleaner way to check the character against multiple values and give separate outputs.


    if(c == 'r')
    {
       Instantiate(blackRook, new Vector2(gridX, gridY), Quaternion.identity);
       gridX  = 1;
    }
    else if(c == 'n')
    {
       Instantiate(blackKnight, new Vector2(gridX, gridY), Quaternion.identity);
       gridX  = 1;
    }
    else if(c == 'p')
    {
       Instantiate(blackPawn, new Vector2(gridX, gridY), Quaternion.identity);
       gridX  = 1;
    }

As you can see, there's clearly a lot of repetition here. I thought about using a function to cover all instantiations of all pieces including increasing the other variable, but I would still have to check which piece is which and what the appropriate response should be.

CodePudding user response:

You can try extracting model, e.g. as a dictionary:

//TODO: Put right type name instead of 'Piece'
Dictionary<char, Piece> blackPieces = new() {
  {'r', blackRook},
  {'n', blackKnight},
  {'p', blackPawn},
  // Add more pieces (Bishop, Queen, King...) if required
};

...

if (blackPieces.TryGetValue(c, out var piece)) {
  Instantiate(piece, new Vector2(gridX, gridY), Quaternion.identity);
  gridX  = 1;
}
  • Related