call(back)
FrontendmediumSign in to star problems

Tic-Tac-Toe: N by N, M in a Row

Build tic-tac-toe on an N by N board where M in a row wins. The plain game is N = M = 3. The default template is HTML/CSS/JS, and a React template is the alternate.

Requirements

  • Board size N (3 to 10) and win length M (3 to N) come from the inputs. "New game" applies them and resets the board. Out-of-range values are clamped.
  • Players alternate, X first. Clicking an empty cell places the current mark, and a filled cell can't be played again.
  • isWinningMove(board, row, col, m) decides a win by checking only the lines through the last move: horizontal, vertical and both diagonals.
  • The status line shows whose turn it is, the winner, or a draw when the board fills without one. No moves are allowed after the game ends.
  • Cells are buttons with labels such as "Row 1, column 2, empty", and the status is announced politely.

Hints

Hint 1

A win can only be created by the mark just placed. From that cell, count matching marks outward in both directions along each of the four direction vectors. 1 + forward + backward >= m is a win.

Hint 2

Keep a move counter for the draw check: moves === n * n with no winner.

Hint 3

In HTML/CSS/JS, build the grid once per game and put one click listener on the board that reads data-row and data-col. In React, replace the board immutably on every move.

Asked at