So I am looking back on a tic tac toe project I worked on for a previous class, and found something that bugs me now as it did when I worked on it. It is this large clump of code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
if (arrStorage[0][0] == 'X' && arrStorage[0][1] == 'X' && arrStorage[0][2] == 'X' || //X Across first row
arrStorage[1][0] == 'X' && arrStorage[1][1] == 'X' && arrStorage[1][2] == 'X' || //X Across Second Row
arrStorage[2][0] == 'X' && arrStorage[2][1] == 'X' && arrStorage[2][2] == 'X' || //X Across Third Row
arrStorage[0][0] == 'X' && arrStorage[1][0] == 'X' && arrStorage[2][0] == 'X' || //X Down First Row
arrStorage[0][1] == 'X' && arrStorage[1][1] == 'X' && arrStorage[2][1] == 'X' || //X Down Second Row
arrStorage[0][2] == 'X' && arrStorage[1][2] == 'X' && arrStorage[2][2] == 'X' || //X Down Third Row
arrStorage[0][0] == 'X' && arrStorage[1][1] == 'X' && arrStorage[2][2] == 'X' || //X Diagonal Top left
arrStorage[0][2] == 'X' && arrStorage[1][1] == 'X' && arrStorage[2][0] == 'X' || //X Diagonal Top Right
arrStorage[0][0] == 'O' && arrStorage[0][1] == 'O' && arrStorage[0][2] == 'O' || //O Across first row
arrStorage[1][0] == 'O' && arrStorage[1][1] == 'O' && arrStorage[1][2] == 'O' || //O Across Second Row
arrStorage[2][0] == 'O' && arrStorage[2][1] == 'O' && arrStorage[2][2] == 'O' || //O Across Third Row
arrStorage[0][0] == 'O' && arrStorage[1][0] == 'O' && arrStorage[2][0] == 'O' || //O Down First Row
arrStorage[0][1] == 'O' && arrStorage[1][1] == 'O' && arrStorage[2][1] == 'O' || //O Down Second Row
arrStorage[0][2] == 'O' && arrStorage[1][2] == 'O' && arrStorage[2][2] == 'O' || //O Down Third Row
arrStorage[0][0] == 'O' && arrStorage[1][1] == 'O' && arrStorage[2][2] == 'O' || //O Diagonal Top left
arrStorage[0][2] == 'O' && arrStorage[1][1] == 'O' && arrStorage[2][0] == 'O') //O Diagonal Top Right
{
I have tried experimenting with ways to significantly shorten this without getting overtly complicated but I am having no luck. I would love some advice as to how I could approach simplifying this.
when the user takes a turn,
the square that was modified on that turn,
check that square's row, column, and if applicable, diagonals for a win.
That would simplify the logic greatly. First, you don't check things not affected by the turn, and second, you only check the letters for the turn-taker, cutting work in half. (that is, if X just moved, you don't need to know if O just won the game). Count the # of turns taken. If turn == 9 and didnt just win, is drawn.