I have a 2D array that acts as a board for a chess game. I expect user input to be in the Smith Notation. The way my array is set up is if the user says they want a piece to move to or from the 8th row (the top one from the user’s point of view), they are interacting with row[0] in the array. So to handle this I wrote a function that converts the user’s input into the correct row for the array. However, it seems a little clunky and I was wondering how programmers with more experience would solve this problem.
int convertToCorrectRow(int row)
{
int newRow;
switch (row) {
case 1:
newRow = 7;
break;
case 2:
newRow = 6;
break;
case 3:
newRow = 5;
break;
case 4:
newRow = 4;
break;
case 5:
newRow = 3;
break;
case 6:
newRow = 2;
break;
case 7:
newRow = 1;
break;
case 8:
newRow = 0;
break;
default:
assert(false);
break;
}
return newRow;
}
I did think of having flipping the array and displaying it in reverse to the user so that when the user interacts with row 8 they are actually interact with row[7] in the array and that would eliminate the need for this function. However, I would still like to know other ways to solve this problem.
Thanks in advance for your response.
It looks like this simplifies to:
If
rowcomes from user input without further validation, I wouldn’t use an assert, though.