Rigrem Arcade empezó con una pregunta: ¿qué tanto le puedo meter a un mapa de DDNet si también cambio el server? La respuesta fue: bastante.
Aquí cuento cómo funciona por dentro. No es un tutorial para copiar y pegar, es para compartir las ideas: si haces mapas, programas o nada más te da curiosidad qué hay detrás de un tee que te bloquea, esto es para ti.
Portales que se prenden
DDNet ya trae teletransportes: tocas un bloque de entrada con un número y apareces en la salida con el mismo número. Es instantáneo, y en un lobby eso es un problema: vas caminando, rozas un portal y de repente estás en otro lado.
Por eso hice los portales del lobby como charcos de luz en el piso. Puedes caminar encima sin que pase nada. Para entrar te quedas quieto un segundo, y mientras tanto se prende un aro de bolitas alrededor de tus pies, una por una. Cuando se llena, te vas.
En el mapa, un charco no es un teletransporte: es solo un dibujo y una marca invisible. El que hace el trabajo es el server. En cada tick (50 por segundo) revisa quién está sobre un charco y si se está moviendo:
bool quieto = abs(vel.x) < 0.5 && abs(vel.y) < 0.5;
if(sobreCharco && quieto)
progreso++;
else
progreso = 0; // caminar o brincar lo cancela
if(progreso == 50) // un segundo
Teletransportar(jugador, destinoDelCharco);
Las bolitas del aro las dibujo mandando al juego rayos láser de un solo punto. Ahí me topé con un detalle curioso: si las repartía por ángulo alrededor de la elipse, se amontonaban en los lados, porque la elipse está acostada.
La solución fue medir el largo del contorno y repartirlas por distancia, no por ángulo:
// recorre la elipse en pasitos y acumula lo que va midiendo
for(int k = 1; k <= PASOS; k++)
largo[k] = largo[k - 1] + distance(punto(k - 1), punto(k));
// la bolita i va donde se cumple su fracción del largo total
for(int i = 0; i < BOLITAS; i++)
aro[i] = puntoEnLargo(largo[PASOS] * i / BOLITAS);
Un último detalle: el server recuerda por qué charco te fuiste. Cuando regresas al lobby apareces en ese mismo charco, no en el spawn, así no se siente que te teletransportaron a un lugar al azar.
Retar con un golpe
En la sala del 1v1 no hay menús ni comandos para retar a alguien: le pegas con el martillo. Si te regresa el golpe en los siguientes 10 segundos, el reto está aceptado y los dos se van a una salita aparte.
- Le pegascon el martillo
- Te la regresaen menos de 10 s
- Escogen modolos dos en el mismo cuadro
- Escogen arenay a pelear
Lo quise así porque es como se reta a alguien en la vida real, y porque se entiende sin leer nada. Por dentro es una pequeña máquina de estados: cada golpe se compara con el último golpe que recibió el que pega.
void AlPegar(int yo, int otro)
{
if(reto[otro].a == yo && ahora - reto[otro].cuando < 10 * 50)
EmpezarDuelo(otro, yo); // me había retado y le contesté
else
reto[yo] = {otro, ahora}; // lo reto yo; ahora le toca a él
}
En la salita repetí la idea: nadie elige solo. Para escoger el modo, los dos se paran en el mismo cuadro, RANKED o AMISTOSO, y tras tres segundos queda. Después, igual con la arena. Así nadie te puede obligar a jugar por puntos, y si en un minuto no se ponen de acuerdo, se cancela.
Las reglas del ranked las pensé para que no se pueda hacer trampa fácil:
- Desde la misma conexión (con un dummy, por ejemplo) solo se puede jugar amistoso.
- Contra el mismo rival solo cuentan unas cuantas victorias al día.
- Salirse a media pelea cuenta como perder.
- El que gana le quita el título de campeón al otro, si lo tenía.
Una ronda se gana igual que en los duelos contra bots: el otro tiene que quedarse congelado y sin moverse dos segundos. Ese “sin moverse” importa, porque deja salvar una jugada con un buen truco aunque ya estés congelado.
El Coliseo
El Coliseo es un torneo de eliminación directa que se organiza solo. Nadie tiene que ser admin ni escribir comandos: el server lleva las inscripciones, arma el bracket, llama a cada pelea y entrega los premios.
- Inscripción. Entras por el charco del Coliseo y esperas en la sala de gladiadores, abajo de la arena.
- Cuenta regresiva. Con 4 inscritos empieza un minuto de espera para que lleguen más. Caben hasta 16.
- El bracket. Se arma de 4, 8 o 16 lugares. El campeón vigente va primero, luego los que tienen más trofeos y medallas; los empates se sortean. Si faltan jugadores para llenar el bracket, los mejor sembrados pasan directo a la siguiente ronda.
- Las peleas. Una a la vez en la arena, con las reglas del 1v1: gana el primero en llegar a 3 bloqueos, y la final es a 5. Los demás miran desde las gradas.
- El premio. El campeón se lleva trofeos (más si encadena torneos), una skin dorada que va cambiando de tono, su estatua en el palco y el título de campeón vigente hasta el siguiente torneo. El subcampeón se lleva una medalla.
Para el orden de las peleas usé la siembra clásica de los torneos de tenis: el tamaño es la siguiente potencia de dos, y cada jugador va contra su “espejo”. Así el 1 y el 2 solo se pueden topar en la final, y los huecos vacíos caen justo enfrente de los mejores:
vector<int> orden = {1};
while(orden.size() < tam) {
int m = orden.size() * 2;
vector<int> nuevo;
for(int s : orden) {
nuevo.push_back(s);
nuevo.push_back(m + 1 - s); // su espejo
}
orden = nuevo;
}
// con 8 lugares: 1-8, 4-5, 2-7, 3-6
// si solo hay 7 inscritos, el 1 pasa directo
El corazón de los bots
Esta es la parte de la que estoy más orgulloso. Escald, Rigrem y Chalequex no son grabaciones ni siguen un camino fijo: en cada momento deciden qué hacer. Y no usan redes neuronales ni nada parecido. Su secreto es más sencillo y más bonito: se imaginan el futuro antes de moverse.
Un jugador más
Para el juego, un bot es un jugador sin pantalla. 50 veces por segundo el server le pregunta lo mismo que le pregunta a tu juego: hacia dónde caminas, si brincas, si lanzas el hook, hacia dónde apuntas y si disparas. Lo único distinto es que la respuesta no viene de un teclado, viene de su cerebro. Por eso los bots no pueden hacer nada que tú no puedas hacer.
Imaginar: el simulador
Toda la física de un tee en DDNet vive en una pieza chiquita del código, el core: posición, velocidad, el hook y los saltos. En cada tick el juego hace dos cosas: Tick() lee las teclas y calcula fuerzas (gravedad, el jalón del hook, el salto), y Move() mueve al tee chocando con las paredes.
Lo importante es que esa física es determinista: si empiezas igual y aprietas las mismas teclas, pasa exactamente lo mismo, siempre. Eso es lo que hace posible imaginar. El bot toma una “foto” de los tees que tiene cerca, los copia a un mundo privado y corre ahí los ticks que quiera, sin que la partida real se entere.
// una copia de los dos; la partida real no se entera
CCharacterCore yo = *bot->Core();
CCharacterCore el = *rival->Core();
yo.SetCoreWorld(&mundoPrivado, colision, equipos);
el.SetCoreWorld(&mundoPrivado, colision, equipos);
for(int t = 0; t < 75; t++) { // un segundo y medio
yo.m_Input = TeclasDelPlan(plan, t);
el.m_Input = {}; // supongo que él suelta todo
yo.Tick(true); el.Tick(true);
yo.Move(); el.Move();
yo.Quantize(); el.Quantize();
if(EnFreeze(yo)) return Fallo();
if(EnFreeze(el)) return Exito(t); // en el tick t lo tiro
}
return NadaPaso();
Ese ciclo es todo el truco. Lo demás es decidir qué teclas probar y no engañarse con lo que sale.
El plan
Cada idea que el bot prueba es un plan: unas cuantas decisiones que se convierten en teclas tick por tick.
struct Plan {
int dir; // -1 izquierda, 0 nada, 1 derecha
int ticksActivos; // después de esto suelta todo
int salto; // 0 no, 1 ya, 2 cuando vaya bajando
bool hook;
vec2 hookDir;
int hookSoltar; // tick en que lo suelta
int dirDespues; // hacia dónde se deja caer
};
Tiene una parte activa y una pasiva (suelta todo y se deja caer), porque lo que importa no es dónde está a la mitad, sino dónde termina. Convertir el plan en teclas parece trivial, y aquí estuvo la primera trampa:
Input TeclasDelPlan(const Plan &p, int t, const Core &yo)
{
Input in = {};
bool activo = t < p.ticksActivos;
in.direction = activo ? p.dir : p.dirDespues;
in.target = p.hookDir * 200;
// el salto cuenta al apretar, no al tener apretado:
// si el botón viene presionado, primero hay que soltarlo
bool botonLibre = !(yo.jumped & 1);
if(p.salto == 1)
in.jump = t <= 3 && botonLibre;
else if(p.salto == 2) // doble salto ya cayendo: así llega más alto
in.jump = activo && botonLibre && yo.vel.y > 0 && !(yo.jumped & 2);
in.hook = p.hook && t < p.hookSoltar;
return in;
}
Sin esa revisión del botón, el doble salto nunca sale en la simulación: el botón se queda apretado desde el primer brinco y el juego no cuenta el segundo.
Que lo imaginado sea lo real
La simulación solo sirve si coincide con lo que de verdad va a pasar. Estas fueron las diferencias que tuve que cazar.
El martillo no vive en el core. El juego aplica el golpe por fuera, justo entre Tick() y Move(). Si no lo reproduces en ese mismo punto, el bot planea martillazos que en la vida real no mueven a nadie.
yo.Tick(true); el.Tick(true);
// el golpe va aquí, entre Tick y Move, como en el juego
if(t == plan.martillo && AlAlcance(yo, el))
el.m_Vel += vec2(0, -1) + normalize(haciaEl + vec2(0, -1.1)) * 10;
yo.Move(); el.Move();
Un tee rápido atraviesa el freeze. Entre un tick y otro un tee puede avanzar más que una línea delgada de freeze, así que reviso también el punto medio del camino.
vec2 antes = yo.m_Pos;
yo.Move();
if(EsFreeze(yo.m_Pos) || EsFreeze((antes + yo.m_Pos) / 2))
return Fallo();
Quantize() no es opcional. El server redondea posiciones y velocidades en cada tick para poder mandarlas por internet. Sin ese redondeo, la simulación se va separando de la realidad poquito a poquito, y al rato el bot ya está imaginando otro partido.
Ganar no basta. Cuando el rival cae al freeze, la simulación sigue 30 ticks más. Una jugada donde el bot se cae detrás de su víctima no es buena jugada.
Imaginar cuesta. Cada tick simulado es trabajo para el server, así que la foto solo incluye a los tees que están cerca y que pueden chocar con el bot (los de otros duelos van en otro equipo y no cuentan), y cada simulación tiene un límite: un segundo y medio para un ataque, 2.2 segundos para el filtro de seguridad.
Un Google Maps para tees
Con el simulador, el bot se aprende el terreno al cargar el mapa. Desde cada lugar donde un tee se puede parar, prueba muchos movimientos: caminar, brincar, doble salto, columpiarse con el hook. Si uno lo lleva a otro lugar sin tocar freeze, lo anota como un camino. Al final tiene un mapa de rutas, y para ir a cualquier parte busca el camino más corto en tiempo.
Esto cuesta mucho cálculo, así que se construye poco a poco, con un límite de ticks simulados en cada tick real, para que el server no se trabe. Y el mapa de rutas no se queda fijo: también crece con lo que hacen ustedes, como explico más abajo en las grabaciones.
Buscar la jugada
Cuando tiene a alguien cerca, el bot busca una jugada unas seis veces por segundo. Arma una lista de ideas (jalones con el hook de distintas duraciones, columpios, brincar y enganchar en el aire, martillazos solos o seguidos de un jalón), las corre todas en el simulador con los dos tees y les pone calificación:
for(Plan p : IdeasPara(yo, rival)) {
Resultado r = Simular(p, yo, rival);
if(!r.rivalCongelado || r.yoCongelado)
continue;
float puntos = 1000 - r.ticksHastaFreeze * 4; // entre más rápido, mejor
puntos += Estilo(r.dondeCae); // la T, una copa o el hoyo valen más
puntos += Azar(0, 40); // para no ser predecible
buenas.push_back({p, puntos});
}
De las mejores, todavía descarta dos tipos: las que solo salen si adivina lo que vas a hacer (tienen que funcionar aunque sueltes todo) y las que te dejan engancharlo a medio camino y voltearle la jugada. Ya escogida, la sigue tick por tick mientras el simulador diga que todavía sale.
Las grabaciones: aprender de ustedes
Un bot que solo usa sus propias ideas se vuelve predecible. Por eso el server tiene una grabadora: mientras alguien juega, apunta tick por tick cómo se mueve cada tee. No graba el chat ni nada fuera del mapa; solo movimiento, como una repetición.
Es un archivo de texto por sesión. Se abre cuando entra el primer jugador y se cierra unos segundos después de que sale el último. Cada renglón es un tee en un tick:
# tick,id,x,y,vx,vy,dir,tx,ty,salto,hook,dispara,arma,hookestado,hookx,hooky,enganchado,congelado,piso
81520,3,4416,1630,512,-1280,1,200,-140,1,0,0,0,0,0,0,-1,0,0
81521,3,4418,1625,512,-1152,1,200,-140,1,1,0,0,1,4610,1460,-1,0,0
Posición, velocidad, las teclas (dirección, salto, hook, disparo, arma), dónde va el hook y a quién tiene enganchado, si está congelado y si pisa el suelo. Arriba del archivo se anota quién es cada id. Se graban los jugadores y los bots que tengan cerca, y si un tee está igual que en el tick anterior (parado sin hacer nada) no se repite el renglón: al leerlo, lo que falta significa “sigue igual”.
De ahí los bots sacan dos cosas:
Rutas
Busco los tramos donde un jugador estaba quieto en un lugar y terminó quieto en otro sin congelarse. Cada tramo es un camino posible. El bot lo prueba en su simulador y, si le sale, lo agrega a su mapa de rutas. Así aprende atajos que nunca se le hubieran ocurrido.
Jugadas
Busco el instante exacto en que alguien se congeló y miro hacia atrás: ¿quién lo enganchó o le pegó con el martillo en el segundo anterior? Si fue un jugador de verdad (los bots no enseñan nada) y él no se congeló en el medio segundo siguiente, cuenta como buena jugada.
De cada jugada guardo la situación del principio y las teclas que apretó:
struct Situacion {
vec2 rel; // dónde estaba la víctima respecto a él
vec2 velYo, velVic;
bool pisoYo, pisoVic;
};
// + las teclas tick por tick, desde un poco antes del hook o el martillazo
En pleno duelo, el bot compara su situación con las guardadas. La diferencia se mide en bloques de distancia, más un poco por las velocidades, más un castigo si uno estaba en el piso y el otro no:
float Diferencia(Situacion a, Situacion b, bool espejo)
{
if(espejo) // una jugada a la derecha también sirve a la izquierda
b = Voltear(b);
float d = distance(a.rel, b.rel) / BLOQUE;
d += 0.12 * (distance(a.velYo, b.velYo) + distance(a.velVic, b.velVic));
d += (a.pisoYo != b.pisoYo ? 1.5 : 0) + (a.pisoVic != b.pisoVic ? 1.0 : 0);
return d;
}
Las más parecidas entran a la lista de ideas junto con las suyas y pasan por el mismo simulador: si en esta situación no salen, se descartan. El truco del espejo duplica gratis todo lo aprendido. Los rivales de en medio solo las usan la mitad de las veces, para que la dificultad no se dispare.
El ángel de la guarda
Antes de mandar sus teclas al juego, cada bot pasa por un filtro de seguridad. El filtro se imagina los siguientes 2.2 segundos; si esas teclas lo llevan al freeze sin remedio, las cambia por el plan seguro que más se parezca a lo que quería hacer. Así el cerebro puede ser agresivo sin suicidarse.
Personalidad
Los tres rivales usan el mismo cerebro. Lo que cambia es el tiempo de reacción:
| Rival | Tarda en atacar | Tarda en defenderse |
|---|---|---|
| Escald | 9 ticks (casi 0.2 s) | 10 ticks, y no sabe salvarse con el hook |
| Rigrem | 4 ticks | 4 ticks |
| Chalequex | al instante | al instante |
Y tienen memoria. Si los jalas en el aire, se acuerdan de ti y juegan con más cuidado el resto del duelo. Si intentas meterlos al hoyo, prefieren las jugadas que te meten a ti. Y cuando te ganan se burlan, pero en susurro, para no llenar el chat.
Una confesión para cerrar este cuarto: la cinemática secreta, cuando Chalequex y Caleco se llevan volando al ganador, no es física de verdad. Esa la mueve el server a mano, como una coreografía, porque ahí no quería que nada pudiera fallar.
Para terminar
Si algo de esto te dejó pensando, la mejor forma de aprender es la que usé yo: abrir el código de DDNet, cambiar una cosa pequeña y ver qué pasa. El juego y el server están en github.com/ddnet/ddnet, y la comunidad de ddnet.org lleva años haciendo mapas y mods increíbles.
Y si nada más quieres ver todo esto en acción, entra al Arcade e intenta ganarle a Chalequex. Ahora ya sabes que se está imaginando tu próximo movimiento.
Rigrem Arcade started with a question: how much can I fit into a DDNet map if I also change the server? The answer turned out to be: a lot.
This is how it works inside. It's not a copy-and-paste tutorial, it's about sharing the ideas: if you make maps, write code, or you're just curious about what's behind a tee that keeps blocking you, this is for you.
Portals that light up
DDNet already has teleporters: you touch an entrance tile with a number and you show up at the exit with the same number. It's instant, and in a lobby that's a problem: you're walking around, you brush a portal and suddenly you're somewhere else.
So I made the lobby portals pools of light on the floor. You can walk over them and nothing happens. To go in, you stand still for a second, and a ring of dots lights up around your feet, one by one. When it's full, you're gone.
In the map, a pool isn't a teleporter: it's just a drawing and an invisible marker. The server does the work. Every tick (50 per second) it checks who is standing on a pool and whether they're moving:
bool still = abs(vel.x) < 0.5 && abs(vel.y) < 0.5;
if(onPool && still)
progress++;
else
progress = 0; // walking or jumping cancels it
if(progress == 50) // one second
Teleport(player, poolDestination);
I draw the dots of the ring by sending the game tiny one-point laser beams. That's where I hit a funny detail: if I spread them by angle around the ellipse, they bunched up on the sides, because the ellipse is lying down.
The fix was to measure the length of the outline and spread them by distance, not by angle:
// walk the ellipse in tiny steps and add up the length
for(int k = 1; k <= STEPS; k++)
length[k] = length[k - 1] + distance(point(k - 1), point(k));
// dot i goes where its share of the total length is reached
for(int i = 0; i < DOTS; i++)
ring[i] = pointAtLength(length[STEPS] * i / DOTS);
One last detail: the server remembers which pool you left through. When you come back to the lobby you land on that same pool, not at the spawn, so it doesn't feel like you got teleported somewhere random.
Challenge with a hit
In the 1v1 room there are no menus or commands to challenge someone: you hit them with the hammer. If they hit you back within 10 seconds, the challenge is accepted and you both go to a separate little room.
- You hit themwith the hammer
- They hit backwithin 10 s
- Pick a modeboth on the same pad
- Pick an arenaand fight
I wanted it this way because that's how you challenge someone in real life, and because you get it without reading anything. Inside, it's a tiny state machine: every hit is compared with the last hit the attacker received.
void OnHit(int me, int other)
{
if(challenge[other].to == me && now - challenge[other].when < 10 * 50)
StartDuel(other, me); // they challenged me and I answered
else
challenge[me] = {other, now}; // I challenge them; their turn now
}
In the little room I repeated the idea: nobody picks alone. To choose the mode, both players stand on the same pad, RANKED or AMISTOSO (friendly), and after three seconds it's set. Then the same for the arena. That way nobody can force you to play for points, and if you can't agree within a minute, it's cancelled.
I designed the ranked rules so cheating isn't easy:
- From the same connection (with a dummy, for example) you can only play friendly.
- Against the same opponent, only a few wins a day count.
- Leaving mid-fight counts as a loss.
- The winner takes the other player's champion title, if they had it.
A round is won the same way as in the bot duels: the other player has to stay frozen and not moving for two seconds. That "not moving" matters, because it lets you save a play with a good trick even when you're already frozen.
The Colosseum
The Colosseum is a single-elimination tournament that runs itself. Nobody needs to be an admin or type commands: the server handles sign-ups, builds the bracket, calls each fight and hands out the prizes.
- Sign-up. You enter through the Colosseum pool and wait in the gladiators' room, under the arena.
- Countdown. With 4 players signed up, a one-minute wait starts so more can join. Up to 16 fit.
- The bracket. It's built for 4, 8 or 16 spots. The reigning champion goes first, then whoever has more trophies and medals; ties are drawn at random. If there aren't enough players to fill the bracket, the top seeds get a bye to the next round.
- The fights. One at a time in the arena, with the 1v1 rules: first to 3 blocks wins, and the final is to 5. Everyone else watches from the stands.
- The prize. The champion gets trophies (more for winning in a row), a golden skin that keeps shifting color, a statue in the box of honor and the reigning champion title until the next tournament. The runner-up gets a medal.
For the order of the fights I used classic tennis seeding: the size is the next power of two, and each player faces their "mirror". That way 1 and 2 can only meet in the final, and the empty spots land right in front of the best players:
vector<int> order = {1};
while(order.size() < size) {
int m = order.size() * 2;
vector<int> next;
for(int s : order) {
next.push_back(s);
next.push_back(m + 1 - s); // their mirror
}
order = next;
}
// with 8 spots: 1-8, 4-5, 2-7, 3-6
// with only 7 players, 1 gets a bye
The heart of the bots
This is the part I'm proudest of. Escald, Rigrem and Chalequex aren't recordings and they don't follow a fixed path: they decide what to do every moment. And they don't use neural networks or anything like that. Their secret is simpler and nicer: they imagine the future before they move.
Just another player
To the game, a bot is a player without a screen. 50 times per second the server asks it the same thing it asks your game: which way you walk, whether you jump, whether you throw the hook, where you aim and whether you fire. The only difference is that the answer doesn't come from a keyboard, it comes from its brain. That's why the bots can't do anything you can't do.
Imagining: the simulator
All the physics of a tee in DDNet lives in a tiny piece of the code, the core: position, velocity, the hook and the jumps. Every tick the game does two things: Tick() reads the keys and works out the forces (gravity, the hook's pull, the jump), and Move() moves the tee, bumping into walls.
The key part is that this physics is deterministic: if you start the same and press the same keys, exactly the same thing happens, every time. That's what makes imagining possible. The bot takes a "snapshot" of the tees nearby, copies them into a private world and runs as many ticks as it wants there, without the real game noticing.
// a copy of both; the real game never notices
CCharacterCore me = *bot->Core();
CCharacterCore him = *rival->Core();
me.SetCoreWorld(&privateWorld, collision, teams);
him.SetCoreWorld(&privateWorld, collision, teams);
for(int t = 0; t < 75; t++) { // a second and a half
me.m_Input = KeysForPlan(plan, t);
him.m_Input = {}; // assume he lets go of everything
me.Tick(true); him.Tick(true);
me.Move(); him.Move();
me.Quantize(); him.Quantize();
if(InFreeze(me)) return Fail();
if(InFreeze(him)) return Success(t); // I knock him out at tick t
}
return NothingHappened();
That loop is the whole trick. The rest is deciding which keys to try and not fooling yourself with what comes out.
The plan
Each idea the bot tries is a plan: a few decisions that turn into keys, tick by tick.
struct Plan {
int dir; // -1 left, 0 nothing, 1 right
int activeTicks; // after this it lets go of everything
int jump; // 0 no, 1 now, 2 on the way down
bool hook;
vec2 hookDir;
int hookRelease; // tick when it lets go
int dirAfter; // which way it drifts while falling
};
It has an active part and a passive part (it lets go and falls), because what matters isn't where it is halfway, but where it ends up. Turning a plan into keys looks trivial, and that's where the first trap was:
Input KeysForPlan(const Plan &p, int t, const Core &me)
{
Input in = {};
bool active = t < p.activeTicks;
in.direction = active ? p.dir : p.dirAfter;
in.target = p.hookDir * 200;
// a jump counts on press, not while held:
// if the button is already down, it has to be released first
bool buttonFree = !(me.jumped & 1);
if(p.jump == 1)
in.jump = t <= 3 && buttonFree;
else if(p.jump == 2) // double jump while falling: it gets higher
in.jump = active && buttonFree && me.vel.y > 0 && !(me.jumped & 2);
in.hook = p.hook && t < p.hookRelease;
return in;
}
Without that button check, the double jump never happens in the simulation: the button stays down from the first jump and the game doesn't count the second one.
Making the imagined match the real
The simulation is only useful if it matches what's really going to happen. These are the differences I had to hunt down.
The hammer doesn't live in the core. The game applies the hit from outside, right between Tick() and Move(). If you don't reproduce it at that exact point, the bot plans hammer hits that don't move anyone in real life.
me.Tick(true); him.Tick(true);
// the hit goes here, between Tick and Move, like in the game
if(t == plan.hammer && InReach(me, him))
him.m_Vel += vec2(0, -1) + normalize(towardHim + vec2(0, -1.1)) * 10;
me.Move(); him.Move();
A fast tee goes through freeze. Between one tick and the next a tee can travel farther than a thin line of freeze, so I also check the midpoint of the path.
vec2 before = me.m_Pos;
me.Move();
if(IsFreeze(me.m_Pos) || IsFreeze((before + me.m_Pos) / 2))
return Fail();
Quantize() isn't optional. The server rounds positions and velocities every tick so it can send them over the internet. Without that rounding, the simulation slowly drifts away from reality, and after a while the bot is imagining a different match.
Winning isn't enough. When the rival falls into freeze, the simulation keeps going for 30 more ticks. A play where the bot falls in right behind its victim isn't a good play.
Imagining costs. Every simulated tick is work for the server, so the snapshot only includes tees that are nearby and can collide with the bot (players in other duels are on another team and don't count), and every simulation has a limit: a second and a half for an attack, 2.2 seconds for the safety filter.
A Google Maps for tees
With the simulator, the bot learns the terrain when the map loads. From every spot where a tee can stand, it tries lots of moves: walking, jumping, double jump, swinging on the hook. If one takes it to another spot without touching freeze, it writes it down as a path. In the end it has a route map, and to get anywhere it looks for the fastest path.
That's a lot of computing, so it's built little by little, with a limit of simulated ticks per real tick, so the server doesn't lag. And the route map isn't fixed: it also grows with what you all do, as I explain below in the recordings.
Finding the play
When someone is close, the bot looks for a play about six times per second. It makes a list of ideas (hook pulls of different lengths, swings, jumping and hooking in the air, hammer hits alone or followed by a pull), runs them all in the simulator with both tees and scores them:
for(Plan p : IdeasFor(me, rival)) {
Result r = Simulate(p, me, rival);
if(!r.rivalFrozen || r.meFrozen)
continue;
float points = 1000 - r.ticksToFreeze * 4; // the faster, the better
points += Style(r.whereHeLands); // the T, a cup or the pit are worth more
points += Random(0, 40); // so it's not predictable
good.push_back({p, points});
}
From the best ones, it still throws out two kinds: the ones that only work if it guesses what you'll do (they have to work even if you let go of everything), and the ones that let you hook it halfway and turn the play around. Once it picks one, it follows it tick by tick as long as the simulator says it still works.
The recordings: learning from you
A bot that only uses its own ideas gets predictable. That's why the server has a recorder: while someone plays, it writes down, tick by tick, how every tee moves. It doesn't record chat or anything outside the map; just movement, like a replay.
It's one text file per session. It opens when the first player joins and closes a few seconds after the last one leaves. Each line is one tee in one tick:
# tick,id,x,y,vx,vy,dir,tx,ty,jump,hook,fire,weapon,hookstate,hookx,hooky,hooked,frozen,ground
81520,3,4416,1630,512,-1280,1,200,-140,1,0,0,0,0,0,0,-1,0,0
81521,3,4418,1625,512,-1152,1,200,-140,1,1,0,0,1,4610,1460,-1,0,0
Position, velocity, the keys (direction, jump, hook, fire, weapon), where the hook is and who it's holding, whether it's frozen and whether it's on the ground. At the top of the file it notes who each id is. Players are recorded, plus any bots near them, and if a tee is the same as on the previous tick (standing still doing nothing) the line isn't repeated: when reading it back, a missing line means "still the same".
From there, the bots get two things:
Routes
I look for stretches where a player was standing still in one place and ended up still in another without freezing. Each stretch is a possible path. The bot tries it in its simulator and, if it works, adds it to its route map. That's how it learns shortcuts it would never have come up with.
Plays
I look for the exact moment someone froze and look back: who hooked them or hit them with the hammer in the second before? If it was a real player (bots don't teach anything) and they didn't freeze in the next half second, it counts as a good play.
For each play I save the starting situation and the keys they pressed:
struct Situation {
vec2 rel; // where the victim was, relative to him
vec2 velMe, velVic;
bool groundMe, groundVic;
};
// + the keys tick by tick, from just before the hook or the hammer hit
Mid-duel, the bot compares its situation with the saved ones. The difference is measured in blocks of distance, plus a bit for the velocities, plus a penalty if one was on the ground and the other wasn't:
float Difference(Situation a, Situation b, bool mirror)
{
if(mirror) // a play to the right also works to the left
b = Flip(b);
float d = distance(a.rel, b.rel) / BLOCK;
d += 0.12 * (distance(a.velMe, b.velMe) + distance(a.velVic, b.velVic));
d += (a.groundMe != b.groundMe ? 1.5 : 0) + (a.groundVic != b.groundVic ? 1.0 : 0);
return d;
}
The closest ones join its list of ideas next to its own and go through the same simulator: if they don't work in this situation, they're dropped. The mirror trick doubles everything learned for free. The middle rivals only use them half the time, so the difficulty doesn't spike.
The guardian angel
Before sending its keys to the game, every bot goes through a safety filter. The filter imagines the next 2.2 seconds; if those keys would take it into freeze with no way out, it swaps them for the safe plan that's closest to what it wanted to do. That way the brain can be aggressive without being suicidal.
Personality
The three rivals use the same brain. What changes is their reaction time:
| Rival | Attack delay | Defense delay |
|---|---|---|
| Escald | 9 ticks (almost 0.2 s) | 10 ticks, and can't save himself with the hook |
| Rigrem | 4 ticks | 4 ticks |
| Chalequex | instant | instant |
And they have memory. If you pull them in the air, they remember you and play more carefully for the rest of the duel. If you try to push them into the pit, they prefer the plays that push you in. And when they beat you they tease you, but in a whisper, so the chat doesn't fill up.
A confession to close this room: the secret cutscene, when Chalequex and Caleco fly the winner away, isn't real physics. The server moves that one by hand, like choreography, because there I didn't want anything to go wrong.
Wrapping up
If any of this got you thinking, the best way to learn is the one I used: open DDNet's code, change one small thing and see what happens. The game and the server are at github.com/ddnet/ddnet, and the ddnet.org community has been making amazing maps and mods for years.
And if you just want to see all this in action, join the Arcade and try to beat Chalequex. Now you know he's imagining your next move.