Reinforcement learning

C3RL: learning through self-play

Q-learning, SARSA and where deep Q-learning fits next.

The question

If two agents learn the same game by playing against themselves, how much does the learning rule matter? C3RL compares tabular Q-learning and SARSA on Connect-3: the same board, rewards, training budget, and exploration schedule, with a different update target.

Q-learning is off-policy: its update target uses the greedy next action, even when the agent explores. SARSA is on-policy: its target uses the action actually taken. In practical terms, SARSA learns the value of the exploring policy it follows, mistakes included, while Q-learning learns about the greedy policy regardless of how it explores.

After 100,000 games each, both agents were strong against simple opponents. Against each other, the score was exactly 0.50. Interpreting that tie depends on accounting for the game’s first-move advantage.

SARSA is conservative; Q-learning is aggressive. Does that distinction produce a measurably different agent?

The sections below present the comparison, its results, and a mapped extension into deep Q-learning.

The setup

Connect-3 uses a 4 × 4 board with gravity. Players alternate dropping a piece into one of four columns. Three pieces in a horizontal, vertical, or diagonal line wins; a full board with no winner is a draw.

The smaller board makes repeated visits to state-action pairs realistic for tabular learning and keeps a full-depth solver practical as a reference. There is no external dataset: the training data is the sequence of state, action, and reward transitions produced by self-play.

A state is the flattened board from the current player’s perspective: +1 for their pieces, −1 for their opponent’s, and 0 for empty cells. An action is a column index. Full columns are masked during both move selection and target calculation.

A state, an action, and the next state

state → action → next state

state scurrent player’s view

action achoose a column

A(s) = {1, 2, 3}

next state s′next player’s view

A state records the board from the current player’s perspective. An action selects a legal column; s′ shows the resulting board from the next player’s view.

Two learning rules

Both methods move an action value toward a target. The learning rate α\alpha controls the size of that correction.

Q(s,a)←Q(s,a)+α [y−Q(s,a)]Q(s,a) \leftarrow Q(s,a) + \alpha\,[y-Q(s,a)]
The shared temporal-difference update

The distinction is entirely in yy. Q-learning asks which legal next action looks best; SARSA uses the next action sampled by the same exploratory policy that generated the game.

Q-learningoff-policy

col 0full
col 10.18
col 20.62best
col 30.31

Uses the best-looking legal reply: max Q(s′, b) = 0.62

SARSAon-policy

col 0full
col 10.18
col 20.62
col 30.31sampled

Uses the reply actually sampled: Q(s′, a′) = 0.31

Since s′ belongs to the opponent, its selected value enters the current player’s target with a minus sign.

The opponent changes the sign

The next state belongs to the other player. A valuable position for them is bad for the player who just moved, so the usual positive bootstrap becomes a negative one. For a nonterminal transition:

