Python3 OOP Tic-Tac-Toe

I’m studying Object-oriented Programming and decided to apply some things doing an Object-oriented Tic-Tac-Toe.
I wanted to know if you have some hints of what to improve and why!

class Board:     """Represents one board to a Tic-Tac-Toe game."""      def __init__(self):         """Initializes a new board.         A board is a dictionary which the key is the position in the board         and the value can be 'X', 'O' or ' ' (representing an empty position         in the board.)"""         self.board = {                 "TL": " ", "TM": " ", "TR": " ",                 "ML": " ", "MM": " ", "MR": " ",                 "BL": " ", "BM": " ", "BR": " "}      def print_board(self):         """Prints the board."""         print(self.board["TL"] + "|" + self.board["TM"] \             + "|" + self.board["TR"] + "|")         print("-+" * 3)         print(self.board["ML"] + "|" + self.board["MM"] \             + "|" + self.board["MR"] + "|")         print("-+" * 3)         print(self.board["BL"] + "|" + self.board["BM"] \             + "|" + self.board["BR"] + "|")      def _is_valid_move(self, position):         if self.board[position] is " ":             return True         return False      def change_board(self, position, type):         """Receive a position and if the player is 'X' or 'O'.         Checks if the position is valid, modifies the board and returns the modified board.         Returns None if the move is not valid."""         if self._is_valid_move(position):             self.board[position] = type             return self.board         return None      def is_winner(self, player):         """Returns True if the player won and False otherwise."""         if self.board["TL"] == player.type and self.board["TM"] == player.type and self.board["TR"] == player.type or \         self.board["ML"] == player.type and self.board["MM"] == player.type and self.board["MR"] == player.type or \         self.board["BL"] == player.type and self.board["BM"] == player.type and self.board["BR"] == player.type or \         self.board["TL"] == player.type and self.board["ML"] == player.type and self.board["BL"] == player.type or \         self.board["TM"] == player.type and self.board["MM"] == player.type and self.board["BM"] == player.type or \         self.board["TR"] == player.type and self.board["MR"] == player.type and self.board["BR"] == player.type or \         self.board["TL"] == player.type and self.board["MM"] == player.type and self.board["BR"] == player.type or \         self.board["BL"] == player.type and self.board["MM"] == player.type and self.board["TR"] == player.type:             return True         return False   class Player:     """Represents one player."""     def __init__(self, type):         """Initializes a player with type 'X' or 'O'."""         self.type = type      def __str__(self):         return "Player {}".format(self.type)   class Game:     """Represents a Tic-Tac-Toe game.     The game defines player 1 always playing with 'X'."""     def __init__(self):         """Initilize 2 Players and one Board."""         self.player1 = Player("X")         self.player2 = Player("O")         self.board = Board()      def print_valid_entries(self):         """Prints the valid inputs to play the game."""         print("""             TL - top left    | TM - top middle    | TR - top right             ML - middle left | MM - center        | MR - middle right             BL - bottom left | BM - bottom middle | BR - bottom right""")      def printing_board(self):         """Prints the board."""         self.board.print_board()      def change_turn(self, player):         """Changes the player turn.         Receives a player and returns the other."""         if player is self.player1:             return self.player2         else:             return self.player1      def won_game(self, player):         """Returns True if the player won the game, False otherwise."""         return self.board.is_winner(player)      def modify_board(self, position, type):         """Receives position and player type ('X' or 'O').         Returns modified board if position was valid.         Asks to player try a different position otherwise."""         if self.board.change_board(position, type) is not None:             return self.board.change_board(position, type)         else:             position = input("Not available position. Please, try again: ")             return self.board.change_board(position, type)   def play():     game = Game()     game.print_valid_entries()     player = game.player1     num = 9     while num > 0:         num -= 1         game.printing_board()         position = input("{} turn, what's your move? ".format(player))         game.modify_board(position, player.type)         if game.won_game(player):             print("{} is the Winner!".format(player))             break         else:             player = game.change_turn(player)     if num == 0:         print("Game over! It's a tie!")   if __name__ == "__main__":     play()  

Improved computer AI in TicTacToe

I was just passing by and I wanted to know how to improve my TicTacToe game by adding “intelligence” to the computer AI so it can block my movements and so on.

