Search code examples
javascriptregextic-tac-toe

Tic-tac-Toe regex


I am working on a tic-tac-toe algo and am using regexes to solve for the win conditions. the 9 squares are given the 0-8 values:

[0][1][2]

[3][4][5]

[6][7][8]

Each time player 1 or 2 clicks a square the value is pushed to an array and after 3 values are collected the regex starts testing to see if a player has won.

the problem.. for example the regex test to see if any order of 012 102 exist but it can't match 03142.

How can I fix my Regex to look for the 3 numbers even if separated by other numbers?

Let regexWin =  /(?:^|\W)[012][012][012](?:$|\W)/gm,

Solution

  • You could keep track of the board state, so you don't need to rely on the moves list: define board as an array of length 9, initialised with all 0 (indicating each cell is empty). Then when a move is played set the corresponding slot to either "1" or "2", depending on which player plays that move.

    var board = Array(9).fill(0); // initial board
    var moves = []; // initial move list
    var turn = 1; // first player to move (other player is identified as 2)
    
    // ...
    
    function play(move) { // move is an index in board (0..8)
        board[move] = turn; // turn is 1 or 2
        moves.push(move); // this is the list you already have
        // Use regular expression to detect any 3-in-a-row
        let isWin = /^(?:...)*([12])\1\1|^.?.?([12])..\2..\2|^([12])...\3...\3|^..([12]).\4.\4/.test(board.join(""));
        console.log("is winning move?", isWin); 
        turn = 3 - turn; // toggle the player that is to move
    }
    

    This way you also can use board to update the display.

    For a full implementation, with rendering, and a minimax algorithm for generating a "best" move, see this answer.