webdevpuneet.com

Tic-Tac-Toe vs Computer with 15 Levels & Ultimate Mode

Tic-Tac-Toe vs Computer · Games · Plain HTML, CSS & JS · Live preview

CategoryGames

About this UI Snippet

Tic-Tac-Toe vs Computer — Minimax AI, Bigger Boards, Ultimate Tic-Tac-Toe and a Daily Forced-Win Puzzle

Screenshot of the Tic-Tac-Toe vs Computer snippet rendered live

Tic-Tac-Toe is the smallest complete game with a computer opponent, and it is the best first lesson in game AI. This version goes much further than the classic board. It has 15 levels in three tiers: the classic 3x3 game against computers that get steadily sharper, bigger 4x4 and 5x5 boards where you need four in a row, and Ultimate Tic-Tac-Toe, nine boards in one, with the full rules. A Daily Puzzle gives you a position with a forced win to find, and a two-player mode is included. It is plain HTML, CSS and JavaScript with no libraries, images or audio files.

One interface for every game type

Each game type is a small object with the same functions: moves(), play(), winner() and evaluate(). makeRowRules(n, k) builds any square board where k in a row wins by listing every winning line once, which covers 3x3, 4x4 and 5x5 with one piece of code. makeUltimateRules() adds the extra rules: the cell you choose decides which small board your opponent must play in, a won small board counts as one mark on the big board, and if you are sent to a finished board you may play anywhere. Because both types look the same to the search, the computer, the hints and the daily puzzle work on every board.

A computer that gets stronger on purpose

The opponent is a negamax search with alpha-beta pruning (negamax()), which scores a position by playing every continuation to a set depth. At the end of the search a position is judged by evaluate(), which rewards lines that are still open and nearly complete. Each level in the LEVELS array sets the depth, a chance that the computer plays a random move instead (a human-like slip) and who starts. The first level is almost random, the second only wins and blocks, the third sees forks, and level 5 searches the whole 3x3 game, which makes it impossible to beat, so a draw passes that level. The search has a time limit, so the page stays responsive on the larger boards.

A daily puzzle built by the solver

The Daily Puzzle is generated, not stored. makePuzzle() plays a few seeded random moves, then asks the solver whether X has a forced win and how long it takes. It keeps only positions where the win needs two or three of your moves and only one or two first moves work, so the solution is a real fork. The computer defends perfectly, always choosing the move that loses most slowly. Three stars for the fastest win, two for any win, and clearing the puzzle on consecutive days builds a streak.

Hints, undo and stars

The Hint button runs the same search for you and highlights the best cell. Undo takes back your move and the computer's reply. Winning gives one star, a second for no hints or undos and a third for finishing within the par number of moves. A win (or a draw on the levels where a draw is enough) unlocks the next level, and progress is saved to localStorage inside try/catch.

Feel

Marks are drawn as SVG strokes that animate as if written by hand, a line is drawn through the winning cells, the last move is highlighted, and in Ultimate the board you must play in glows. Sounds come from a Web Audio synth, the keyboard works (number keys 1 to 9 on the classic board, arrow keys and Enter everywhere), and the whole game scales to short preview areas.

What's included

Features

Three game types on one engine: classic 3x3, 4x4 and 5x5 boards with four in a row, and full Ultimate Tic-Tac-Toe
Negamax search with alpha-beta pruning and a time cap, with depth and a random-slip chance per level
15 levels from an almost random computer to a perfect one, with a draw passing the levels where it cannot be beaten
Computer or you can start, depending on the level, so you practise both the first-move and second-move game
Daily Puzzle generated by the solver: a position with a forced win that needs a fork, against a perfect defender, with a streak
Hints that tell you whether a move leads to a forced win, and undo that takes back your move and the reply
Stars for winning, for no assists and for a quick win, saved with the record in localStorage inside try/catch
Pass-and-play two-player mode, number keys, arrow keys and Enter, and labelled cells for screen readers
SVG marks that draw themselves, a win line, last-move highlight, glowing active board in Ultimate, confetti and Web Audio sounds
Scales to its preview area (down to 40 percent) and stacks on phones

Step by step

How to Use

  1. 1
    Pick a level, the Daily Puzzle or two playersThe menu shows 15 levels in three tiers: classic 3x3, bigger boards, and Ultimate Tic-Tac-Toe. Level 1 is open at first and passing a level unlocks the next. The gold card is the Daily Puzzle and the purple card is a two-player game on one screen.
  2. 2
    Place your marksYou play X. Click a cell to place your mark. On the classic board you can also press 1 to 9 (1 is the top left, 9 the bottom right), and on every board the arrow keys move a cursor and Enter places a mark.
  3. 3
    Get your lineGet the required number in a row, column or diagonal: three on the 3x3 board, four on the 4x4 and 5x5 boards. The winning line is drawn through your marks. A full board with no line is a draw.
  4. 4
    Learn the Ultimate ruleIn Ultimate Tic-Tac-Toe the cell you pick sends your opponent to the matching small board. Win a small board to claim it, and win three claimed boards in a row to win the game. The glowing board is where you must play, unless it is finished, then you may play anywhere.
  5. 5
    Use hints and undoHint (H) highlights a strong move and tells you if it leads to a forced win. Undo (U) takes back your move and the reply. Both are useful for learning, but they cost the unassisted star.
  6. 6
    Earn stars and keep your streakOne star for winning, one more for no hints or undos, one more for a win within the par number of moves. The Daily Puzzle asks you to find a forced win: win in the fastest way for three stars and build a streak by solving it every day.