#include <iostream> #include <string>     #include <stdlib.h> rand(); #define dim_m 3 using namespace std;  class Tic_Tac_Toe{  private:  char matrix[dim_m][dim_m]; public:  void checking_for_wins(){     const char* wins_possibilities[8] = {"123","456","789","159","753","147","258","369"};      for (int i =0;i<8;i++){         bool win = true;         char prev_op = '0';         const char* win_possibility = wins_possibilities[i]; //funciona como puntero en caso de que se cumpla uno de las wins_possibilities[]          for (int rcl = 0;rcl<dim_m;rcl++){                 char alphaChar = win_possibility[rcl];                  int intr_number = alphaChar - '0';                 int op_sp = intr_number - 1;                  int row = op_sp / dim_m;    //busca la posición de la fila                 int column = op_sp % dim_m; //busca la posición de la columna                  char current_op = matrix[row][column];                      if (prev_op == '0'){                         prev_op = current_op;                     }else if (prev_op == current_op){                         continue;                     }else{                         win = false;                         break;                     }         }                 if (win){                     cout << "Felicidades, ganaste!! \n";                     cout << "El jugador "<<prev_op<<" gana, felicidades! \n";                     exit(0);                     break;                 }     } } void player_turn(){     string input;     while(true){         cout << "\nEscoja la posicion donde quiere jugar: ";         cin >> input;     if (input != ""){         char intr = input.c_str()[0]; //cambia el valor de char por un int para poder operarlo          if (intr >= '1' && intr <= '9' ){             int intr_number = intr - '0';             int op = intr_number - 1;             int row = op/3; //revisa y ejecuta la posición de la fila             int column = op%3; //revisa y ejecuta la posicion de la columna             char matrix_pos = matrix[row][column];                 if (matrix_pos == 'X' || matrix_pos == 'O'){                     cout << "Esa posicion ya esta tomada!\n";                 }else{                     matrix[row][column] = 'X';                     break;                 }         }else{             cout << "La opcion elegida debe estar entre el rango de 1 a 9!"<<endl;         }     }else{         cout << "Debe elegir alguna opción! "<<endl;     }     } } void ia_turn(){     while (true){         int ia_tu = (rand() % 9) +1;         int ia_op = ia_tu - 1;          int row = ia_op / 3;         int column = ia_op % 3;      char matrix_pos = matrix[row][column];             if (matrix_pos == 'X' || matrix_pos == 'O'){ //si se cumple la condicion, se eligirá otro numero aleatorio                 continue;             }else{                 cout << "El IA eligio la posicion "<<ia_tu<<endl;                 matrix[row][column] = 'O';                 break;             }     } } void genGrid(){     int digit = 1;     for (int i=0;i<dim_m;i++){     for (int j=0;j<dim_m;j++){     matrix[i][j] = to_string(digit).c_str()[0];     digit += 1;     }     } } void showGrid(){         printf(" -------------\n");     for (int i=0;i<dim_m;i++){         printf(" |");     for (int j=0;j<dim_m;j++){         printf(" %c |" , matrix[i][j]);         }         printf("\n -------------\n");         }     } Tic_Tac_Toe(){          genGrid();         showGrid();         checking_for_wins();     while (true){     player_turn();         showGrid();         checking_for_wins();     ia_turn();         checking_for_wins();         showGrid();     }  } };  int main(int argc, char *argv[] ) { Tic_Tac_Toe play;  return 0; } 

TicTacToe classic in C

I’m learning myself C and to make sure that I learn to code C in a proper way I created tic tac toe and want to hear your opinion on what I should do and what I shouldn’t do.

One thing is sure is to divide the code up in several files maybe but outside of that.

The code:

#include <stdio.h> #include <stdlib.h>  #define ROWS 3 #define BOARD_SIZE ROWS * ROWS  typedef enum { false, true } bool;  bool enter_entry(char *board, char character, int x, int y); void print_board(const char *board); void *init_board(); bool is_solved(char *board, char item); bool is_draw(char *board); bool is_equal(char *board, int indexA, int indexB, int indexC, char item); void player_selection(char *board, char item); void game_loop(char *board);  int main() {     char *board = init_board();     game_loop(board);     return 0; }  void *init_board() {     char *board = malloc(sizeof(char) * BOARD_SIZE);     for(int i = 0; i < BOARD_SIZE; i++)     {         board[i] = ' ';     }     return board; }  void print_board(const char *board) {     for(int i = 1; i < BOARD_SIZE+1; i++)     {         printf("| %c ", board[i-1]);         if(i % 3 == 0)         {             printf("|\n");                 }     }     printf("\n"); }  bool is_solved(char *board, char item) {     if(is_equal(board, 0, 1, 2, item)) { return true; }     if(is_equal(board, 3, 4, 5, item)) { return true; }     if(is_equal(board, 6, 7, 8, item)) { return true; }      if(is_equal(board, 0, 3, 6, item)) { return true; }     if(is_equal(board, 1, 4, 7, item)) { return true; }     if(is_equal(board, 2, 5, 8, item)) { return true; }      if(is_equal(board, 0, 4, 8, item)) { return true; }     if(is_equal(board, 2, 4, 6, item)) { return true; }     return false; }  bool is_draw(char *board) {     for(int i = 0; i < BOARD_SIZE; i++)     {         if(board[i] == ' ')         {             return false;         }     }     return true; }  bool is_equal(char *board, int indexA, int indexB, int indexC, char item) {     if(board[indexA] == item && board[indexB] == item && board[indexC] == item)     {         return true;     }     return false; }  bool enter_entry(char *board, char character, int x, int y) {     int index = x + ROWS * y;      if(board[index] != ' ')     {         return false;     }      board[index] = character;     return true; }  void player_selection(char *board, char item) {     int x, y;     printf("enter coords (x, y): \n");      while(1)     {         scanf(" %d %d", &x, &y);         bool succes = enter_entry(board, item, x-1, y-1);         if(succes)         {             break;         }         printf("This coord is already used or not valid enter new ones:\n");     }     print_board(board); }  void game_loop(char *board) {     char playerOneChar = 'o';     char playerTwoChar = 'x';      printf("Welcome to tic tac toe!\n");     printf("Press enter to continue\n");     char enter = 0;     while (enter != '\r' && enter != '\n') { enter = getchar(); }      printf("Let's start the game!\n");     print_board(board);      while(1)     {         printf("Player one: \n");         player_selection(board, playerOneChar);         if(is_solved(board, playerOneChar))         {             printf("PLayer one won!\n");             break;         }          if(is_draw(board))         {             printf("No winners!\n");             break;         }          printf("Player two: \n");         player_selection(board, playerTwoChar);         if(is_solved(board, playerOneChar))         {             printf("PLayer two won!");             break;         }         if(is_draw(board))         {             printf("No winners!\n");             break;         }     } } 

