Articles / agentsmachine-learning
Build an AI agent that plays a game in Python: Q-learning vs minimax vs an LLM
Three agents play one small board game in pure Python: tabular Q-learning with a learning curve, exact minimax, and a local qwen3 LLM. Real win rates and time per move.
A game-playing agent is the cleanest place to see what "agent" means outside the LLM hype: something that looks at a state, picks an action, and gets judged on the outcome. This post builds three of them for the same small board game, in pure Python, and makes them play each other. One learns from self-play with tabular Q-learning. One searches the whole game tree with minimax. One is a 4-billion-parameter LLM (qwen3 running locally in Ollama) that reads the board as text and names a column.
The results are lopsided in a useful way. After 30 seconds of self-play on a laptop CPU, the Q-learning agent picks a provably optimal move in 90% of test positions and wins 193 of 200 games against a random player. Minimax solves the game in under a quarter of a second. The LLM takes about two seconds per move, wins 11 of 20 games against a random player (the random player itself won 7 of 20 in the same run), and loses both games to minimax, including the one where it moves first from a won position. The rest of the post shows the code, the numbers and why the gap exists.
Why a board game and not CartPole#
Most RL tutorials start with CartPole from Gymnasium and a deep Q-network. That works, but it hides two things. The neural network, replay buffer and target arithmetic bury the actual learning rule. And a single-player balancing task gives you nothing to compare against: you get a score, with no idea how far it is from the best possible play.
A two-player game small enough to solve exactly fixes both. The value function fits in a Python dict, so the Q-learning update is one line you can read. And because an exact solver exists, every move any agent makes can be graded against ground truth instead of against "it seems to play well". That grading turns out to matter more than any hyperparameter.
The game here is made up for this post, so nobody's rules or trademarks are involved. Call it Drop-3:
. . . . 4 columns x 4 rows, pieces fall to the lowest empty cell
. O . . players X and O alternate, X moves first
. X . . three in a row (across, down or diagonal) wins
. X O . a full board with no line is a draw
0 1 2 3 a move is just a column number
It is small enough to solve and big enough that a random player loses most games, which is what you want from a test bed.
The game engine#
The board is a tuple of 16 characters, row 0 at the top. Tuples are hashable, which lets the same object work as a cache key for minimax and a dict key for the Q-table.
"""Drop-3: a 4x4 gravity board, three in a row wins. Pure Python, no dependencies."""
import random
ROWS, COLS, NEED = 4, 4, 3
EMPTY, X, O = ".", "X", "O"
def new_board():
return tuple([EMPTY] * (ROWS * COLS)) # row 0 is the top row
def legal_moves(b):
return [c for c in range(COLS) if b[c] == EMPTY] # top cell free -> column open
def play(b, col, piece):
for r in range(ROWS - 1, -1, -1): # fall to the lowest empty cell
i = r * COLS + col
if b[i] == EMPTY:
cells = list(b)
cells[i] = piece
return tuple(cells)
raise ValueError(f"column {col} is full")
def _lines():
out = []
for r in range(ROWS):
for c in range(COLS):
for dr, dc in ((0, 1), (1, 0), (1, 1), (1, -1)):
cells = [(r + k * dr, c + k * dc) for k in range(NEED)]
if all(0 <= rr < ROWS and 0 <= cc < COLS for rr, cc in cells):
out.append([rr * COLS + cc for rr, cc in cells])
return out
LINES = _lines()
def winner(b):
for a, m, z in LINES:
if b[a] != EMPTY and b[a] == b[m] == b[z]:
return b[a]
if EMPTY not in b:
return "draw"
return None
def other(p):
return O if p == X else X
def render(b):
rows = [" ".join(b[r * COLS:(r + 1) * COLS]) for r in range(ROWS)]
return "\n".join(rows) + "\n" + " ".join(str(c) for c in range(COLS))
class RandomAgent:
name = "random"
def move(self, b, me):
return random.choice(legal_moves(b))
def play_game(agent_x, agent_o):
b, turn = new_board(), X
agents = {X: agent_x, O: agent_o}
while (w := winner(b)) is None:
col = agents[turn].move(b, turn)
if col not in legal_moves(b): # an illegal move loses on the spot
return other(turn)
b = play(b, col, turn)
turn = other(turn)
return w
Every agent has the same interface, move(board, me) -> column. That is the whole contract between an agent and the environment, and it is what lets an LLM, a lookup table and a search routine sit in the same arena. The rule that an illegal move forfeits the game matters only for the LLM; the other two cannot produce one.
Ground truth first: solve the game with minimax#
Minimax assumes both players play perfectly. At each position it tries every legal move, recurses, and takes the best result for whoever is to move. Python's functools.lru_cache turns this into a transposition table for free, because the same position reached by different move orders is computed once.
"""Full-depth minimax with a cache (transposition table). Solves Drop-3 exactly."""
from functools import lru_cache
from drop3 import legal_moves, play, winner, other
CENTER_FIRST = [1, 2, 0, 3] # ties go to the middle columns
@lru_cache(maxsize=None)
def value(b, to_move):
"""Score from X's point of view: +1 X wins, -1 O wins, 0 draw. Faster wins score higher."""
w = winner(b)
if w == "X":
return 1 + b.count(".") / 100
if w == "O":
return -1 - b.count(".") / 100
if w == "draw":
return 0
moves = [c for c in CENTER_FIRST if c in legal_moves(b)]
scores = [value(play(b, c, to_move), other(to_move)) for c in moves]
return max(scores) if to_move == "X" else min(scores)
class MinimaxAgent:
name = "minimax"
def move(self, b, me):
moves = [c for c in CENTER_FIRST if c in legal_moves(b)]
pick = max if me == "X" else min
return pick(moves, key=lambda c: value(play(b, c, me), other(me)))
The small bonus for empty cells makes the solver prefer a fast win over a slow one and a slow loss over a fast one. Without it, a winning agent can wander, since every winning move scores the same.
game value for X: +1.07 positions cached: 41750 solve time: 0.09s
A second run on a busier machine took 0.23 s; either way it is a fraction of a second.
solve.py is short:
import time
from drop3 import new_board
from search import value
t = time.perf_counter()
v = value(new_board(), "X")
print(f"game value for X: {v:+.2f} positions cached: {value.cache_info().currsize} solve time: {time.perf_counter()-t:.2f}s")
A value of +1.07 means X wins with perfect play, with 7 empty cells left, so after 9 moves in total. The whole game has 41,750 distinct positions reachable from the start. That number decides which methods are sensible. A table with tens of thousands of rows is trivial. The standard 7x6 Connect Four board has 4,531,985,219,092 legal positions (John Tromp's count), and chess far more, which is why those need pruning, heuristics or a neural network instead of a full table.
The column order (CENTER_FIRST) does nothing for correctness here, since there is no alpha-beta cutoff. It only decides which move gets played when several moves tie. Add alpha-beta pruning when the tree is too big to enumerate.
Agent 1: tabular Q-learning by self-play#
Q-learning keeps a number Q(s, a) for each state and action: the expected final result if you play a from s and play well afterwards. After each move it nudges that number toward a better estimate:
Q(s, a) <- Q(s, a) + alpha * (target - Q(s, a))
target = +1 if the move wins
= 0 if the move draws
= -max Q(s', a') otherwise, where s' is the board from the opponent's side
The minus sign is the two-player trick. In a zero-sum game, the opponent's best outcome is your worst, so the value of your position after the move is minus the best value the opponent can get from theirs. To use one table for both sides, the board is flipped (X and O swapped) whenever O is to move, so the mover always looks like X. Self-play then trains both seats at once.
Worked numbers with alpha = 0.3: a winning move starts at Q = 0. The first time it is played, Q becomes 0 + 0.3 x (1 - 0) = 0.30. Then 0.51, then 0.66. Each visit closes 30% of the remaining gap, and the value then flows backwards: the move before it sees an opponent whose best reply is now worth less, and so on up the game.
"""Tabular Q-learning by self-play. One table serves both sides: before every lookup the
board is flipped so the player to move is always X. The opponent's best reply is then
just the negative of its own best Q-value (negamax form of the Q-learning target)."""
import random
from collections import defaultdict
from drop3 import new_board, legal_moves, play, winner
FLIP = {"X": "O", "O": "X", ".": "."}
def canon(b, me):
return b if me == "X" else tuple(FLIP[c] for c in b)
class QAgent:
name = "q-learning"
def __init__(self, alpha=0.3, eps=0.2):
self.Q = defaultdict(float) # (canonical board, column) -> value for the mover
self.alpha, self.eps = alpha, eps
def best(self, s):
moves = legal_moves(s)
top = max(self.Q[(s, c)] for c in moves)
return random.choice([c for c in moves if self.Q[(s, c)] == top]), top
def move(self, b, me): # greedy play, no exploration
return self.best(canon(b, me))[0]
def train_episode(self):
s = new_board() # always canonical: the mover is X
while True:
a = random.choice(legal_moves(s)) if random.random() < self.eps else self.best(s)[0]
nxt = play(s, a, "X")
w = winner(nxt)
if w == "X":
target = 1.0
elif w == "draw":
target = 0.0
else:
s2 = canon(nxt, "O") # opponent's view of the board
target = -self.best(s2)[1] # gamma = 1: the game is short and always ends
self.Q[(s, a)] += self.alpha * (target - self.Q[(s, a)])
if w is not None:
return
s = s2
Epsilon = 0.2 means one move in five during training is random. Without that, self-play locks into the same few games and never visits most of the table. At evaluation time the agent plays greedily.
The learning curve, graded two ways#
The training script measures the agent at checkpoints in two ways. Win rate against a random player over 500 games, alternating sides. And the optimal-move rate: on 2,000 fixed positions sampled from random play, how often the agent's move is one the solver rates as best.
"""Train Q-learning and measure it at checkpoints: win rate vs random, and how often
its move is optimal according to the exact solver."""
import random, time
from drop3 import new_board, legal_moves, play, winner, other, RandomAgent, play_game
from search import value, MinimaxAgent
from qlearn import QAgent
random.seed(7)
# Probe set: 2,000 random non-terminal positions reached by random play.
probes = []
while len(probes) < 2000:
b, turn = new_board(), "X"
for _ in range(random.randint(0, 10)):
if winner(b) is not None:
break
b, turn = play(b, random.choice(legal_moves(b)), turn), other(turn)
if winner(b) is None:
probes.append((b, turn))
def optimal_moves(b, me):
vals = {c: value(play(b, c, me), other(me)) for c in legal_moves(b)}
best = max(vals.values()) if me == "X" else min(vals.values())
return {c for c, v in vals.items() if abs(v - best) < 1e-9}
def optimal_rate(agent):
return sum(agent.move(b, me) in optimal_moves(b, me) for b, me in probes) / len(probes)
def vs_random(agent, n=500):
rnd, wins = RandomAgent(), 0
for i in range(n):
if i % 2 == 0:
wins += play_game(agent, rnd) == "X"
else:
wins += play_game(rnd, agent) == "O"
return wins / n
q = QAgent()
t0 = time.perf_counter()
print(f"{'games':>7} {'win% vs random':>15} {'optimal move %':>15} {'table size':>11} {'secs':>6}")
CHECKPOINTS = [0, 5000, 10000, 25000, 50000, 100000, 200000, 300000]
for prev, step in zip([0] + CHECKPOINTS, CHECKPOINTS):
if step:
for _ in range(step - prev):
q.train_episode()
print(f"{step:>7} {vs_random(q):>15.1%} {optimal_rate(q):>15.1%} {len(q.Q):>11,} {time.perf_counter()-t0:>6.1f}")
mm = MinimaxAgent()
print("Q as X vs minimax:", play_game(q, mm), "| Q as O vs minimax:", play_game(mm, q))
print(f"minimax: {vs_random(mm):.1%} win vs random, {optimal_rate(mm):.1%} optimal moves")
import pickle; pickle.dump(dict(q.Q), open("q_table.pkl", "wb"))
Real output on an Apple M5, one core, Python 3.15:
games win% vs random optimal move % table size secs
0 50.8% 42.0% 6,195 0.1
5000 85.8% 71.0% 25,825 0.2
10000 86.4% 74.6% 29,619 0.4
25000 90.4% 77.5% 34,597 1.0
50000 90.6% 83.5% 38,149 2.6
100000 95.2% 83.5% 42,417 12.9
200000 95.8% 86.3% 45,571 21.0
300000 93.8% 90.3% 47,339 33.2
Q as X vs minimax: X | Q as O vs minimax: X
minimax: 99.2% win vs random, 100.0% optimal moves
The two columns tell different stories. Win rate against random jumps to 86% after 5,000 games and then wobbles between 90% and 96%, and it even drops at the last checkpoint. That is noise from 500 games against a weak opponent: a random player rarely punishes a bad move, so this metric cannot tell a good agent from a great one. The optimal-move rate keeps climbing, from 71% to 90%, because it checks each decision against the solver instead of waiting for an opponent to exploit it.
The last line is the real test. As X, the trained agent beats minimax, which is the best result possible because X wins the game with perfect play. As O it loses, which is also the best possible: nothing beats a perfect X. On this game, 30 seconds of self-play produced an agent that holds its own against the exact solver in both seats.
Agent 2: an LLM that reads the board#
The LLM agent turns the board into text, adds the rules and the legal columns, and asks for JSON. The model call hides behind one function, chat(prompt) -> str. Here it calls a local Ollama server with qwen3:4b-instruct; swap in a hosted model by replacing that one function, or use stub_chat to run everything offline with no model at all. No API key is involved.
"""An LLM that picks moves from a text board. The model sits behind one function,
chat(prompt) -> str, so you can swap Ollama for any hosted model or a stub."""
import json, os, re, time, urllib.request
from drop3 import legal_moves, play, winner, other, render
RULES = ("Game: Drop-3 on a 4x4 board. Players take turns dropping a piece into a column "
"(0-3); it falls to the lowest empty cell. First to get 3 in a row horizontally, "
"vertically or diagonally wins. Row 1 below is the top of the board.")
def ollama_chat(prompt, model="qwen3:4b-instruct"):
body = {"model": model, "stream": False, "messages": [{"role": "user", "content": prompt}],
"format": {"type": "object", "properties": {"column": {"type": "integer"}},
"required": ["column"]},
"options": {"temperature": 0, "num_predict": 20}}
req = urllib.request.Request(os.environ.get("OLLAMA_URL", "http://localhost:11434") + "/api/chat", json.dumps(body).encode(),
{"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=900) as r:
d = json.load(r)
# Model compute only (prompt + generation), excluding time spent queued in the server.
ollama_chat.compute_s = (d.get("prompt_eval_duration", 0) + d["eval_duration"]) / 1e9
return d["message"]["content"]
def stub_chat(prompt): # offline stand-in: always the first legal column it can find
return json.dumps({"column": int(re.search(r"Legal columns: \[(\d)", prompt).group(1))})
def tactics(b, me):
"""What a few lines of code can compute exactly: wins, blocks and blunders."""
win = [c for c in legal_moves(b) if winner(play(b, c, me)) == me]
block = [c for c in legal_moves(b) if winner(play(b, c, other(me))) == other(me)]
blunder = []
for c in legal_moves(b):
nb = play(b, c, me)
if any(winner(play(nb, d, other(me))) == other(me) for d in legal_moves(nb)):
blunder.append(c)
return win, block, blunder
class LLMAgent:
def __init__(self, chat=ollama_chat, hints=False):
self.chat, self.hints = chat, hints
self.name = "llm+hints" if hints else "llm"
self.times, self.compute, self.bad = [], [], 0
def move(self, b, me):
prompt = (f"{RULES}\nYou are {me}. Board:\n{render(b)}\n"
f"Legal columns: {legal_moves(b)}\n")
if self.hints:
win, block, blunder = tactics(b, me)
prompt += (f"Columns that win now: {win}. Columns that block the opponent's "
f"immediate win: {block}. Columns that let the opponent win next turn: "
f"{blunder}.\n")
prompt += 'Reply with JSON {"column": <int>}.'
t = time.perf_counter()
raw = self.chat(prompt)
self.times.append(time.perf_counter() - t)
self.compute.append(getattr(self.chat, "compute_s", 0.0))
try:
col = int(json.loads(raw)["column"])
except (ValueError, KeyError, TypeError):
col = -1
if col not in legal_moves(b):
self.bad += 1 # play_game() scores an illegal move as a loss
return col
Three settings do most of the work. The format field passes a JSON schema to Ollama's structured outputs, so the reply is always parseable. Temperature 0 makes the model repeatable, which also means it plays the same game twice against a deterministic opponent. And the hints=True variant runs the tactics() helper first and tells the model which columns win, block or blunder. That is the tool-use pattern from AI agent architectures explained: code computes facts the model is bad at, and the model only decides.
The arena: win rates and time per move#
Each agent plays 20 games against a random player (10 as X, 10 as O) and 2 games against minimax (one per side). Results are wins-draws-losses. The arena wraps every agent's move in a timer:
"""Play every agent against random and against minimax, from both sides."""
import pickle, random, statistics, sys, time
from collections import defaultdict
from drop3 import RandomAgent, play_game
from search import MinimaxAgent
from qlearn import QAgent
from llm_agent import LLMAgent, ollama_chat, stub_chat
def timed(agent):
agent.ms = []
raw = agent.move
def move(b, me):
t = time.perf_counter(); c = raw(b, me); agent.ms.append(time.perf_counter() - t); return c
agent.move = move
return agent
def series(agent, opp, n):
w = d = l = 0
for i in range(n):
side = "X" if i % 2 == 0 else "O"
res = play_game(agent, opp) if side == "X" else play_game(opp, agent)
w += res == side; d += res == "draw"; l += res not in (side, "draw")
return f"{w}-{d}-{l}"
random.seed(11)
q = QAgent(); q.Q.update(pickle.load(open("q_table.pkl", "rb")))
chat = stub_chat if "--stub" in sys.argv else ollama_chat
n_rand = int(sys.argv[1]) if len(sys.argv) > 1 and sys.argv[1].isdigit() else 10
agents = [timed(RandomAgent()), timed(q), timed(MinimaxAgent()),
timed(LLMAgent(chat)), timed(LLMAgent(chat, hints=True))]
print(f"{'agent':<11} {'vs random W-D-L':>16} {'vs minimax W-D-L':>17} {'median ms/move':>15}")
for a in agents:
vr = series(a, RandomAgent(), n_rand)
vm = series(a, MinimaxAgent(), 2) # minimax is deterministic: one game per side
print(f"{a.name:<11} {vr:>16} {vm:>17} {statistics.median(a.ms) * 1000:>15.3f}", flush=True)
if hasattr(a, "bad"):
print(f"{'':<11} illegal moves: {a.bad}, median model compute: "
f"{statistics.median(a.compute):.2f}s, median wall incl. queue: {statistics.median(a.times):.2f}s",
flush=True)
Output of python3 arena.py 20:
agent vs random W-D-L vs minimax W-D-L median ms/move
random 7-0-13 0-0-2 0.002
q-learning 20-0-0 1-0-1 0.011
minimax 20-0-0 1-0-1 0.014
llm 11-1-8 0-0-2 1891.972
illegal moves: 0, median model compute: 1.87s, median wall incl. queue: 1.89s
llm+hints 15-0-5 0-0-2 2092.265
illegal moves: 0, median model compute: 2.06s, median wall incl. queue: 2.09s
The non-LLM rows are cheap to run at a larger sample. This is python3 arena.py 200 --stub with the stubbed LLM rows left out:
agent vs random W-D-L vs minimax W-D-L median ms/move
random 103-1-96 0-0-2 0.002
q-learning 193-0-7 1-0-1 0.009
minimax 198-1-1 1-0-1 0.012
Twenty games is a small sample, so read the LLM rows as rough. They are still clear. The plain LLM went 11-1-8 against random, close to a coin flip. It never made an illegal move, thanks to the schema and the legal-column list, but legal is not good: on the empty board it opened in column 0. The solver rates that opening as still winning for X, but with perfect defence only on X's last possible move (value +1.01, one empty cell left), while the middle columns win three X moves sooner (+1.07). The edge opening leaves almost no margin for a later mistake. Against minimax it lost both seats, including as X, where perfect play wins.
The hints moved it to 15-0-5. Telling the model which columns win, block or hand the opponent a win cut its losses to random from 8 to 5. It still lost five games to a random player, and it still lost as X to minimax. The hints look one move ahead. The solver looks to the end of the game, and nothing in the prompt does that. You could keep adding deeper hints, and at some point you have written minimax and put a two-second model call in front of it.
Q-learning and minimax went 20-0-0 against random. At 200 games, Q-learning lost 7 and minimax lost 1; the gap most likely comes from the 10% of positions where the Q-table still picks a suboptimal move. Minimax's one loss had to come as O, since X wins with perfect play and a random X can stumble onto a winning line.
On time: the Q-table lookup and the cached minimax both take around 10 microseconds per move. The LLM takes about 1.9 seconds of model compute per move on the same machine, more than 100,000 times slower, for worse moves. On this Mac, /api/ps showed the whole model in GPU memory, so the LLM had the GPU while the Python agents used one CPU core. One measuring trap: with other jobs sharing the Ollama server, wall-clock time per move went past 70 seconds, almost all of it queueing. The script records Ollama's own prompt_eval_duration and eval_duration fields so the reported number is model work, not waiting.
When RL and search beat an LLM, and where the LLM helps#
Search wins whenever you can write down the rules and the tree is small enough, or prunable enough, to look ahead. It is exact, it needs no training, and it explains itself: the principal variation is the reason for the move. Here it solved the game outright.
RL wins when you can simulate cheaply and the game is too big to solve but the same situations recur. It turns millions of fast simulated games into a policy that runs in microseconds. Its weak spots are the opposite of the LLM's: it knows nothing about the world outside its reward, and a tabular agent cannot generalise at all. A position it never saw in training has Q = 0 for every move, and it picks at random.
The LLM has no lookahead. It predicts a plausible next token given a picture of a board, and a 4x4 grid flattened into text loses most of the spatial structure that makes "three in a row" obvious to a person. Even when a model finds the right move, it pays seconds per move for something a 30-line function computes exactly.
Where the LLM earns its place is everywhere around the move:
- Explaining rules and positions to a human player, in plain language, after the engine has picked the move.
- Writing the environment and the reward. The engine in this post is the kind of code an LLM drafts well and a solver then checks.
- Proposing heuristics for games too big to search. An LLM can suggest "prefer centre columns" or "count open two-in-a-rows" as an evaluation function, which search then tests at depth.
- Handling the parts with no clean rules: negotiation games, natural-language moves, games where the state lives in text.
The llm+hints row shows the pattern that works in practice: deterministic code for the facts, the model for the judgement layer on top, and an evaluation that grades every decision.
Failure modes worth testing for#
- Grading against a weak opponent. The 94% win rate against random looked like a finished agent. The solver showed 10% of its moves were still wrong. Grade decisions, not just games.
- No exploration. With epsilon = 0, self-play converges on a handful of lines and the table stays mostly empty. Watch the table size column; if it stops growing early, the agent stopped exploring.
- Sign errors in the two-player target. Forgetting the minus sign in
-max Q(s', a')trains each side to help the other. The agent then loses to random more often than random loses to itself, which is an easy check to automate. - Unseen states. A tabular agent has no answer for positions it never visited. That is fine at 41,750 positions and hopeless at Connect Four size, where you need function approximation (a deep Q-network) or search with a learned evaluation, the AlphaZero recipe.
- LLM output and orientation. Without a schema, models wrap answers in prose. With a schema, they still confuse which row is the top. Spell it out in the prompt and count illegal moves as losses so the error shows up in the score.
- Timing under load. Measure model compute separately from wall time when a shared server is involved, or your latency numbers measure the queue.
Scaling the same ideas up#
The CartPole route is still a fine next step once the tabular version makes sense. The current Gymnasium release is 1.4.0, and CartPole-v1 gives +1 per step with a 500-step limit; its docs list a reward threshold of 500 for v1 and 200 for v0. An older "solved at an average of 195" bar comes from the v0 era, so an agent that clears 195 on v1 is not finished. The deep Q-network from the 2015 Nature paper replaces the dict with a neural network, adds a replay buffer and a separate target network, and the same Q-learning target from this post sits underneath.
For two-player games past the size of a table, Monte Carlo tree search with a learned value and policy network is the standard answer. It is the same split as above: search does the lookahead, learning supplies the judgement that search cannot afford to compute.
To run everything here: save drop3.py, search.py, solve.py, qlearn.py, curve.py, llm_agent.py and arena.py in one folder, run python3 solve.py, then python3 curve.py (about 35 seconds; it writes q_table.pkl for the arena), then ollama pull qwen3:4b-instruct and python3 arena.py 20. Pass --stub to run the arena without a model.
Sources#
- Sutton and Barto, Reinforcement Learning: An Introduction, 2nd edition (Q-learning, chapter 6): incompleteideas.net/book/the-book-2nd.html
- Watkins and Dayan, "Q-learning", Machine Learning 8, 1992: link.springer.com/article/10.1007/BF00992698
- Mnih et al., "Human-level control through deep reinforcement learning", Nature 518, 2015: nature.com/articles/nature14236
- Gymnasium CartPole documentation: gymnasium.farama.org/environments/classic_control/cart_pole
- Ollama chat API (timing fields): docs.ollama.com/api/chat
- Ollama structured outputs: docs.ollama.com/capabilities/structured-outputs
- Qwen3 4B instruct in the Ollama library: ollama.com/library/qwen3:4b-instruct
- John Tromp, Connect Four position count: tromp.github.io/c4/c4.html
- Silver et al., "Mastering Chess and Shogi by Self-Play with a General Reinforcement Learning Algorithm" (AlphaZero), 2017: arxiv.org/abs/1712.01815
- Python
functools.lru_cache: docs.python.org/3/library/functools.html