Real-world uses

Common Use Cases

The classic first lesson in game AI
Minimax and alpha-beta pruning are easiest to understand on Tic-Tac-Toe. This snippet shows them in under a hundred lines, and then shows how the same search scales to bigger boards and to Ultimate by changing only the rules object.
Designing a rules interface that works for many games
Because every game type provides moves(), play(), winner() and evaluate(), the search, the hints and the daily puzzle do not know which game they are running. It is a useful pattern for any collection of board games.
A tutorial that teaches forks
The Daily Puzzle teaches the one tactic that wins Tic-Tac-Toe, the fork, by making you find it in a real position. The computer plays perfectly, so you cannot win by luck.
Animating SVG strokes
The X and the O are drawn with stroke-dasharray and stroke-dashoffset animations, so they appear as if written by hand, which is a reusable trick for any line art.
Difficulty by search depth and slips
Depth sets how far ahead the computer sees, and a blunder chance makes it fail like a person. Combining the two gives smooth difficulty without changing the AI code.
Related: Checkers Game
See the Checkers Game for a bigger game with the same kind of search-based opponent.
Related: Connect Four vs Computer
See the Connect Four vs Computer for a related games pattern with a computer opponent.

Got questions?

Frequently Asked Questions

On levels 1 to 4 yes, because it looks only a few moves ahead and sometimes plays a random move. On level 5 it searches the whole 3x3 game and never slips, so Tic-Tac-Toe against it is always a draw at best, which is why a draw passes that level. On the bigger boards and in Ultimate the computer is strong but not perfect, so it can still be beaten.

chooseMove() usually runs negamax(), a search that tries every move to a set depth, assumes the opponent also plays well, and uses alpha-beta pruning to skip moves that cannot matter. At the depth limit evaluate() scores the position. With a small chance set by the level, it plays a random move instead. In the daily puzzle it always picks the move that delays its loss the longest.

The board is nine small boards in a 3x3 grid. The cell you play in a small board decides which small board your opponent must play in next. If that small board is already won or full, they can play in any open board. Winning a small board marks it for you, and winning three small boards in a row wins the game. The glowing board shows where the next move must be.

makePuzzle() plays a few random moves from a seed based on the date, then uses the solver to check that X has a forced win that needs two or three of your moves and that only one or two first moves lead to it. That guarantees a position with a real fork. The same date always gives the same puzzle.

Edit the LEVELS array: type is row or ultimate, n and k are the board size and the line length, depth is how many plies the computer searches, blunder is the chance of a random move, first is who starts, par is the number of your moves for the speed star and goal says whether a draw passes. The menu shows five levels per tier.

Yes. All localStorage access is in try/catch, so a blocked storage only means that progress is not saved, and every sound call is wrapped. Cells respond to pointer events, so touch works, and on narrow screens the side panel moves under the board and the page scrolls. The computer thinks within a time cap, so the page stays responsive.

Copy & paste

Source Code

