Can anyone tell me why this is always returning zero?

Title says it all; I am making a chess game and wrote a function to dtermine whether a space is a black or white space I have no clue why I keep getting zero (neither black or white). I have confirmed that the appropriate column and Row values are being passed in (character literals ‘A’ ‘B’ ‘C’ ‘D’ ‘E’ ‘F’ ‘G’ ‘H’ ‘1’ ‘2’ ‘3’ ‘4’ ‘5’ ‘6’ ‘7’ ‘8’.) Anybody see what I messed up?

	private int GetSpaceColor(char Column, char Row){
		Debug.Log ("Get Space Color Called");
		Debug.Log(Column);
		Debug.Log(Row);

		if ( ((Column == 'A') || (Column == 'C') || (Column == 'E') || (Column == 'G')) && ((Row == '1') || (Row == '3') || (Row == '4') || (Row == '7')) ) {
			//return (int) Color.Black; // return 1 for Black
			return 1;
		}
		else{
			if (((Column == 'B') || (Column == 'D') || (Column == 'F') || (Column == 'H')) && ((Row == '2') || (Row == '4') || (Row == '6') || (Row == '8'))) {
				//return (int) Color.White; // return 2 for White
				return 2;
			}
			else{
				Debug.Log("Function Returning 0");
				//return (int) Color.None; // return 0 for None
				return 0;
			}
		}
	}

How are you calling this? If I call like so: Debug.Log("return: " + GetSpaceColor('A', '1')); Debug.Log("return: " + GetSpaceColor('B', '2')); Debug.Log("return: " + GetSpaceColor('A', '2')); My log output is 1, 2, 0, which seems to be correct.

1 Answer

1

There is a much simpler way to code this. This will return 0 or 1 based on a grid pattern. (I didn’t get out my pen and paper to see which colours those map to).

private int GetSpaceColor(char Column, int Row){

    int charOffset = 0;

    if ((Column == 'A') || (Column == 'C') || (Column == 'E') || (Column == 'G')) {
        charOffset = 1;
    }

    return (row + charOffset) % 2;
}

You could also modify it to throw an error if the input is outside of the board.

You could go one step further and convert your Column to an int and get rid of that ugly if altogether.