Thank you in advance!

Improved first Tic-Tac-Toe + Minimax AI

Posted my first attempt at Tic-Tac-Toe a second ago here. Got a lot of great and helpful responses. The main things I took away from the responses I received is to use spell check, and to keep things simple. Wanted to give it a second go before moving on to something a bit bigger.

Learned about the Minimax algorithm from this article. It doesn’t work exactly like I’d hope but I can’t tell if its just the pitfalls of the algorithm or my code.

I’m greatful for any critique or pointers.

tictactoe.h

#ifndef TICTACTOE #define TICTACTOE #include <bitset> #include <iostream> #include <vector>  enum class BoardValue{ none, o, x};  class Board { public:     Board() = default;     Board(const Board& board): o_bits(board.o_bits), x_bits(board.x_bits) {};     BoardValue at(int index) const;     bool check_tie() const;     bool check_win(bool) const;     bool place(int, bool);     std::vector<int> possible_moves() const; private:     std::bitset<9> o_bits{};     std::bitset<9> x_bits{};     std::bitset<9> filled_bits() const{ return o_bits | x_bits; } };  class AI { public:     AI(bool o) : is_o(o) {};     int best_move(const Board&); private:     int minimax(const Board&, int, bool);      int choice{};     bool is_o; //is the ai playing as 'O' }; #endif 

tictactoe.cpp

#include "tictactoe.h" #include <bitset> #include <iostream> #include <limits> #include <stdexcept> #include <string> #include <vector>  BoardValue Board::at(int index) const{     if(index < 0 || 8 < index) throw std::out_of_range{ "Index out of Board range" };     if(filled_bits().test(index) == true)     {         return (o_bits.test(index) ? BoardValue::o : BoardValue::x);     }     else return BoardValue::none; }  bool Board::check_tie() const {     std::bitset<9> full_board{ "111111111" };     if( full_board == (filled_bits() & full_board) ) return true;     return false; }  bool Board::check_win(bool o) const {     const std::bitset<9>& bits = o ? o_bits : x_bits; //bits to be checked      //diagonals     if(bits.test(4) != false) //if middle is not taken no diagonals will pass     {         std::bitset<9> forward_diagonal{ "100010001" }; //bits of '\'         std::bitset<9> backward_diagonal{ "001010100" }; //bits of '/'         if(forward_diagonal == (bits & forward_diagonal)) return true;         if(backward_diagonal == (bits & backward_diagonal)) return true;     }      //columns and rows     std::bitset<9> col_check{ "001001001" }; //bits of the first column/row     std::bitset<9> row_check{ "000000111" };     for(int i = 0; i < 3; ++i) // loop for all 3 columns and rows     {         if(col_check == (bits & col_check)) return true;         if(row_check == (bits & row_check)) return true;         col_check = col_check << 1; //move over a column/row over         row_check = row_check << 3;     }      return false; }  //returns false if index is occupied bool Board::place(int index, bool o) {     if(at(index) != BoardValue::none) return false;      std::bitset<9>& bits = o ? o_bits : x_bits; //bits to be changed     bits.set(index);     return true; }  //returns indexes of free spaces //all returned indexes will return true when used in place(int,bool) std::vector<int> Board::possible_moves() const {     const std::bitset<9> bits = filled_bits();     std::vector<int> moves{};     //loop through each bit and add the index of the ones that are 0 to possible_moves     for(int i = 0; i < 9; ++i)     {         if( bits.test(i) == false)         {             moves.push_back(i);         }     }     return moves; }  int AI::best_move(const Board& board) {     minimax(board, 0, true);     return choice; }  int AI::minimax(const Board& position, int depth, bool maxPlayer) {     //check position game state and return score if game is lost, won, or tied     if(position.check_win(!is_o)) //AI loses     {         return depth - 10;     }     else if(position.check_win(is_o)) //AI wins     {         return 10 - depth;     }     else if(position.check_tie())     {         return 0;     }      //do minimax calculation     if(maxPlayer)     {         int max_move{};         int max_move_score{ std::numeric_limits<int>::min()};         for(int move : position.possible_moves())         {             Board possible_position{ position };             possible_position.place(move, is_o);             int score = minimax(possible_position, ++depth, false);             if ( score > max_move_score )             {                 max_move = move;                 max_move_score = score;             }         }          choice = max_move;//last call to this will be at first call to minimax() from best_move()         return max_move_score; //return max score     }     else     {         int min_move{};         int min_move_score{ std::numeric_limits<int>::max()};         for(int move : position.possible_moves())         {             Board possible_position{ position };             possible_position.place(move, !is_o);             int score = minimax(possible_position, ++depth, true);             if ( score < min_move_score )             {                 min_move = move;                 min_move_score = score;             }         }          return min_move_score; //return max score     } } 