<div class="tt-fit" id="tt-fit"><div class="tt-wrap" id="tt-wrap">
  <div class="tt-panel" id="tt-panel">
    <div class="tt-hud">
      <div class="tt-hud-left">
        <span class="tt-kicker" id="tt-kicker">Tic-Tac-Toe</span>
        <span class="tt-name" id="tt-name">Pick a level</span>
      </div>
      <div class="tt-turn" id="tt-turn"></div>
      <div class="tt-hud-btns">
        <button class="tt-btn-sm" id="tt-levels-btn" type="button" title="Levels (Esc)">Levels</button>
        <button class="tt-btn-sm" id="tt-mute" type="button" aria-pressed="false">Sound on</button>
      </div>
    </div>

    <div class="tt-main">
      <div class="tt-board-col"><div class="tt-board-wrap" id="tt-board-wrap"><div class="tt-board" id="tt-board" role="grid" aria-label="Game board"></div><svg class="tt-winline" id="tt-winline" viewBox="0 0 100 100" preserveAspectRatio="none"></svg></div></div>
      <aside class="tt-side">
        <div class="tt-player" id="tt-p-you"><i class="tt-chip tt-x"></i><div><b>You</b><span id="tt-you-sub">play X</span></div></div>
        <div class="tt-player" id="tt-p-cpu"><i class="tt-chip tt-o"></i><div><b id="tt-cpu-name">Computer</b><span id="tt-cpu-sub">plays O</span></div></div>
        <div class="tt-rule" id="tt-rule"></div>
        <div class="tt-tools">
          <button class="tt-tool" id="tt-undo" type="button"><span class="tt-tool-ico">&#8630;</span>Undo <em>U</em></button>
          <button class="tt-tool" id="tt-hint" type="button"><span class="tt-tool-ico">&#128161;</span>Hint <i id="tt-hint-count">3</i><em>H</em></button>
        </div>
        <p class="tt-msg" id="tt-msg"></p>
      </aside>
    </div>

    <div class="tt-overlay show" id="tt-menu">
      <p class="tt-logo">Tic-Tac-Toe</p>
      <p class="tt-tagline">Beat a computer that thinks ahead. Start with the classic board, move up to bigger boards, and finish on Ultimate Tic-Tac-Toe, nine boards in one.</p>
      <div class="tt-menu-row">
        <button class="tt-daily" id="tt-daily" type="button">
          <span class="tt-daily-title" id="tt-daily-title">Daily Puzzle</span>
          <span class="tt-daily-sub" id="tt-daily-sub">Find the forced win. Same position for everyone.</span>
        </button>
        <button class="tt-daily tt-pvp" id="tt-pvp" type="button">
          <span class="tt-daily-title">Two players</span>
          <span class="tt-daily-sub">Pass and play on one screen</span>
        </button>
        <div class="tt-totals"><span><b id="tt-star-total">0</b> / 45 stars</span><span>Daily streak <b id="tt-streak">0</b></span><span id="tt-record"></span></div>
      </div>
      <div class="tt-tiers" id="tt-tiers"></div>
    </div>

    <div class="tt-overlay" id="tt-result">
      <p class="tt-result-title" id="tt-result-title">You win!</p>
      <div class="tt-result-stars" id="tt-result-stars"><span>&#9733;</span><span>&#9733;</span><span>&#9733;</span></div>
      <p class="tt-result-sub" id="tt-result-sub"></p>
      <div class="tt-result-btns">
        <button class="tt-btn" id="tt-next" type="button">Next level</button>
        <button class="tt-btn tt-btn-ghost" id="tt-retry" type="button">Play again</button>
        <button class="tt-btn tt-btn-ghost" id="tt-share" type="button">Copy result</button>
        <button class="tt-btn tt-btn-ghost" id="tt-menu-back" type="button">Levels</button>
      </div>
    </div>
  </div>
</div></div>

Extend with AI

Take This Snippet Further With AI

Paste this snippet's HTML, CSS and JS into an AI coding assistant like Claude and ask it to explain how makeRowRules() and makeUltimateRules() give the search a common interface, how negamax() uses the win score minus the ply to prefer faster wins, and how makePuzzle() finds a position with a forced fork. It is also a good base to extend: ask for a transposition table, an opening book, a misere (reverse) mode, a 3D 4x4x4 board, an online two-player mode, or a hint that explains why a move works (for example "this creates two threats"). You can also ask it to review the busy flag and run id that guard clicks while the computer thinks.

Prompt to recreate it

Copy this into your AI assistant of choice to build the effect from scratch, or as a jumping-off point for your own variant:

text
Build a Tic-Tac-Toe game against the computer with levels in plain HTML, CSS and JavaScript, with no libraries, images or audio files.

Requirements:
- A generic rules interface (moves, play, winner, evaluate) with two implementations: a square board of n x n where k in a row wins (3x3 with 3, 4x4 with 4, 5x5 with 4), generated from a list of winning lines, and full Ultimate Tic-Tac-Toe (nine small boards; the cell you play decides the small board your opponent must play in; a won small board counts for the big board; if the target board is finished the player may play anywhere; three small boards in a row win).
- A computer using negamax with alpha-beta pruning, a time cap and an evaluation of open lines, with 15 levels defined as data (type, board size, search depth, chance of a random slip, who starts, par moves, whether a draw passes). Make level 5 a perfect 3x3 player that goes first, where a draw passes.
- Draw X and O as SVG strokes that animate as if written (stroke-dasharray), highlight the last move, draw a line through the winning cells, show the active small board in Ultimate with a glow, show the computer thinking, and confetti on a win.
- Stars: 1 for a win (or a draw where it passes), +1 for no hints or undos, +1 for a win within par moves. Hint (3 per game) shows the best move from the search and says whether it forces a win. Undo takes back your move and the computer reply. Level unlocking, a win/loss/draw record and the daily result saved to localStorage inside try/catch.
- A Daily Puzzle: a 3x3 position generated from a date seed where X to move has a forced win that needs a fork (the solver finds it, with the win 3 to 5 plies away and only one or two winning first moves), against a perfect defender, with a day streak and a copy result button. A two-player pass-and-play mode.
- Keyboard play (number keys 1 to 9 on 3x3, arrow keys and Enter on every board), aria labels on the cells, Web Audio synth sounds with a mute button, and a busy flag plus run id that guard clicks and timers while the computer thinks.
- Scale the whole game to fit the available area (down to 40 percent) and stack the layout on narrow screens.

Want to tighten it up first? Run this prompt through the AI Prompt Studio to score it across 8 quality dimensions, catch anti-patterns, and tune the wording for Claude, ChatGPT, or Gemini before you paste it in.