โญ• TIC-TAC-TOE in Python

The same game โ€” but every line of it is Python, running in your browser

โ† Back to Fun Time
๐Ÿ Starting Pythonโ€ฆ
You
0
Computer
0
Draws
0

โŒจ๏ธ Controls

  • โ† โ†’ โ†‘ โ†“ move the dashed cursor
  • Space or Enter play there
  • Clicking or tapping a square works too
  • R next round  โ€ข  P pause
  • ๐ŸŽฎ Xbox controller? Just plug it in or pair it โ€” the stick and D-pad are the arrow keys, A is SPACE, Menu pauses and View starts again

๐ŸŽฏ How to play

  • You are X and you always go first.
  • Get three in a row โ€” across, down or diagonally.
  • The computer replies straight away, so every tap is a whole turn.
  • The scoreboard keeps count across rounds.

๐Ÿค– How the computer thinks

  • 1. If it can win this turn, it wins.
  • 2. If you are about to win, it blocks you.
  • 3. Otherwise it takes the middle โ€” that square is on four lines.
  • 4. Otherwise a corner, which is on three.
  • Those four rules are enough that it never loses. A draw is a win for you!

๐Ÿง‘โ€๐Ÿ’ป This whole game is Python

There is almost no JavaScript on this page. The browser downloaded Pyodide โ€” a complete Python interpreter compiled to WebAssembly โ€” and then ran the .py files in funtime/pylib/. Python does the rules, the maths and the drawing.

File What it does Good functions to try re-writing
pylib/tictactoe_rules.py The rules, and the computer's brain winning_line, is_draw, computer_move
pylib/tictactoe_draw.py Painting the board โ€” Python calling the canvas draw_mark, draw_winning_line, square_at_pixel
pylib/tictactoe_web.py The glue: clicks, keyboard, the scoreboard do_action, on_board_click, start_game

๐Ÿ” Compare the two versions. Open lib/tictactoe-rules.js and pylib/tictactoe_rules.py side by side โ€” same ideas, two languages.

๐Ÿ› ๏ธ Build it yourself: Build Tic-Tac-Toe in Python walks you through the functions one at a time.

โš ๏ธ If the game never starts: the page has to read its .py files, which a browser will not do for a page opened straight off your disk. Use the live site, or run python3 -m http.server in the project folder.