yQ=r−γmax⁡b∈A(s′)Q(s′,b)ySARSA=r−γQ(s′,a′)\begin{aligned} y_{\mathrm{Q}} &= r-\gamma\max_{b\in A(s')}Q(s',b) \\ y_{\mathrm{SARSA}} &= r-\gamma Q(s',a') \end{aligned}
A(s′) contains legal columns; a′ is the action actually taken next

Here γ\gamma discounts future value. Without the minus sign, an agent would learn to favor positions that are good for its opponent. Terminal targets use reward alone: a winning final move receives +1, the losing player’s final move receives −1, and a draw receives 0. Each method has its own table. Within a method, both sides share that table through the perspective convention.

The experiment

The experiment keeps the main training choices fixed so the update rule is the intended difference. Values start at zero. Exploration chooses uniformly among legal moves; greedy play breaks value ties randomly.

Shared training and evaluation settings
Training budget100,000 self-play games per learner
Learning rate / discountα = 0.30 / γ = 0.95
Explorationε starts near 0.30 and decreases to a floor of 0.02
Learning-curve checkpointsEvery 2,000 games; 500 games against the heuristic
Tournament500 games per ordered pairing; alternating first mover
RandomnessGlobal seed 486; one training run per method

The exploration schedule is ϵg=max⁡{0.02,  0.30(1−g/G)}\epsilon_g=\max\{0.02,\;0.30(1-g/G)\}, where G=100,000G=100{,}000. It reaches the floor before training ends. Evaluation is greedy, although equal-valued actions can still be broken randomly.

Three reference opponents provide context:

  • Random: chooses a uniformly random legal column.
  • Heuristic: takes an immediate win, otherwise blocks an immediate loss, otherwise plays randomly.
  • Perfect: searches to the end of the game using memoized negamax.

The solver uses the same change of perspective. A winning move is worth +1, a board-filling draw is worth 0, and any other move is worth the negative of the resulting position’s value to the opponent.

v(s)=max⁡a∈A(s){+1if a wins,0if a draws,−v(s′)otherwise.v(s)=\max_{a\in A(s)}\begin{cases} +1 & \text{if }a\text{ wins}, \\ 0 & \text{if }a\text{ draws}, \\ -v(s') & \text{otherwise}. \end{cases}
Full-depth negamax with outcome-only rewards

Results

Both agents learn

Early performance improves quickly, then the learning curves spend much of the run in a similar band. They cross repeatedly, with neither method maintaining a clear learning-speed advantage.

Learning against the heuristic

Win rate100,000 / 100,000
Learning against the heuristicWin rate by training games. Q-learning, SARSA. Use the vertical slider to reveal the lines.00.250.50.751025k50k75k100k

Training games

Figure 1. Greedy win rate against the heuristic, evaluated every 2,000 training games over 500 evaluation games. The 0-game point is an unmeasured visual origin; measured checkpoints begin at 2,000. Straight segments connect values without smoothing.

Tournament results

The tournament gives a win 1 point, a draw 0.5, and a loss 0. This differs from the pure win rate plotted above. Each entry is the row player’s average score against the column player, with both move orders represented.

C3RL · tournament score

Row → column
C3RL · tournament score. Figure 2. Ordered-pair tournament scores: win = 1, draw = 0.5, loss = 0. Opposite cells come from separate evaluations, so their sums can vary. Diagonals are unmeasured.
Row playerQ-learningSARSAPerfectHeuristicRandom
Q-learning—
SARSA—
Perfect—
Heuristic—
Random—

Hover, tap, or tab to inspect a score.

0.01.0
Figure 2. Ordered-pair tournament scores: win = 1, draw = 0.5, loss = 0. Opposite cells come from separate evaluations, so their sums can vary. Diagonals are unmeasured.

Q-learning scores 0.94 against Random and 0.85 against Heuristic. SARSA scores 0.96 and 0.92 respectively. Both agents genuinely learned. The heuristic gap is worth investigating. Establishing an algorithm-level advantage requires multiple training runs per method.

Why everything strong lands at 0.50

Connect-3 on this board is a first-player win under perfect play. All pairings among Q-learning, SARSA, and Perfect score 0.50. A separate 1,000-game evaluation against the solver gives 50% wins, no draws, and 50% losses for each learner.

First-move advantage dominates play among strong agents. Alternating who starts produces a statistical tie when each agent converts its games as the first player. The 0.50 score can therefore represent alternating wins across the two move orders.

A perfect solver maximizes the theoretical game outcome. From a lost position, it can treat several losing moves as equivalent, even when some would give a weaker opponent more chances to make a mistake.

What the tie means

The head-to-head score is 0.500 ± 0.044, using an approximate 95% interval over 500 games. That interval describes finite evaluation sampling. Variation across independently trained agents requires multiple runs. The score statistic also allows half-points, so a binomial interval is only an approximation when draws occur.

These trained agents tied in this evaluation. Their performance against the solver supports strong play on the tested trajectories. Establishing optimal decisions in every reachable state requires a separate analysis.

Exploration never fully disappears. The learning rate stays constant. Self-play changes the opponent as learning progresses. A single seed also cannot reveal run-to-run variability. Sequential training gives the learners different random trajectories.

Multiple seeds, side-specific results, and checks against solver-labeled positions would make the comparison stronger. A larger board may also expose the conservative and aggressive tendencies that this solved game compresses into the same alternating-start score.

Deep Q-learning

The extension asks whether a learned value function can generalize across board positions once a table becomes too sparse. It begins on the same 4 × 4 game, where the tabular agents and full-depth solver can catch implementation errors, then scales to a larger board.

Model and representation

Three binary input planes encode current-player pieces, opponent pieces, and empty cells. A starting model flattens the 3 × 4 × 4 input into two 64-unit ReLU layers with four outputs, one Q-value per column. A convolutional model becomes a later architectural comparison.

Replay entries contain state, action, reward, next state, terminal status, and the next legal-action mask. A replay buffer breaks temporal correlation; a separate target network slows movement in bootstrap values. Illegal columns are masked before every maximum or action selection.

Target and replay

The one-ply next-player perspective keeps the negative bootstrap. The plan compares standard DQN with Double DQN, which separates selecting the next action from evaluating it. With online parameters θ\theta and target parameters θˉ\bar\theta:

a∗=arg⁡max⁡b∈A(s′)  Qθ(s′,b)y={rif terminal,r−γQθˉ(s′,a∗)otherwise.\begin{aligned} a^* &= \underset{b\in A(s')}{\arg\max}\;Q_\theta(s',b) \\ y &= \begin{cases} r & \text{if terminal}, \\ r-\gamma Q_{\bar\theta}(s',a^*) & \text{otherwise}. \end{cases} \end{aligned}
Double DQN adapted to the next-player perspective

Replay entries are created after each full game, preserving +1 for the winning final move and −1 for the losing final move. Terminal entries never bootstrap. Unit tests cover one-move wins, losing replies, draws, full columns, legal masks, and flipped player perspectives before any long run begins.

Experiment map

Deep Q-learning experiment sequence
StepBuild / measureWhat it answers
01 · BaselineRepeat the tabular agents across at least five independent training seeds.How much of the observed gap is run-to-run noise?
02 · DQNSmall MLP, replay buffer, target network, legal-action masking, and Huber loss on the same board.Can function approximation recover strong small-board play?
03 · Double DQNSeparate action selection and evaluation; vary target-update frequency and replay settings.Which choices affect stability and sample efficiency?
04 · ScaleMove to 5 × 5 Connect-4 under matched interaction budgets and explicit search limits.Does generalization help when repeated states become rarer?

The initial configuration uses a 50,000-transition buffer, batch size 64, Adam at 0.001, 1,000 replay-warm-up transitions, and a hard target update every 1,000 optimizer steps. These are starting hypotheses to log and tune, while the tabular discount and exploration schedule anchor the first comparison.

Current-policy self-play is compared with a pool of frozen opponent snapshots while evaluation opponents remain fixed. Reports separate first- and second-player performance, wins, draws, losses, seed spread, environment moves, and wall-clock cost. On the small board, a held-out set of solver-labeled positions measures whether chosen moves preserve the best available outcome.

References

  1. Richard S. Sutton and Andrew G. Barto. Reinforcement Learning: An Introduction, second edition, 2018.
  2. Donald E. Knuth and Ronald W. Moore. An analysis of alpha-beta pruning, 1975.
  3. Volodymyr Mnih et al. Human-level control through deep reinforcement learning, 2015.
  4. Hado van Hasselt, Arthur Guez, and David Silver. Deep Reinforcement Learning with Double Q-learning, 2015.