main.cpp

#include "tictactoe.h" #include <array> #include <ctime> #include <iostream> #include <random> #include <string>  int ask_player_input() {     bool retry{ false };     int index{};      std::cout << "It's your turn. Where do you want to go(e.g. A1 B3 C2)? ";     do{         if(retry)         {             std::cout << "No, no, no! Input a letter followed by a number: ";         }         retry = false; //reset retry          std::string input;         std::cin >> input;         if(input.size() < 2)         {             retry = true;             continue;         }          //letter input         int col_input{};         switch(input.at(0))         {             case 'A':             case 'a':                 col_input = 0;                 break;             case 'B':             case 'b':                 col_input = 1;                 break;             case 'C':             case 'c':                 col_input = 2;                 break;             default:                 retry = true;                 continue;         }          //number input         int row_input = input.at(1) - '0'; //converts char '2' to int 2         if(--row_input < 0 || 3 < row_input)         {             retry = true;             continue;         }          index = col_input * 3 + row_input;     } while( retry );     return index; }  bool ask_turn() //ask who will go first if return true O goes first {     bool turn{};     std::string input;     std::cout << "Who do you want to be?(X or O)? ";     for(bool valid_input{false}; !valid_input;)     {         std::cin >> input;         switch(input.front()) //input cannot be null at this point         {             case 'x':             case 'X':                 valid_input = true;                 turn = false;                 break;             case '0':             case 'o':             case 'O':                 valid_input = true;                 turn = true;                 break;             default:                 std::cout << "Invalid input! Try X or O :";         }     }     return turn; }  std::ostream& print_board(std::ostream& os,const Board& board) {     os << " |A|B|C\n";     for(int row = 0; row < 3; ++row)     {         os << std::string( 8, '-') << '\n';         os << row + 1 << '|';         for(int col = 0; col < 3; ++col)         {             char follow_char{ col == 2 ? '\n' : '|' };             char place_char{};              //determine character to print for this board place on the board             BoardValue place_value  = board.at(col * 3 + row);             if(place_value == BoardValue::none) place_char = ' ';             else place_char = place_value == BoardValue::o ? 'O' : 'X';              os << place_char << follow_char;         }     }     os << '\n';     return os; }  std::ostream& operator<<(std::ostream& os,const Board& board) {     return print_board(os, board); }  int main(){     std::default_random_engine e{ static_cast<long unsigned int>(time(NULL)) };     bool turn{ e() % 2 };     bool player_turn{ ask_turn() };     Board board{};     AI ai{ !player_turn };      if(turn != player_turn)//player first, turns will be flipped at start of game loop     {         std::cout << "You go first!\n" << board;     }     else      {         std::cout << "Computer gets to go first this time. Good luck!\n";     }      while(board.check_win(turn) == false && board.check_tie() == false)     {         turn = !turn;         if(turn == player_turn)         {             bool input_valid{false};             while(input_valid == false)             {                 int input;                 input = ask_player_input();                 input_valid = board.place(input, turn);                 if( input_valid == false )                     std::cout << "That place is take! Try again...\n";             }         }         else //AI turn         {             int best_move = ai.best_move(board);             board.place( best_move, turn);              std::cout << board;             //print AI turn             std::array<char,3> col_chars = { 'A', 'B', 'C' };             char col_input = col_chars.at( best_move % 3 );             int row_input = ((best_move + 1) / 3) + 1;              std::cout << "Computer picks " << col_input << row_input << '\n';         }     }     std::cout << board;     if(board.check_tie())     {         std::cout << "Looks like its a tie...\n";     }     else      {         std::cout << (turn == player_turn ? "You won!" : "The computer wins..." )  << '\n';     } } 

Tic-tac-toe for the terminal, written in C

I recently started learning C, and this is my first fairly large (to me) program. It’s a basic tic tac toe game for the console. There’s no ai, it’s just a 2 player game. Anything I can improve?

