#include using namespace std; /* The exact same code, but now implementing arrays for convenience. * While I discourage hard coding, I don't mind it in this case because * a tic-tac-toe grid is always fixed to be a 3x3 grid. If it were * meant to be expandable, then you'd have to avoid hard coding. */ int turn = 0, place; bool Xwin = false, Owin = false, invalid_input = false; string pos = " "; // 9 spaces, one for each grid // char arrays are strings, but access them by the index /* * 0 1 2 User Indicies: 1 2 3 * 3 4 5 4 5 6 * 6 7 8 7 8 9 */ char input_char; int main() { while(!Xwin && !Owin && turn < 9) { for(int i = 0; i < 7; i++) // 7 rows needed for grid { // Only odd rows contain X and O marks if(i % 2 == 0) cout << "+---+---+---+" << endl; else cout << "| " << pos[i*3/2 - 1] << " | " << pos[i*3/2] << " | " << pos[i*3/2 + 1] << " |" << endl; } if(turn % 2 == 0) input_char = 'X'; else input_char = 'O'; do { cout << "Place " << input_char << " at: "; cin >> place; cin.ignore(); if(place < 1 || place > 9) { invalid_input = true; cout << "Invalid input! 1-9 only.\n"; } else // An entire switch-case reduced to one line! invalid_input = (pos[place-1] != ' '); if(invalid_input) cout << "Invalid input! Position already filled.\n"; } while(invalid_input); // Another entire switch-case reduced to one line using arrays! pos[place-1] = input_char; if(turn >= 4) { // Row based victory for(int i = 0; i < 3; i++) if(pos[i*3] == pos[i*3+1] && pos[i*3+1] == pos[i*3+2]) { if(pos[i*3] == 'X') Xwin = true; else if(pos[i*3] == 'O') Owin = true; } // Column based victory for(int i = 0; i < 3; i++) if(pos[i] == pos[(i+1)*3] && pos[(i+1)*3] == pos[(i+2)*3]) { if(pos[i] == 'X') Xwin = true; else if(pos[i] == 'O') Owin = true; } // Diagonal based victory for(int i = 2; i <= 4; i += 2) if(pos[4] == pos[4-i] && pos[4] == pos[4+i]) { if(pos[i] == 'X') Xwin = true; else if(pos[i] == 'O') Owin = true; } } turn++; } // Display the final results for(int i = 0; i < 7; i++) // Print the grid one more time { if(i % 2 == 0) cout << "+---+---+---+" << endl; else cout << "| " << pos[i*3/2 - 1] << " | " << pos[i*3/2] << " | " << pos[i*3/2 + 1] << " |" << endl; } cout << "Game Over - "; if(Xwin) cout << "X wins!" << endl; else if(Owin) cout << "O wins!" << endl; else cout << "Draw" << endl; return 0; }