How Token Rain Was Built
This page exists to demonstrate one thing concretely: what it actually looks like when an AI writes software. Not a toy autocomplete, not a snippet — a complete, working browser game, designed and implemented in a single session, documented by the same AI that wrote it.
The idea: you are the model
The training essay on this site explains that a language model does exactly one thing: predict the next token. Shown “the cat sat on the…”, it assigns a probability to every possible next token and the likely ones float to the top. Generate a token, append it, predict again — that loop, called autoregressive generation, is how every chat answer you’ve ever read was produced.
Token Rain turns that loop into an arcade mechanic:
- The sentence at the top is the context — what the model has produced so far.
- The falling pills are candidate tokens. One genuinely belongs; the rest are low-probability nonsense (a real model considers “banana” too — it just scores it terribly).
- You are the sampler: catch the token that should come next. Each catch appends to the sentence, and the sentence you build is the generation.
- Your loss bar is the same idea as the training loss in the essay: wrong predictions push it up, good ones pull it down. When the run ends you even get your own loss curve — the same chart researchers stare at during real training runs.
One honest detail: each sentence starts with two words already filled in. A model with no context can’t predict meaningfully, and neither can you — prediction needs something to condition on.
How the AI built it
The build followed the same editor/author split as the other essays on this site, except this time the output was software:
- The brief (human). “Add a JavaScript game that shows AI can code. Simple enough for teenagers to understand, graphics required, tied to the concepts in the site’s articles, and original — nothing that invites a lawyer’s letter.”
- Research (AI). Claude read every page of this site — the essays on the Transformer, training, and scaling — plus the site’s code, design system, and bilingual setup.
- Proposals (AI), decision (human). The model pitched three original concepts: a gradient-descent physics game, a word-vector navigation game, and Token Rain. Miguel picked Token Rain — partly because the site’s background already rains code tokens, so the game grows out of the site’s own visual identity.
- Implementation (AI). One Astro component: the game is plain JavaScript drawing on a
<canvas>, no game engine, no libraries, no assets to download. It speaks both of the site’s languages and reads its colors from the site’s CSS variables, so it can never fall out of theme. - Review (human). Play-testing, tuning, and the decision to ship.
The split matters. The AI contributed speed and breadth — design, code, prose, two languages, in one sitting. The human contributed the things the AI cannot own: taste, judgment, and accountability for what got published.
The JavaScript inside (the fun parts)
If you’re learning to code, these are the five tricks doing the heavy lifting. View the page source — all of it is readable.
1. The game loop
Games don’t run on events; they run on a heartbeat. The browser provides one called requestAnimationFrame, which calls your function once per screen refresh:
let last = performance.now();
function frame(now) {
const dt = Math.min((now - last) / 1000, 0.05); // seconds since last frame
last = now;
update(dt); // move everything: position += speed * dt
draw(); // repaint everything
requestAnimationFrame(frame); // ask for the next heartbeat
}
requestAnimationFrame(frame);
The subtle part is dt (delta time). Frames don’t arrive on a perfect schedule — a 144 Hz monitor gets more of them than a 60 Hz laptop. Moving things by speed × dt instead of a fixed step per frame keeps the game equally fast on both. The Math.min(…, 0.05) cap stops the game from teleporting forward after a stutter or a background tab pause.
2. Drawing with canvas
<canvas> is a blank rectangle you paint with code, sixty times a second, from scratch:
ctx.clearRect(0, 0, W, H); // wipe the previous frame
ctx.fillStyle = '#111a33';
ctx.fill(pillPath); // each token is a rounded rectangle
ctx.fillText(token.word, x, y); // with its word drawn on top
There are no objects to move around — the illusion of motion is just “erase everything, redraw everything slightly lower.” One extra wrinkle: on a high-resolution display, a canvas drawn at CSS size looks blurry, so the game scales the canvas by devicePixelRatio and then draws in normal coordinates.
3. Collision detection
How does the game know you caught a token? The oldest trick in game programming — AABB (axis-aligned bounding box) overlap. Two rectangles overlap when they overlap on both axes:
const caught =
token.y + token.h / 2 >= catcherTop && // low enough, and
Math.abs(token.x - catcher.x) < (token.w + catcher.w) / 2; // lined up
That’s the entire physics engine. Pong, Space Invaders, and most platformers you’ve played run on this same comparison.
4. Particles and screen shake
The “juice” — the burst when you catch a token, the shudder when you grab nonsense — comes from two tiny systems. A particle is just an object with a position, a velocity, and a lifespan:
particles.push({ x, y, vx: Math.cos(a) * speed, vy: Math.sin(a) * speed, life: 0.65 });
// every frame: move it, apply gravity (vy += g * dt), fade it, delete it when life ≤ 0
Screen shake is even simpler: when you catch a wrong token, the whole canvas is drawn at a small random offset that decays back to zero over a few frames. Cheap to write, and it’s most of what makes the game feel like a game.
5. A state machine
The game is always in exactly one state — title, playing, paused, or over — stored in a single variable. Every input asks “what state am I in?” before acting, which is what keeps the pause menu from catching tokens. A bonus trick: the state is mirrored onto the HTML (data-state="paused"), and CSS decides which overlay panel is visible. The JavaScript never shows or hides panels — it just announces the state, and the stylesheet does the rest. The site’s language toggle works exactly the same way, which is also why the game is bilingual for free.
Why this game won’t get a cease-and-desist
The mechanic — catch the correct next word from a falling set — isn’t borrowed from any commercial title; it falls out of the subject matter itself. The pills, palette, and falling-token aesthetic come from this site’s own design system. Game mechanics as such aren’t protectable, but cloning a specific game’s expression invites trouble; an original mechanic built on your own visual identity is the clean path.
Try it yourself
The most repeatable lesson here isn’t in the code — it’s the workflow. Pick something you understand well enough to judge, write a clear brief, let an AI propose options, choose one, and make it explain every trick it used. You’ll end up with working software and the understanding to maintain it. That’s learning by doing, with a very patient lab partner.
Cómo se construyó Token Rain
Esta página existe para demostrar una sola cosa de forma concreta: cómo se ve en la práctica que una IA escriba software. No un autocompletado de juguete, no un fragmento — un juego de navegador completo y funcional, diseñado e implementado en una sola sesión, y documentado por la misma IA que lo escribió.
La idea: tú eres el modelo
El ensayo sobre entrenamiento de este sitio explica que un modelo de lenguaje hace exactamente una cosa: predecir el siguiente token. Si le muestras “el gato se sentó en la…”, le asigna una probabilidad a cada token posible y los más probables flotan hacia arriba. Genera un token, lo añade, predice de nuevo — ese bucle, llamado generación autorregresiva, es como se produjo cada respuesta de chat que has leído.
Token Rain convierte ese bucle en una mecánica de arcade:
- La oración de arriba es el contexto — lo que el modelo ha producido hasta ahora.
- Las píldoras que caen son tokens candidatos. Uno de verdad encaja; el resto son disparates de baja probabilidad (un modelo real también considera “arepa” — solo que le da un puntaje pésimo).
- Tú eres el muestreador: atrapa el token que debería venir después. Cada atrapada se añade a la oración, y la oración que construyes es la generación.
- Tu barra de pérdida es la misma idea que la pérdida de entrenamiento del ensayo: las predicciones malas la suben, las buenas la bajan. Al final de la partida hasta recibes tu propia curva de pérdida — la misma gráfica que los investigadores miran fijamente durante un entrenamiento real.
Un detalle honesto: cada oración empieza con dos palabras ya colocadas. Un modelo sin contexto no puede predecir nada con sentido, y tú tampoco — predecir necesita algo sobre lo cual condicionar.
Cómo lo construyó la IA
La construcción siguió la misma división editor/autor que los otros ensayos de este sitio, solo que esta vez el resultado fue software:
- El encargo (humano). “Agrega un juego en JavaScript que muestre que la IA puede programar. Lo bastante simple para que lo entiendan adolescentes, con gráficos, conectado a los conceptos de los artículos del sitio, y original — nada que invite la carta de un abogado.”
- Investigación (IA). Claude leyó todas las páginas de este sitio — los ensayos sobre el Transformer, el entrenamiento y el escalamiento — más el código del sitio, su sistema de diseño y su montaje bilingüe.
- Propuestas (IA), decisión (humano). El modelo presentó tres conceptos originales: un juego de física sobre descenso de gradiente, uno de navegación por vectores de palabras, y Token Rain. Miguel escogió Token Rain — en parte porque el fondo del sitio ya llueve tokens de código, así que el juego nace de la propia identidad visual del sitio.
- Implementación (IA). Un solo componente de Astro: el juego es JavaScript puro dibujando sobre un
<canvas>, sin motor de juegos, sin librerías, sin assets que descargar. Habla los dos idiomas del sitio y lee sus colores de las variables CSS del sitio, así que nunca puede desentonar con el tema. - Revisión (humano). Pruebas jugando, ajustes, y la decisión de publicar.
La división importa. La IA aportó velocidad y amplitud — diseño, código, prosa, dos idiomas, en una sentada. El humano aportó lo que la IA no puede poseer: gusto, criterio y la responsabilidad por lo que se publicó.
El JavaScript por dentro (las partes divertidas)
Si estás aprendiendo a programar, estos son los cinco trucos que hacen el trabajo pesado. Mira el código fuente de la página — todo es legible.
1. El bucle del juego
Los juegos no corren con eventos; corren con un latido. El navegador ofrece uno llamado requestAnimationFrame, que llama a tu función una vez por refresco de pantalla:
let last = performance.now();
function frame(now) {
const dt = Math.min((now - last) / 1000, 0.05); // segundos desde el último frame
last = now;
update(dt); // mueve todo: posición += velocidad * dt
draw(); // repinta todo
requestAnimationFrame(frame); // pide el siguiente latido
}
requestAnimationFrame(frame);
La parte sutil es dt (delta time). Los frames no llegan con horario perfecto — un monitor de 144 Hz recibe más que una laptop de 60 Hz. Mover las cosas por velocidad × dt en vez de un paso fijo por frame mantiene el juego igual de rápido en ambos. El tope Math.min(…, 0.05) evita que el juego se teletransporte hacia adelante después de un tropezón o una pestaña en segundo plano.
2. Dibujar con canvas
<canvas> es un rectángulo en blanco que pintas con código, sesenta veces por segundo, desde cero:
ctx.clearRect(0, 0, W, H); // borra el frame anterior
ctx.fillStyle = '#111a33';
ctx.fill(pillPath); // cada token es un rectángulo redondeado
ctx.fillText(token.word, x, y); // con su palabra dibujada encima
No hay objetos que mover — la ilusión de movimiento es solo “borra todo, redibuja todo un poquito más abajo”. Un detalle extra: en una pantalla de alta resolución, un canvas dibujado al tamaño CSS se ve borroso, así que el juego escala el canvas por devicePixelRatio y luego dibuja en coordenadas normales.
3. Detección de colisiones
¿Cómo sabe el juego que atrapaste un token? El truco más viejo de la programación de juegos — la superposición AABB (caja delimitadora alineada a los ejes). Dos rectángulos se superponen cuando se superponen en ambos ejes:
const atrapado =
token.y + token.h / 2 >= bordeSuperior && // bajó lo suficiente, y
Math.abs(token.x - catcher.x) < (token.w + catcher.w) / 2; // está alineado
Ese es todo el motor de física. Pong, Space Invaders y la mayoría de los juegos de plataformas que has jugado corren sobre esta misma comparación.
4. Partículas y sacudida de pantalla
La “salsa” — el estallido cuando atrapas un token, el temblor cuando agarras un disparate — viene de dos sistemas chiquitos. Una partícula es solo un objeto con posición, velocidad y tiempo de vida:
particles.push({ x, y, vx: Math.cos(a) * vel, vy: Math.sin(a) * vel, life: 0.65 });
// cada frame: muévela, aplica gravedad (vy += g * dt), desvanécela, bórrala cuando life ≤ 0
La sacudida de pantalla es aún más simple: cuando atrapas un token equivocado, todo el canvas se dibuja con un pequeño desplazamiento aleatorio que decae a cero en unos pocos frames. Barato de escribir, y es buena parte de lo que hace que el juego se sienta como un juego.
5. Una máquina de estados
El juego está siempre en exactamente un estado — title, playing, paused o over — guardado en una sola variable. Cada entrada pregunta “¿en qué estado estoy?” antes de actuar, que es lo que evita que el menú de pausa atrape tokens. Un truco extra: el estado se refleja en el HTML (data-state="paused"), y el CSS decide qué panel se ve. El JavaScript nunca muestra ni oculta paneles — solo anuncia el estado, y la hoja de estilos hace el resto. El selector de idioma del sitio funciona exactamente igual, y por eso el juego salió bilingüe gratis.
Por qué este juego no va a recibir una carta de cese y desistimiento
La mecánica — atrapar la siguiente palabra correcta entre un grupo que cae — no está tomada de ningún título comercial; sale del propio tema. Las píldoras, la paleta y la estética de tokens cayendo vienen del sistema de diseño de este mismo sitio. Las mecánicas de juego como tales no son protegibles, pero clonar la expresión de un juego específico busca problemas; una mecánica original construida sobre tu propia identidad visual es el camino limpio.
Pruébalo tú mismo
La lección más repetible de todo esto no está en el código — está en el flujo de trabajo. Escoge algo que entiendas lo suficiente como para juzgarlo, escribe un encargo claro, deja que una IA proponga opciones, elige una, y hazla explicar cada truco que usó. Terminarás con software que funciona y con el entendimiento para mantenerlo. Eso es aprender haciendo, con un compañero de laboratorio bien paciente.