// Tic Tac Toe in C. V1.0 by James 26/05/2019  #include <stdio.h> #include <stdlib.h> #include <stdbool.h>  #define SIZE 3  // Draws the board along with rows/cols, numbered. void draw_board(char board[]) {     system("clear");     printf("# 1 2 3\n");      // Rows     for (int i = 0, n = 0; i < SIZE; i++)     {         // Columns         printf("%d ", i + 1);         for (int j = 0; j < SIZE; j++)         {             printf("%c ", board[n]);             n++;         }         printf("\n");     } }  // Initializes board to '-' characters. void init_board(char board[]) {     for (int i = 0; i <  SIZE * SIZE; i++)     {         board[i] = '-';     } }  // Returns true if the piece was successfully placed, // false if the position was invalid or already taken. bool place(char board[], char player) {     char posinput[64];      printf("%c, pick your position (xy, rc): ", player);     scanf("%s", posinput); // <-- I realise that this is potentially bad, but realistically,                             // the user would have to be trying to break something, and                            // this is just a little program I made for practice.      int row = (posinput[0] - '0') - 1;     int col = (posinput[1] - '0') - 1;      int pos = col + row * SIZE;      if (pos >= 0 && pos < SIZE * SIZE)     {         if (board[pos] == 'x' || board[pos] == 'o')             return false;          board[pos] = player;         return true;     }      return false; }  // Returns true if there are three of the same chars in a row. // b = board, p = player. Shortened for readability. bool check(char b[], char p)  {     // Check rows     if (b[0] == p && b[1] == p && b[2] == p)         return true;     if (b[3] == p && b[4] == p && b[5] == p)         return true;     if (b[6] == p && b[7] == p && b[8] == p)         return true;       // Check columns     if (b[0] == p && b[3] == p && b[6] == p)         return true;     if (b[1] == p && b[4] == p && b[7] == p)         return true;     if (b[2] == p && b[5] == p && b[8] == p)         return true;       // Check diagonals     if (b[0] == p && b[4] == p && b[8] == p)         return true;     if (b[2] == p && b[4] == p && b[6] == p)         return true;      // If no one won, return false     return false; }  int main(void) {     char board[SIZE * SIZE];     char player = 'x';     init_board(board);      while (true)     {         draw_board(board);          if (place(board, player))         {             if (check(board, player))                 break;              if (player == 'x')                 player = 'o';             else                 player = 'x';         }     }      draw_board(board);     printf("-----------------------------\n");     printf("Player %c wins!!!\n", player);     printf("-----------------------------\n"); } 

Python program to know who wins a tic-tac-toe game

Given an input where we have two players: “X” and “O”, and empty cells marked with a “.” like:

check_winner([ “X.O”, “XX.”, “XOO”])

the program outputs if there are three “X” or “O” in horizontal, vertical or diagonal. If there is a draw it outputs “D”.

expected results

def check_winner(game_result: List[str]) -> str:      for i, row in enumerate(game_result):         if game_result[i][0] == game_result[i][1] == game_result[i][2]:             if game_result[i][0] != ".":                 return game_result[i][0]         if game_result[0][i] == game_result[1][i] == game_result[2][i]:             if game_result[0][i] != ".":                 return game_result[0][i]      if game_result[0][0] == game_result[1][1] == game_result[2][2]:         if game_result[1][1] != ".":             return game_result[1][1]      if game_result[0][2] == game_result[1][1] == game_result[2][0]:         if game_result[1][1] != ".":             return game_result[1][1]      return "D" 

How could we improve this code?

First Program Tic-Tac-Toe. Trouble with abstraction?

This is the first little project I’ve made that didn’t feel it was complete gibberish. But I couldn’t tell.

The biggest problem I had with this was using the BoardValue enum working like I wanted to. I understand that classes should have a level of abstraction to them and I suspect that the way I implemented the at(int) returning a char over a BoardValue took away from that. However, I though having to convert the return from at(int) to a char if it returned a BoardValue would be redundant. For example, using a statement like this

char print_char = Board.at(some_index) == BoardValue::o ? 'O' : 'X'; 

I hope I’ve done a decent job describing my dilemma.

Overall, I’m hoping for some overall general code style tips and pointers on how to write better code from here.

tictactoe.h

#ifndef TICTACTOE #define TICTACTOE #include <array> #include <iostream>  enum BoardValue : char{ none = ' ', o = 'O', x = 'X' };  class Board { public:     Board()     {         for(auto begin = board.begin(),end = board.end();begin != end; ++begin)             *begin = BoardValue::none;     }      char at(int index) const{ return board.at(index); }     inline bool check_win(BoardValue) const;     bool place(int, BoardValue); private:     bool check_diagonals(BoardValue) const;     bool check_horizontals(BoardValue) const;     bool check_verticals(BoardValue) const;      std::array<char, 9> board{}; };  inline bool Board::check_win(BoardValue check) const {     if(check == BoardValue::none)         throw "Trying to check_win for check == BoardValue::none!";     return check_diagonals(check) || check_horizontals(check) || check_verticals(check); }  #endif 

tictactoe.cpp

