I wrote a rock, paper, scissors player for the M5Stack CoreS3 that learns how you play while you play. It trains on the device after every round, and it starts each game already knowing common human habits, learnt from 102,000 rounds of recorded games. It also locks in its move before you tap, so it can't cheat. The only way it wins is by predicting you.
Against a random player it breaks even. Against a player with a pattern it wins: a player who cycles rock, paper, scissors loses 98% of rounds. Against real recorded people it wins 43% of the first ten rounds and loses 28%, where chance would be 33% each.
This post walks through how it works, with the actual code and the numbers I measured, including an idea that made it worse. The code, the trained weights and the test harness are open source (MIT):
- esp32-rock-paper-scissors on GitHub
- jmclean/esp32-rock-paper-scissors on Hugging Face (the pre-trained weights)
| A new game | Playing a pattern | Playing at random |
|---|---|---|
![]() | ![]() | ![]() |
The bar shows how predictable you are over the last 20 rounds: how often it guessed your throw. The line marks chance, 33%. Stay near the line and it can't do better than break even.
Why this fits on a microcontroller
The CoreS3 is an ESP32-S3 at 240 MHz with 512 KB of internal RAM and a 320 x 240 touch screen. That's plenty here, because the learner is tiny:
- The neural network that trains on the device has 499 parameters (numbers it learns).
- The pre-trained network has the same shape, 499 parameters, compiled in as a 2 KB C header.
- Everything else is counting.
A whole round, including training, takes under 2.5 ms on the CoreS3. It's done between your tap and the screen updating.
The learner is in one C header, firmware/src/rps_model.h. The CoreS3 app, a version for ESP32-S3 boards without a screen, and a command-line version for your computer (host/rps.c) all use it. That meant I could test it on my laptop rather than on the device.
It can't see your move
The easiest way to write a rock, paper, scissors bot that always wins is to read the player's move and then pick. So the first rule was that it never sees your move first. Before each round it predicts your throw, chooses its own move and stores it. Your tap is scored against that stored move:
static void lockIn() { itsMove = rps_choose(&rps, &itsPredicted); } static void play(int you) { int res = rps_outcome(you, itsMove); score[res]++; ... rps_learn(&rps, you, itsMove, itsPredicted); // trains on the recent rounds ... lockIn(); // its next move, before you see this result drawBar(); drawMiddle(); } It learns from the round you just played and locks in its next move before the screen even shows you the result.
Moves are numbers throughout: 0 rock, 1 paper, 2 scissors. That makes the rules arithmetic. The move that beats m is (m + 1) % 3 (paper beats rock, scissors beats paper, rock beats scissors), and m beats (m + 2) % 3.
Step 1: a network that trains after every round
The first member of the team is a small neural network. It looks at the last three rounds and guesses your next throw.
What it sees
Each round is turned into nine numbers: your throw, its throw and who won, each as one-hot. One-hot means one number per possible value, set to 1 for the one that happened and 0 for the others, so "you threw paper" is 0 1 0. Three rounds of nine is 27 inputs. Rounds that haven't happened yet (at the start of a game) are all zeros:
static void rps_features(const Rps *r, float *x) { memset(x, 0, sizeof(float) * RPS_IN); for (int k = 0; k < RPS_K && k < r->n; k++) { int i = r->n - 1 - k, y = r->you[i % 1024], t = r->it[i % 1024]; x[k * 9 + y] = 1; x[k * 9 + 3 + t] = 1; x[k * 9 + 6 + rps_outcome(y, t)] = 1; } } Including who won, not just the moves, lets it pick up habits like "after losing, people switch" without having to work out the rules of the game first.
What it is
27 inputs feed 16 hidden units, each a weighted sum passed through tanh (a squashing function that keeps values between -1 and 1). Those feed 3 outputs, one per throw, turned into probabilities with softmax. Softmax raises e to the power of each output, then divides each by the total, so all three are positive and add up to 1, and the biggest output gets the biggest share. Outputs of 2, 1 and 0 become 67%, 24% and 9%. That's 27 x 16 + 16 + 16 x 3 + 3 = 499 parameters.
How it learns
After each round it takes one gradient step per example: nudge every weight a little in the direction that would have made the right answer more likely. The error measure is cross-entropy: minus the log of the probability it gave to the throw you actually made. If it gave your throw 100%, the error is 0; at 50% it's 0.69; at 10% it's 2.3. So it's punished most for being confidently wrong. The update is plain stochastic gradient descent (SGD), written out by hand. The learning rate, 0.05, sets how big each nudge is:
static void rps_step(Rps *r, const float *x, int y) { float hid[RPS_H], p[3]; rps_forward(r, x, hid, p); float dz[3], dh[RPS_H]; for (int o = 0; o < 3; o++) dz[o] = p[o] - (o == y); for (int h = 0; h < RPS_H; h++) { float s = 0; for (int o = 0; o < 3; o++) s += dz[o] * r->w2[o][h]; dh[h] = s * (1 - hid[h] * hid[h]); } for (int o = 0; o < 3; o++) { for (int h = 0; h < RPS_H; h++) r->w2[o][h] -= r->lr * dz[o] * hid[h]; r->b2[o] -= r->lr * dz[o]; } for (int h = 0; h < RPS_H; h++) { for (int i = 0; i < RPS_IN; i++) if (x[i]) r->w1[h][i] -= r->lr * dh[h] * x[i]; r->b1[h] -= r->lr * dh[h]; } } With softmax and cross-entropy, the error at each output is simply the predicted probability minus 1 for the right answer, or minus 0 for the others (p[o] - (o == y)). The 1 - hid * hid is the slope of tanh, which carries the error back to the hidden layer. Since the inputs are one-hot, most of them are 0, so the first layer skips them (if (x[i])).
One step on one round learns almost nothing. So it keeps the last 48 rounds in a replay buffer (a small ring of recent examples) and, after every round, goes over all of them three times. That's up to 144 small steps a round, still well inside the 2.5 ms.
Step 2: counting learners
A neural network is a slow way to notice "you always throw rock". Counting is faster. So most of the team are counting learners, each keeping counts of what you threw next in a different context:
| Learner | Counts what you throw... | Rows |
|---|---|---|
| Overall | at all | 1 |
| After your last throw | after rock, after paper, after scissors | 3 |
| After your last two throws | after each pair | 9 |
| After your last throw and its result | e.g. after rock that lost | 9 |
| After its last throw | after it played rock, and so on | 3 |
| After both last throws | after each pair of yours and its | 9 |
| During a losing streak | after your last throw, by how many rounds in a row you've just lost (0, 1, 2 or more) | 9 |
The last one is there because people change tack when they're losing.
Each learner looks up its row for the current situation and guesses in proportion to the counts, lightly smoothed so a count of zero doesn't mean "impossible":
static void rps_row(const float *c, float *p) { float t = c[0] + c[1] + c[2] + 0.9f; for (int m = 0; m < 3; m++) p[m] = (c[m] + 0.3f) / t; } Fast and slow
People change their habits mid-game, so old counts need to fade. But fade them too fast and noise looks like a habit. So every counting learner exists twice, with the same contexts and different memories. After each round, the counts in the row that applied are multiplied by a fade factor, and then the throw you made is added:
rps_add(r->cnt[0][row[k]], you, 0.75f); // fast rps_add(r->cnt[1][row[k]], you, 0.97f); // slow At 0.75, a round's weight halves in about 2.4 rounds, so the fast learners catch a new habit within a few rounds. At 0.97 it halves in about 23 rounds, so the slow ones hold steady against noise. Which to trust is left to the team (Step 4).
Step 3: a player who thinks one step ahead
A player who's been losing to "it beats what I usually throw" may start thinking: "it expects rock, so it will play paper, so I'll play scissors". That player is still predictable.
So every member of the team also exists in two shifted forms. If a member thinks you'll throw rock, the one-step form thinks you'll throw what beats the counter to rock, and the two-step form goes round once more:
for (int e = 0; e < RPS_BASE; e++) for (int sh = 1; sh <= 2; sh++) for (int m = 0; m < 3; m++) p[e + sh * RPS_BASE][(m + sh) % 3] = p[e][m]; There are 16 base members: the on-device network, the pre-trained network (Step 6), and seven counting learners, each fast and slow. Each in three forms makes 48 members in all.
Step 4: trust is earned
48 guesses need to become one. The team doesn't average them equally. Each member keeps a score of how well it has predicted you lately, and the team leans on the best.
The score is a fading sum of log-likelihoods. After each round, before anyone learns from it, each member's score is multiplied by 0.95 and then gets the log of the probability it gave to the throw you actually made. A member that said 90% for your real throw gains log(0.9) ≈ -0.1. One that said 10% gains log(0.1) ≈ -2.3. The 0.95 fade means it's roughly a judgement on the last 20 rounds:
for (int e = 0; e < RPS_TEAM; e++) r->skill[e] = fade * r->skill[e] + logf(t[e][you] + 1e-4f); The team's prediction weights each member by e raised to its score (a softmax over the scores). A member whose score is 1 higher than another's gets e ≈ 2.7 times the weight, so the best few soon dominate:
for (int e = 0; e < RPS_TEAM; e++) if (r->skill[e] > mx) mx = r->skill[e]; for (int e = 0; e < RPS_TEAM; e++) { w[e] = expf((r->skill[e] - mx) * RPS_TRUST); sum += w[e]; } for (int m = 0; m < 3; m++) { p[m] = 0; for (int e = 0; e < RPS_TEAM; e++) p[m] += w[e] / sum * t[e][m]; } No single learner is good against everyone. "Always rock" is caught instantly by the fast overall count. A cycle is caught by "after your last throw". Win-stay, lose-shift (throw the same again after a win, change after a loss) is caught by "after your last throw and its result". The scoring finds out which one fits this player, and switches when the player changes.
Step 5: choosing its move
With a prediction in hand, the obvious move is the one that beats your most likely throw. But a bot that always plays the obvious move can itself be predicted and beaten.
So it scores each of its three moves by expected value: the chance that move wins minus the chance it loses. Playing m wins against (m + 2) % 3 and loses against (m + 1) % 3:
for (int m = 0; m < 3; m++) { ev[m] = p[(m + 2) % 3] - p[(m + 1) % 3]; if (ev[m] > top) top = ev[m]; } for (int m = 0; m < 3; m++) { w[m] = expf((ev[m] - top) * RPS_SHARP); // sharper as the prediction gets surer sum += w[m]; } Then it picks at random, weighted by w. The RPS_SHARP of 30 sets how decisive that is. If the prediction is sure (one move 0.1 better than the next in expected value), the best move gets e^3 ≈ 20 times the weight and is nearly always played. If the prediction is close to even, the three weights are nearly equal and its move is close to random. The random numbers come from xorshift32, a pseudo-random number generator that's three lines of code.
Step 6: a head start from recorded games
Everything so far starts each game knowing nothing. For the first few rounds it's guessing.
People aren't random, even at the start. So the last member of the team is a second network, the same shape as the one in Step 1, trained beforehand on recorded games and then fixed. It never trains on the device. It knows how people in general play: what they open with (paper 44%, rock 30%, scissors 26%), and what they tend to do after a win or a loss.
The data
The games come from Erik Brockbank and Edward Vul at UC San Diego, from two studies: people playing people, and people playing fixed-pattern and learning bots. After cleaning, that's 345 players and 102,318 rounds:
| Games | Players |
|---|---|
| People against people, 300 rounds each | 86 |
| People against fixed-pattern bots | 130 |
| People against learning bots | 129 |
The bot games are released as CC0 (public domain). The people-against-people games are in a public repository with no licence stated. Neither is included in my repo. A script downloads them from the original repositories instead:
training/get_data.sh training/prepare_games.py turns each player into two sequences, their throws and their opponent's, as 0, 1 and 2. Players with missing rounds are dropped, and nothing else is kept: no IDs, timings or course-credit codes.
python training/prepare_games.py data/ data/games.npz Training
training/pretrain.py builds exactly the same 27 inputs as rps_features() on the device, one example per round, and trains the 27 ‚Üí 16 ‚Üí 3 network in PyTorch. Here it uses Adam (a version of gradient descent that adapts the step size for each weight) with a learning rate of 0.003 and a little weight decay (0.0001, a gentle pull of every weight towards zero, to stop it memorising). 10% of the training players are kept aside, and training stops once its error on those players (the loss) hasn't improved for 8 passes through the data (early stopping). It takes under a minute on a laptop:
python training/pretrain.py data/games.npz firmware/src/rps_pretrained.h --all --weights weights/rps-human-habits.safetensors It writes the weights as a C header that the firmware includes:
open(sys.argv[2], "w").write( "// Generated by training/pretrain.py from Brockbank & Vul's recorded games. Do not edit.\n" ... f"static const float RPS_PRE_W1[{H}][{IN}] = {rows(W1)};\n" f"static const float RPS_PRE_B1[{H}] = {arr(B1)};\n" f"static const float RPS_PRE_W2[3][{H}] = {rows(W2)};\n" f"static const float RPS_PRE_B2[3] = {arr(B2)};\n") On the device that's 2 KB of constant arrays in flash, so there's no model file to load. The same weights are also written as a safetensors file (a simple format: a JSON header saying each array's name, type and shape, then the raw numbers), for Hugging Face. The script writes that format directly rather than pulling in another library.
How much to trust it
The pre-trained network is just another member of the team, but it starts with a head start: a score of 8 while every other member starts at 0. That's e^8, about 3,000 times the weight of any other member, so the first rounds follow it. Every round it predicts badly costs it score, and every round another member predicts well earns that member score. Once the learners know the player, they take over.
r->skill[1] = RPS_PRIOR_HEAD; // 8 The comment in the code says 8 did best against real players in cross-validation (next step).
Step 7: measure it
There are two ways to test a learner like this, and I used both.
Against fake players
The computer version has a test mode that plays 50 games of 60 rounds against twelve made-up players, each with a different habit:
cc -O2 -Ifirmware/src -o rps host/rps.c -lm ./rps --test | Player | You win | It wins | Draws |
|---|---|---|---|
| Random | 33% | 33% | 34% |
| Always rock | 5% | 95% | 0% |
| Half rock, half random | 23% | 52% | 25% |
| Cycles rock, paper, scissors | 2% | 98% | 0% |
| Win-stay, lose-shift | 3% | 97% | 1% |
| Beats its last move | 4% | 92% | 4% |
| Cycle with 30% random | 19% | 59% | 22% |
| Counters the counter | 1% | 91% | 8% |
| Copies its last move | 4% | 92% | 4% |
| Beats its favourite | 21% | 65% | 14% |
| Switches strategy every 15 rounds | 5% | 90% | 6% |
| Switches strategy when losing | 14% | 57% | 28% |
The random player breaks even, as nothing can beat a random player. Everything with a pattern loses, and a plain cycle is caught within about five rounds. The hardest are the noisy ones (half random, 30% random) and the ones that react to it (beats its favourite, switches when losing).
Fake players are useful for catching bugs, but they don't tell you whether it works on people.
Against recorded people
training/crossval.py replays the recorded games through the full device learner, round by round. It uses five-fold cross-validation by player: split the 345 players into five groups, and for each group, train a fresh pre-trained network on the other four and test on that one. So no player is ever tested on a network that saw their games.
The learner locks in its move before seeing each throw, and is scored against the throw the player really made. One caveat: those players were answering a different opponent, not this one, so it's a replay, not a live game.
| Recorded players | First rounds | Predicted | It wins | You win |
|---|---|---|---|---|
| People against people | 10 | 44% | 43% | 28% |
| 20 | 44% | 43% | 27% | |
| 30 | 44% | 43% | 27% | |
| People against learning bots | 10 | 44% | 45% | 26% |
| 20 | 45% | 44% | 25% | |
| 30 | 44% | 44% | 25% | |
| People against fixed-pattern bots | 10 | 51% | 49% | 22% |
| 20 | 51% | 50% | 22% | |
| 30 | 53% | 52% | 22% |
Chance is 33% in every column. Against people playing people, it predicts 44% of throws from the very first rounds and wins 43 rounds in every 100 to their 28.
What the head start is worth
The same cross-validation, with and without the pre-trained network, measuring how often the team predicts the next throw of the people-against-people players:
| Rounds | 1 to 5 | 6 to 20 | 21 to 60 | 61 on |
|---|---|---|---|---|
| Without | 37% | 38% | 44% | 49% |
| With | 44% | 44% | 46% | 49% |
In the first 20 rounds it lifts prediction from barely above chance to 44%. By round 60 the learners know the player and it makes no difference.
I also built the computer version without it (-DRPS_NO_PRETRAINED) and ran the fake players again. It helps against some and costs against others:
| Player | It wins, without | It wins, with |
|---|---|---|
| Always rock | 97% | 95% |
| Cycles rock, paper, scissors | 94% | 98% |
| Win-stay, lose-shift | 90% | 97% |
| Beats its last move | 94% | 92% |
| Cycle with 30% random | 54% | 59% |
| Counters the counter | 95% | 91% |
| Switches strategy every 15 rounds | 86% | 90% |
Against a player who does something no person would (always rock), knowing how people play slows it down for a few rounds. Against the patterns people actually use, like win-stay, lose-shift, it helps. As it's meant for people, I kept it.
What didn't work
The code still carries one idea that's switched off, RPS_REJUDGE. The thinking was: a person who keeps losing is likely to change how they play, so after it wins two in a row, fade the team's scores faster (0.7 instead of 0.95) so whoever predicts the new habit takes over sooner.
It made things worse. I re-ran the fake players with it on (-DRPS_REJUDGE=1):
| Player | It wins, off | It wins, on |
|---|---|---|
| Half rock, half random | 52% | 50% |
| Cycle with 30% random | 59% | 55% |
| Switches strategy every 15 rounds | 90% | 84% |
| Switches strategy when losing | 57% | 58% |
It barely helped the one player it was designed for, and it hurt the noisy players. Forgetting faster means trusting whoever got lucky in the last couple of rounds, and with a noisy player that's often the wrong member. So it stays off, and the code says why:
#define RPS_REJUDGE 0 // re-judge the team faster after it wins twice in a row (tested: hurt against noisy players) The losing-streak counting learner (Step 2) is a similar idea that I kept. It doesn't change how the team is judged. It gives the team one more member that knows about losing streaks, and lets the scoring decide whether to use it. On the fake players it makes little difference either way, and I haven't measured it separately on the recorded people.
Play it
On your computer
No ESP32 needed, just a C compiler:
cc -O2 -Ifirmware/src -o rps host/rps.c -lm ./rps Type r, p or s each round, or a string of them, and q to stop. After each round it tells you what it predicted you'd throw.
On an M5Stack CoreS3
From firmware/, with PlatformIO:
pio run -e m5stack-cores3 -t upload Tap rock, paper or scissors. New (top right), or a long press, starts a new game. Over USB serial at 115200 you can also type r, p or s, new or stat, and shot sends the screen to tools/screenshot.py. Each round prints what it predicted and how long training took.



