Games

Nim with Q-Learning

Q-Learning

Play Nim with a trainable Q-Learning agent and a live Q-table

Game

Current turnYour turn
15
Last player None
Sticks taken0

Live Q-Table

BadGood
StateTake 1Take 2Take 3
15 0.00 0.00 0.00
14 0.00 0.00 0.00
13 0.00 0.00 0.00
12 0.00 0.00 0.00
11 0.00 0.00 0.00
10 0.00 0.00 0.00
9 0.00 0.00 0.00
8 0.00 0.00 0.00
7 0.00 0.00 0.00
6 0.00 0.00 0.00
5 0.00 0.00 0.00
4 0.00 0.00 0.00
3 0.00 0.00 0.00
2 0.00 0.00 0.00
1 0.00 0.00 0.00
0 0.00 0.00 0.00

Metrics

Episodes trained0
Current win rate0.0%
Current epsilon1.000
ModelModel: current session

About this tool

Nim is a combinatorial game between two players with an exact mathematical solution based on the XOR operation on pile sizes: a position is losing for the player to move if and only if the XOR of all piles (the nim-sum) is zero. In this tool, Nim is used as a learning environment for a Q-Learning agent that must discover this strategy empirically.

Q-Learning is a model-free reinforcement learning algorithm that learns the action-value function Q(s,a)Q(s, a), the expected reward of taking action aa in state ss and following the optimal policy thereafter. The update follows the Bellman equation: Q(s,a)←Q(s,a)+α[r+γmax⁡a′Q(s′,a′)−Q(s,a)]Q(s,a) \leftarrow Q(s,a) + \alpha\left[r + \gamma \max_{a'} Q(s',a') - Q(s,a)\right] where α\alpha is the learning rate, γ\gamma the discount factor, rr the immediate reward, and s′s' the next state.

Observe how the Q-table evolves during training and how the agent progressively learns to avoid losing states. The exploration-exploitation dilemma, one of the central concepts in reinforcement learning, becomes visible in real time: the agent must balance exploring new strategies with exploiting those it already knows work.