#include "tictactoe.h" #include <iostream>  //returns false if index is occupied bool Board::place(int index, BoardValue value) {     if(board.at(index) != BoardValue::none)         return false;     board.at(index) = value;     return true; }  bool Board::check_diagonals(BoardValue check) const {     //if middle is not check no diagnols will pass     if(board.at(4) != check)         return false;     //backward diagonal '\'     if(board.at(0) == check && board.at(4) == check)         return true;     //forward diaganol '/'     if(board.at(2) == check && board.at(6) == check)         return true;     return false; }  bool Board::check_horizontals(BoardValue check) const {     for(int row = 0; row < 3; ++row){         if(board.at(row) == check &&             board.at(row + 3) == check &&             board.at(row + 6) == check)             return true;     }     return false; }  bool Board::check_verticals(BoardValue check) const {     for(int col = 0; col < 3; ++col){         if(board.at(col * 3) == check &&             board.at(col * 3 + 1) == check &&             board.at(col * 3 + 2 ) == check)             return true;     }     return false; } 

main.cpp

#include "tictactoe.h" #include <iostream>  int ask_input(char player, bool retry = false) {     if(!retry)         std::cout << "It's " << player             << "'s turn. Where do you want to go(e.g. A1 B3 C2)? ";     else         std::cout << "No, no, no " << player             << "! Input a letter followed bt a number: ";     std::string input;     std::cin >> input;      if(input.size() < 2)         return ask_input(player, true);      int col_input{};     switch(*input.begin())     {         case 'A':         case 'a':             col_input = 0;             break;         case 'B':         case 'b':             col_input = 1;             break;         case 'C':         case 'c':             col_input = 2;             break;         default:             return ask_input(player, true);     }      int row_input = *(input.begin() + 1) - '0'; //convers char '1' to int 1     --row_input;      return col_input * 3 + row_input; }  BoardValue ask_turn() //ask whos first if return true O goes first {     BoardValue turn;     std::string input;     std::cout << "Who goes first(X or O)? ";     for(bool valid_input{false}; !valid_input;)     {         std::cin >> input;         switch(input.front()) //input cannot be null at this point         {             case 'x':             case 'X':                 valid_input = true;                 turn = BoardValue::x;                 break;             case '0':             case 'o':             case 'O':                 valid_input = true;                 turn = BoardValue::x;                 break;             default:                 std::cout << "Invalid input! Try X or O :";         }     }     return turn; }  std::ostream &print_board(std::ostream &os,const Board &board) {     os << " |A|B|C\n";     for(int row = 0; row < 3; ++row)     {         os << std::string( 8, '-') << '\n';         os << row + 1 << '|';         for(int col = 0; col < 3; ++col)         {             char follow_char{ col == 2 ? '\n' : '|' };             os << board.at(col * 3 + row) << follow_char;         }     }     os << std::endl;     return os; }  int main(){     Board board{};     BoardValue turn{ ask_turn() };      //turn will be set back to appropriate value at start of game loop     turn = turn == BoardValue::o  ? BoardValue::x : BoardValue::o;     int turn_count{0};     while(board.check_win(turn) == false)     {         turn = turn == BoardValue::o  ? BoardValue::x : BoardValue::o;         print_board(std::cout, board);         bool input_valid{false};         while(input_valid == false)         {             int input;             input = ask_input(turn);             input_valid = board.place(input, turn);             if( input_valid == false )                 std::cout << "That place is take! Try again..\n";         }         if(++turn_count == 9) //max amount of turns game is tie             break;     }     print_board(std::cout, board);     if(turn_count == 9)//game is tie         std::cout << "Looks like its a tie...\n";     else         std::cout << (char)turn << " wins!\n"; } 

Tic-Tac-Toe code in JavaScript

I have developed a tic-tac-toe game in native JavaScript. Can you tell me how to optimize more and what are the missing things? JSBIN

The logic, modular approach, testable and scalable?

