Search code examples
algorithmtic-tac-toe

How to determine game end, in tic-tac-toe?


I'm developing tic-tac-toe game, and I need algorithm to check when game ends(and who win). In 3x3 game I would check each possible win-situation(there is 8 capabilities). But in 7x7(needed 4 signs in a row or collumn, or diagonal)is a lot of possible win patterns.


Solution

  • While a very basic approach is to look at runs in all the directions from every single cell, here are an approach then only ever checks a cell in a single "line" once. A "line" is a row, column, or diagonal that can possibly win, like in a Vegas slot machine :)

    1. For each "line", move to start of that "line" and;
    2. Set counter to 0.
    3. For each cell in the "line" (traversing the line in order):
      • If the cell is P1 and counter is >= 0, add one to counter
        • If counter = 4 then P1 wins.
      • If the cell is P1 and counter is negative, set counter to 0
      • If the cell is P2 and counter is <= 0, subtract one from counter
        • If counter = -4 then P2 wins
      • If the cell is P2 and counter is positive, set counter to 0

    Important Edit: If the cell contains neither P1 or P2, reset counter to 0 (doh!). I omitted this trivial but required step. Otherwise "11-11" would be counted as a win.

    The "lines" can be traversed given a starting point and row/column offset per iteration (e.g. start at (0,0) and advance (1,1) for longest diagonal from NW to SE). Diagonals with lengths less than 4 can avoid being checked entirely, of course.

    Happy coding.