๐Ÿ”ด CONNECT FOUR 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

  • โ† โ†’ aim above a column
  • Space, Enter or โ†“ drop a counter
  • Clicking or tapping a column 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 the solid counters; the computer is the rings.
  • Counters fall to the lowest free hole in the column you pick.
  • Get four in a row โ€” across, down or diagonally.
  • The computer replies straight away, so every drop is a whole turn.

๐Ÿค– How the computer thinks

  • 1. If it can make four, it does.
  • 2. If you are about to make four, it blocks you.
  • 3. Otherwise it plays as near the middle as it can โ€” the middle column is part of more possible lines than any other.
  • 4. And it never drops a counter that lets you win by landing on top of it.
  • To beat it, build two threats at once. It can only block one!

๐Ÿง‘โ€๐Ÿ’ป 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/connect4_rules.py The rules, the win check and the computer drop_row, count_in_direction, is_win_at, computer_column
pylib/connect4_draw.py Painting the board โ€” Python calling the canvas draw_counter, draw_drop_marker, column_at_pixel
pylib/connect4_web.py The glue: clicks, keyboard, the scoreboard do_action, on_board_click, start_game

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

๐Ÿ› ๏ธ Build it yourself: Build Connect Four 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.