(function() {   var playerOneData = {     name: null,     arr: []   };   var playerTwoData = {     name: null,     arr: []   };   winnerFound = false;   var clickCount = 2;    var start = document.getElementById('start');   var resultsList = [     [0, 1, 2],     [3, 4, 5],     [6, 7, 8],     [0, 3, 6],     [1, 4, 7],     [2, 5, 8],     [0, 4, 8],     [2, 4, 6],   ];   var setApplicationView = function(screenId, display) {     //     hide user infor form     document.getElementById(screenId).style.display = display;   };   start.addEventListener('click', function() {     //     fetch username     playerOneData.name = document.getElementById('player-one-name').value;     playerTwoData.name = document.getElementById('player-two-name').value;     //     hide user info form     setApplicationView('user', 'none');     //     show game board     setApplicationView('game-board', 'block');     //     set the player's name     document.querySelector('#p1-info span').innerHTML = playerOneData.name;     document.querySelector('#p2-info span').innerHTML = playerTwoData.name;   });    var ifClicked = function(index, tile) {     var i = 0;     while (i < tile.length) {       if (index == tile[i])         return false;       i++;     }     return true   };   var selectedTiles = [];    var winnerFinder = function(playersData, resultsList) {     if(playersData.arr.length<2) return true;     var player = playersData.arr;     var i = 0;     resultsList.forEach(function(element) {       i = 0;       player.forEach(function(ele) {         if (element.indexOf(ele) >= 0) {           i++;         }       });       if (i == element.length) {         matrix.removeEventListener('click', startMatrix);         document.getElementById('result').innerHTML = "Winner is " + playersData.name;         winnerFound = true;         return false;       }     });   };   var matrix = document.getElementById('matrix');   var startMatrix = function($  event) {     var target = $  event.target;     var tileIndex = +target.getAttribute('tile-index');     var alreadyClickedStatus = ifClicked(tileIndex, selectedTiles);     if (target.className === 'tile' && alreadyClickedStatus === true) {       selectedTiles.push(tileIndex);         if (clickCount % 2 === 0) {         playerOneData.arr.push(tileIndex);         target.className = 'tile red';          if (winnerFinder(playerOneData, resultsList) === false) {           matrix.removeEventListener('click', startMatrix);         }       } else {         playerTwoData.arr.push(tileIndex);         target.className = 'tile blue';         if (winnerFinder(playerTwoData, resultsList) === false) {           matrix.removeEventListener('click', startMatrix);         }       }        clickCount++;       if (clickCount === 11 && winnerFound === false) {         document.getElementById('result').innerHTML = 'Match drawn';       }     }   }   matrix.addEventListener('click', startMatrix);   var resetBoard = function() {     winnerFound = false;     clickCount = 2;     matrix.addEventListener('click', startMatrix);     document.getElementById('result').innerHTML = '';     selectedTiles = [];     var tile = document.querySelectorAll('.tile')     tile.forEach(function(ele, index) {       tile[index].className = 'tile';     });     playerOneData.arr = [];     playerTwoData.arr = [];   };   var restart = document.getElementById('restart');   restart.addEventListener('click', function() {      resetBoard();   });   var newGame = document.getElementById('new-game');   newGame.addEventListener('click', function() {     //     show user info form     setApplicationView('user', 'block');     //     hide game board     setApplicationView('game-board', 'none');     resetBoard();   }); })(); 

TicTacToe Board Check

I have written a code in C# that checks whether the user have won the TicTacToe game. I feel that maybe there is a more elegant way to check it, but I couldn’t find one. Would like your help.

public static bool CheckWinnings(string[,] gameboardsquares) {     bool iscontinue = true;      //rows;     if (gameboardsquares[0,0] == gameboardsquares[0,1] && gameboardsquares[0,1] == gameboardsquares[0,2] && gameboardsquares[0,0] != " ")     {         iscontinue = false;     }     else if (gameboardsquares[1,0] == gameboardsquares[1,1] && gameboardsquares[1,1] == gameboardsquares[1,2] && gameboardsquares[1,0] != " ")     {         iscontinue = false;     }     else if (gameboardsquares[2,0] == gameboardsquares[2,1] && gameboardsquares[2,1] == gameboardsquares[2,2] && gameboardsquares[2,0] != " ")     {         iscontinue = false;     }      //columns;     else if (gameboardsquares[0,0] == gameboardsquares[1,0] && gameboardsquares[1,0] == gameboardsquares[2,0] && gameboardsquares[0,0] != " ")     {         iscontinue = false;     }     else if (gameboardsquares[0,1] == gameboardsquares[1,1] && gameboardsquares[1,1] == gameboardsquares[2,1] && gameboardsquares[0,1] != " ")     {         iscontinue = false;     }     else if (gameboardsquares[0,2] == gameboardsquares[1,2] && gameboardsquares[1,2] == gameboardsquares[1,2] && gameboardsquares[0,2] != " ")     {         iscontinue = false;     }      //diagonals;     else if (gameboardsquares[0,0] == gameboardsquares[1,1] && gameboardsquares[1,1] == gameboardsquares[2,2] && gameboardsquares[0,0] != " ")     {         iscontinue = false;     }     else if (gameboardsquares[0,2] == gameboardsquares[1,1] && gameboardsquares[1,1] == gameboardsquares[2,0] && gameboardsquares[0,2] != " ")     {         iscontinue = false;     }      return iscontinue; } 

TIC-TAC-TOE Player vs Computer

I have created a logical AI for tic-tac game , i want a review about how good or bad it is . Here the computer AI will defend all your attacks as well as try to attack whenever it gets a chance . Below is the code you can directly try running it .

import java.util.Random;     import java.util.Scanner;      public class TicTac {         static {             System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t  ________________________    _______________________");             System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t |___  ___|___  ___|  ____|  |___  ___|   _   |  ____|");             System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t    |  |     |  |  |  |   ____  |  |  |  |_|  |  |");             System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t    |  |     |  |  |  |  |____| |  |  |   _   |  |");             System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t    |  |   __|  |__|  |___      |  |  |  | |  |  |___");             System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t    |__|  |________|______|     |__|  |__| |__|______|");             System.out.println("\n\n");         }          private Scanner sc = new Scanner(System.in);         private char board[] = new char[9];         private char turn = 'X';         private Random random = new Random();         private int winX = 0;         private int winO = 0;         private String name;         private char myChoice = 'O';          public static void main(String[] args) {             TicTac t = new TicTac();             int numberOfGames = 1;             long start, end;             start = System.currentTimeMillis();             do {                 t.play();                 numberOfGames--;                 System.out.println("\t\t\t\t\t\t\t\t\t\t\t----------------------------------------------------------------");             } while (numberOfGames > 0);             end = System.currentTimeMillis();             System.out.println("\n\t\t\t\t\t\t\t\t\t\t\tTime taken by the program to execute is : " + (end - start));         }          private void playersTurn() {             int r;             boolean check = false;             do {                 System.out.println("\n\n\t\t\t\t\t\t\t\twhere do you wnt to play , select from 1 - 9 :");                 try {                     r = getChoice();                     if (!(r > 0 && r < 10)) {                         Thread.sleep(1000);                         throw new NumberFormatException("Invalid Number");                     }                     r -= 1;                     if (board[r] == ' ') {                         board[r] = turn;                         check = true;                     } else if (board[r] == myChoice) {                         System.out.println("you already played there");                     } else {                         System.out.println("computer played there");                     }                 } catch (Exception e) {                     System.out.println("invalid choice. \t " + e);                 }             } while (!check);         }          private int getChoice() {             String x = "1";              try {                 x = sc.nextLine();                 if (x.matches("^[1-9]$  ")) {                  } else {                      throw new NumberFormatException("Invalid Number");                 }             } catch (Exception e) {                 System.out.println(e.getMessage());             }             return Integer.parseInt(x);         }          private void initializeBoard() {             for (int i = 0; i < 9; i++) {                 board[i] = ' ';             }         }          private void switchPlayer() {             if (turn == 'X') {                 turn = 'O';             } else if (turn == 'O') {                 turn = 'X';             }         }          private boolean win() {             for (int i = 0; i < 9; i++) {                 if (board[i] == ' ') {                     board[i] = turn;                     if (checkWin()) {                         return true;                     } else {                         board[i] = ' ';                     }                 }             }             return false;         }          private void attack() {             boolean check = false;             do {                 int r = random.nextInt(9);                 if (r == 1 || r == 3 || r == 5 || r == 7 || r != 4) {                     r = random.nextInt(9);                 }                 if (board[r] == ' ') {                     board[r] = turn;                     check = true;                 }             } while (!check);         }          private boolean defence() {             switchPlayer();             for (int i = 0; i < 9; i++) {                 if (board[i] == ' ') {                     board[i] = turn;                     if (checkWin()) {                         switchPlayer();                         board[i] = turn;                         return true;                     } else {                         board[i] = ' ';                     }                 }             }             switchPlayer();             return false;         }          private boolean filled() {             for (int i = 0; i < 9; i++) {                 if (board[i] == ' ') {                     return false;                 }             }             return true;         }          private void play() {             initializeBoard();             do {                 if (win()) {                     switchPlayer();                 } else if (defence()) {                     switchPlayer();                 } else {                     attack();                     switchPlayer();                 }                 display();                 if (turn == myChoice && !checkWin() && !filled()) {                     playersTurn();                     switchPlayer();                     display();                 }                 /*try {                     Thread.sleep(2000);                 } catch (InterruptedException e) {                     e.printStackTrace();                 }*/                 System.out.println("\n");             } while (!filled() && !checkWin());             if (checkWin()) {                 switchPlayer();                 if (turn == 'O') {                     winO++;                 } else {                     winX++;                 }                 System.out.println();                 display();                 System.out.println("\n");                 System.out.println("\t\t\t\t\t\t\t\t\t\t\t  " + turn + "  has won");             } else {                 System.out.println();                 display();                 System.out.println("\n");                 System.out.println("\t\t\t\t\t\t\t\t\t\t\t   game is draw... ");             }         }          private boolean checkWin() {             return (board[0] == board[1] && board[1] == board[2] && board[0] != ' ' || board[3] == board[4] && board[4] == board[5] && board[3] != ' ' || board[6] == board[7] && board[7] == board[8] && board[6] != ' ' || board[0] == board[4] && board[4] == board[8] && board[0] != ' ' || board[2] == board[4] && board[4] == board[6] && board[2] != ' ' || board[0] == board[3] && board[3] == board[6] && board[0] != ' ' || board[1] == board[4] && board[4] == board[7] && board[1] != ' ' || board[2] == board[5] && board[5] == board[8] && board[2] != ' ');         }          private void display() {              System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t " + board[0] + " | " + board[1] + " | " + board[2] + "           PLAYER 'O' | CPU  'X'");             System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t---|---|---            ---------|---------");             System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t " + board[3] + " | " + board[4] + " | " + board[5] + "                      |");             System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t---|---|---" + "\t   \t\t\t\t" + winO + "\t|\t" + winX);             System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t " + board[6] + " | " + board[7] + " | " + board[8] + "                      |");         }     }