Lines 46-86 can be consolidated
1 2 3 4 5 6 7 8 9 10
|
if (PlayerChoice > 0 && PlayerChoice < 10 && board[(PlayerChoice-1)/3][(PlayerChoice-1)%3] == char(PlayerChoice + '0')
{
board[PlayerChoice/3][PlayerChoice%3] = PlayerMark;
}
else{
cout << "\nInvalid Move!\n";
ValidMove = 0;
cin.ignore();cin.get();
}
|
PlayerChoice > 0 && PlayerChoice < 10 Is validating the input, so that later you don't run out of bounds. C++ evaluates conditions from left to right, and as soon as it finds one that is false, it stops evaluating, so the validating is done before you try to access an array element that is out of bounds.
(PlayerChoice-1)/3 will evaluate to the size column properly, so if the user inputs 3, minus 1 is 2, divided by 3, integer division always rounds down to 0. If the user inputs 4, minus 1 is 3, divided by 3 is one, so it would be in column 1 (the second column).
(PlayerChoice-1)%3 likewise does the previous, then chooses the row based on the remainder.
char(PlayerChoice + '0') converts a single digit number to the character equivalant. It adds the decimal value of '0' (the first number in ascii, 48) to the number the user entered, then converts that to a char. So if the user enters 3, 3 + 48 is 51, 51 as a char is '3', which would then be compared to the char held in the array.