Feedback och konstruktiv kritik är välkommen, är lite av en nybörjare så skulle gärna veta vad ni tycker om mitt spel.
Kod:
/* Tic tac toe game */ #include <iostream> /* Clearing the tty */ #define CLEAR (std::cout << "\033[2J\033[;H") //ANSI escape sequence to clear tty class Game { private: char boards[9] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}; public: Game() {} void drawGame() { for (int i=0; i<9; i++) { if (i%3==0 && i!=0) std::cout << '\n'; std::cout << '[' << boards[i] << ']'; } } bool hasWon(char player) { #define IS_PLAYER(i) boards[i] == player /* Vertical checks */ if (IS_PLAYER(0) && IS_PLAYER(1) && IS_PLAYER(2)) return true; else if (IS_PLAYER(3) && IS_PLAYER(4) && IS_PLAYER(5)) return true; else if (IS_PLAYER(6) && IS_PLAYER(7) && IS_PLAYER(8)) return true; /* Horizontal checks */ else if (IS_PLAYER(0) && IS_PLAYER(3) && IS_PLAYER(6)) return true; else if (IS_PLAYER(1) && IS_PLAYER(4) && IS_PLAYER(7)) return true; else if (IS_PLAYER(2) && IS_PLAYER(5) && IS_PLAYER(8)) return true; /* Cross checks */ else if (IS_PLAYER(2) && IS_PLAYER(4) && IS_PLAYER(6)) return true; else if (IS_PLAYER(0) && IS_PLAYER(4) && IS_PLAYER(8)) return true; return false; } void setBoard(int i, char x) {boards[i] = x;} bool isSet(int i) {return (boards[i] == ' ' ? false : true);} }; char nextPlayer(char player) {return (player == 'X' ? 'O' : 'X');} int main(void) { Game game; std::cout << "Hi! Welcome to this tac-tac-toe game!\n"; std::cout << "X will start to make a move, then O.\n\n"; /* Game logic */ char player='X'; do { short board; game.drawGame(); std::cout << '\n'; std::cout << player << ", pick a board number (1 - 9): "; std::cin >> board; if (board <= 0 || board > 9) { CLEAR; std::cout << "Out of range, try again!!\n\n"; continue; } if (game.isSet(board-1)) { CLEAR; std::cout << "Oops, board " << board << " is already occupied.. Try again!\n\n"; continue; } game.setBoard(board-1,player); CLEAR; player = (nextPlayer(player)); } while (!game.hasWon('X') && !game.hasWon('O')); game.drawGame(); std::cout << "\nThree in a row! Congrats player " << nextPlayer(player) << ", you won!!\n"; exit(EXIT_SUCCESS); }