Как устроены классические игры: от Sopwith до Wolfenstein 3D
Академия Starbound · Мастерская Архимеда · Класс 4 · Около 25 минут
Как игры показывали самолёты, гонки и трёхмерные лабиринты на компьютерах той эпохи — советских ПК «Истра-4816», «Искра-1030М» и ЕС-1840/1841 с 16-разрядным процессором и 640 КБ памяти? Без видеокарты с 3D-ускорением, без чисел с плавающей точкой и почти без памяти. Ответ — в нескольких приёмах, которые работают до сих пор: игровой цикл, спрайты, арифметика с фиксированной точкой и рейкастинг. Я перепроверила каждую дату и каждое имя по двум независимым источникам; номера в квадратных скобках ведут к списку в конце.
1. Компьютеры эпохи и игры, о которых пойдёт речь
Речь о персональных компьютерах (ПК) эпохи (IBM PC/XT, Intel 8088, CGA). Процессор Intel 8088 вышел в 1979 году; в IBM PC и IBM PC XT он работал на частоте 4,77 МГц[29, 28]. IBM PC XT появился 8 марта 1983 года; гнездо под математический сопроцессор 8087 в нём было, но сам сопроцессор покупали отдельно[28]. CGA (Color Graphics Adapter, цветной графический адаптер) появился в 1981 году: 16 КБ видеопамяти и режим 320×200 всего в 4 цветах из фиксированных палитр[27, 22].
Такие же IBM PC/XT-совместимые машины выпускали и в СССР; все они построены на процессоре К1810ВМ86, советском аналоге Intel 8086. Там, где источники расходятся, мы приводим оба значения.
Машина
Процессор
Тактовая частота
ОЗУ
«Истра-4816»
К1810ВМ86 + два КР580ВМ80А (аналог Intel 8080)[55, 57]
в найденных источниках не указана
512 КБ – 1 МБ[57]; 1–4 МБ по данным разработчиков[56], общая для всех процессоров
Рейкастинг, VGA в 256 цветах; нужен процессор 286, рассчитана на 386[14, 15, 21]
2. Игровой цикл: ввод, обновление, отрисовка, время
🚀 Стартовая площадка
Любая игра, от «Марсиан» до Wolfenstein 3D, — это один и тот же цикл, который крутится много раз в секунду. Похоже на мультфильм в блокноте: на каждой странице герой чуть сдвинулся, а быстрое перелистывание даёт движение[25].
Псевдокод
пока игра идёт:
прочитать клавиши # ВВОД
сдвинуть всё на шаг # ОБНОВЛЕНИЕ (правила, столкновения, очки)
нарисовать кадр # ОТРИСОВКА
подождать до конца кадра # ВРЕМЯ: одна и та же скорость на любом компьютере
Почему важно время. Ранние программы часто считали время по скорости процессора. На более быстрых компьютерах такие игры шли слишком быстро и становились неиграбельными, поэтому на корпусах появилась кнопка Turbo: её выключали, чтобы замедлить машину для старых игр[31, 25]. Правильное решение — измерять реальное время и двигать объекты на столько, сколько его прошло[26].
Настоящий пример: Wolfenstein 3D. В опубликованном исходном коде id Software функция PlayLoop делает ровно эти шаги. Таймер тикает 70 раз в секунду (TickBase 70), функция CalcTics считает, сколько тиков прошло с прошлого кадра, и всё движение умножается на это число. На медленном компьютере кадров меньше, но враги бегут с той же скоростью[18, 19, 20, 21].
C · Wolfenstein 3D (сокращено)
/* Wolfenstein 3D, id Software, 1992 (released source, 1995) */
typedef long fixed; /* WL_DEF.H: 32-bit number, 16.16 fixed point */
#define GLOBAL1 (1l<<16) /* WL_DEF.H: 1.0 = 65536 = one map tile */
#define MAPSIZE 64 /* WL_DEF.H: the map is a 64 x 64 grid */
#define TickBase 70 /* ID_SD.H: the timer ticks 70 times a second */
/* WL_PLAY.C, PlayLoop (simplified order of calls): */
CalcTics (); /* how many 1/70 s ticks passed since the last frame */
PollControls (); /* input */
MoveDoors (); /* ... DoActor() for every enemy ... */ /* update */
ThreeDRefresh (); /* render: cast the rays, draw walls and sprites */
3. Как игры 80-х и 90-х обманывали физику
🛰️ Орбита
3.1 Четыре цвета CGA
В режиме 320×200 CGA показывал только 4 цвета, причём не любые: одна палитра — зелёный, красный, коричневый, другая — голубой, пурпурный, белый, плюс цвет фона[27, 22]. Художники рисовали так, чтобы глаз сам «досчитывал» детали.
3.2 Спрайты
Спрайт — небольшая картинка, которую программа рисует поверх фона и двигает целиком[32]. Grand Prix Circuit строил гонку от первого лица из спрайтов, а не из полигонов[4, 5]. Даже враги в Wolfenstein 3D — плоские спрайты, которые просто масштабируются с расстоянием[14, 21].
3.3 Фиксированная точка вместо плавающей
У 8088 и у 386 без сопроцессора не было FPU (floating-point unit, блока операций с плавающей точкой), а программная эмуляция была слишком медленной. Поэтому дробные числа хранили как целые: младшие 16 бит — дробная часть, старшие — целая. Это и есть фиксированная точка 16.16[30, 21]. В Wolfenstein 3D так записаны координаты игрока: typedef long fixed;, а единица равна 1<<16[17, 21].
Карта Wolfenstein 3D — сетка 64×64 клетки[17]. Для каждого столбца экрана (их 320) программа выпускает один луч и шагает по клеткам сетки, пока не упрётся в стену. Такой пошаговый обход называют DDA (digital differential analyzer, цифровой дифференциальный анализатор). Чем дальше стена, тем ниже её столбик на экране. Чтобы стены не выгибались, как в «рыбьем глазе», расстояние умножают на косинус угла между лучом и направлением взгляда[24, 23, 33]. Wolfenstein 3D вышла 5 мая 1992 года (id Software, издатель Apogee): код написан на языке C по стандарту ANSI (American National Standards Institute, Американский национальный институт стандартов), а самые горячие места — рейкастинг и масштабирование — на ассемблере; картинка — VGA (Video Graphics Array) 320×200 в 256 цветах[14, 21, 15]. В 1995 году id Software опубликовала исходный код[14, 16].
4. «Марсиане»: разбор кода
🪐 База на Марсе
Теперь сыграем. «Марсиане» — терминальная игра: сверху падают нули, внизу их ловит каретка. Поймали — +10 очков, пропустили — минус жизнь и экран на мгновение инвертируется; жизней три. Ниже — версия для браузера: логическое разрешение 320×200, чёрно-белая графика, клавиши ← → или A/D, R — заново, Q — пауза; на телефоне есть кнопки. А ниже — как её сделали вместе человек и ИИ (искусственный интеллект).
Бережный ремейк первой игры основателя, восстановленный по его описанию. Оригинальный код скоро появится.Открыть на весь экран →Оригинал в терминале: видео без звука. Записано на исходной системе: изолированный от сети ноутбук HP 255 G10 (AMD Ryzen 5 7530U, 16 ГБ ОЗУ, SSD 512 ГБ) с Omarchy Linux.
4.1 Человек + ИИ: как это было сделано
Игру придумал и довёл до работающей версии основатель Starbound; Grok помогал как инженер: код, отладка, математика. Сам геймплей — идея человека. Время ниже отсчитано от первой просьбы «давай сделаем игру» (минута 0) по меткам сообщений в журнале сессии.
Прошло (ч:мм)
Этап
Кто вёл
Вклад Grok
0:00
Идея: «давай сделаем эту игру»
Основатель
—
0:02
Выбор: bash, как можно короче. Первая версия кода
Основатель + Grok
код
0:05
Вторая, минимальная версия
Grok
код
0:50
Первая версия набрана вручную
Основатель
—
0:57
Первая ошибка найдена: пропущено слово do
Grok
отладка
0:59
Первый запуск: нули мигают, но не падают
Основатель
—
0:59
Версия с падением: +10 очков, 3 жизни, проверка поимки, конец игры
Grok
код
1:03
По просьбе основателя: версия с комментариями
Основатель + Grok
код
1:31
Версия с комментариями набрана
Основатель
—
1:31–1:54
Отладка: синтаксис массивов, пары if/fi, bash -n, set -x. Основатель предложил отладку через echo и попросил set -x
Основатель + Grok
отладка
2:27
Основатель сам нашёл пропущенную скобку «)»
Основатель
—
2:29
Игра запускается: каретка ездит, но ничего не падает
Основатель
—
2:36
Странность клавиш-стрелок решили оставить как особенность игры (решение основателя; Grok объяснил escape-последовательности)
Основатель + Grok
отладка
2:40
В логике падения найдены две опечатки: >= вместо ++ и пропущенное then
Grok
отладка
2:46
Поимка работает, но всё слишком быстро
Основатель
—
2:47
Нули двигаются только каждый 3-й кадр (tick % 3)
Grok
математика
2:58
Работает. Частота появления: RANDOM % 12 == 0, не больше 5 нулей сразу
Основатель + Grok
математика
3:03–3:19
Разбор математики: вероятность ≈ 1/12 и общее правило (x mod n = 0) ∧ (c < m)
Grok
математика
Итого: от первой просьбы до настроенной рабочей версии — 2 ч 58 мин, вместе с разбором математики — 3 ч 19 мин; это 200 сообщений. Перезапуск и инвертирующая вспышка появились позже, уже за пределами этого журнала.
4.2 Код с комментариями
Мы бережно переписали игру в учебную версию: все настройки — в блоке констант наверху, цикл разделён на ввод, обновление и отрисовку, есть проверка размера терминала и аккуратный выход. Нужны только bash и стандартные утилиты tput и stty; сеть не нужна. Скачать martians_v1_commented.sh и запустить: bash martians_v1_commented.sh. Это не исходный файл основателя: его оригинальный код будет опубликован позже.
Сердце игры — обновление. Нули падают только каждый 3-й кадр: каретка остаётся быстрой, а нули падают медленно. Поймали ли ноль, решает одно сравнение: carriage ≤ x < carriage + ширина.
bash · обновление
# 5.3 Zeros fall only every FALL_EVERY-th frame, so the carriage stays quick
# while zeros fall slowly (the fix from the build session: tick % 3).
if (( tick % FALL_EVERY == 0 )); then
local i kept_x=() kept_y=()
for i in "${!zero_x[@]}"; do
local x=${zero_x[i]} y=$(( zero_y[i] + 1 ))
if (( y >= FIELD_H )); then
# Landed. Caught if it is over the carriage: carriage <= x < carriage + width
if (( x >= carriage && x < carriage + CARRIAGE_W )); then
(( score += POINTS ))
else
(( lives-- ))
flash=$FLASH_FRAMES # start the inverted flash
fi
# A landed zero is not kept (this replaces unset + re-pack of the arrays).
else
kept_x+=( "$x" ); kept_y+=( "$y" )
fi
done
zero_x=( "${kept_x[@]}" ); zero_y=( "${kept_y[@]}" )
fi
А вот сам цикл: ввод, обновление, отрисовка и ожидание до конца кадра — как в псевдокоде из раздела 2.
bash · главный цикл
while (( lives > 0 )); do
start=${EPOCHREALTIME/./} # microseconds (bash 5+; empty on bash 4)
read_key # INPUT (waits up to one frame)
[[ $key == quit ]] && exit 0
update # UPDATE
render # RENDER
# WAIT: a key press ends `read` early; sleep the rest of the frame so
# the game runs at the same speed whether or not keys are pressed.
if [[ -n $start ]]; then
now=${EPOCHREALTIME/./}
spent=$(( now - start ))
if (( spent < FRAME_US )); then
sleep "0.$(printf '%06d' $(( FRAME_US - spent )))"
fi
fi
done
Вероятность появления нуля в кадре — около 1/12, потому что RANDOM % 12 == 0 выполняется для одного остатка из двенадцати. В общем виде: (x mod n = 0) ∧ (c < m) — ноль появляется с вероятностью ≈ 1/n, пока на экране меньше m нулей.
Скоро в v2: модель ИИ играет в игру
В v1 играет человек. В следующей версии за клавиатуру сядет модель ИИ.
5. Уголок безопасности
Браузерная версия — одна страница и один файл JavaScript: сам код игры не делает сетевых запросов, ничего не скачивает и не использует внешние шрифты; рекорд хранится только у вас в браузере. В уроке она встроена в «песочницу» (sandbox). Как и весь сайт, эта страница использует аналитику посещений Cloudflare без cookie: она ничего не сохраняет в вашем браузере (документация Cloudflare). Прежде чем запускать любой скрипт из интернета, прочитайте его и проверьте синтаксис без запуска: bash -n файл.sh.
6. Кратко
Игра — это цикл: ввод → обновление → отрисовка → время.
Скорость надо считать по часам, а не по процессору.
Спрайты, 4 цвета CGA и фиксированная точка позволяли обходиться без мощного железа.
Рейкастинг превращает двумерную карту в трёхмерную картинку: один луч на столбец экрана.
Скриншоты остальных игр мы не публикуем: свободной лицензии на их изображения мы не нашли, поэтому вместо картинок — ссылки. Все товарные знаки принадлежат их владельцам. Урок не связан с правообладателями и не одобрен ими. Шрифт игры «Марсиане» — font8x8, автор Daniel Hepper (общественное достояние)[34].
Сделано командой Starbound вместе с Grok. Шрифт игры — font8x8 (общественное достояние)[34].
С заботой, команда Starbound
New class · Nov 24, 2026
How classic PC games worked: from Sopwith to Wolfenstein 3D
Starbound Academy · Archimedes' Workshop · Class 4 · About 25 minutes
How did games show fighter planes, race tracks and 3D mazes on computers of the era, such as the Soviet Istra-4816, Iskra-1030M and ES-1840/1841 PCs, with a 16-bit processor and 640 KB of memory? No 3D graphics card, no floating-point math, barely any memory. The answer is a handful of tricks that are still in use: the game loop, sprites, fixed-point arithmetic and raycasting. I double-checked every date and name against two independent sources; the numbers in square brackets point to the list at the end.
1. The computers of the era and the games in this class
We are talking about PCs of the era (IBM PC/XT, Intel 8088, CGA). The Intel 8088 came out in 1979; in the IBM PC and IBM PC XT it ran at 4.77 MHz[29, 28]. The IBM PC XT arrived on March 8, 1983; it had a socket for the 8087 math coprocessor, but the chip itself was an optional extra[28]. CGA (Color Graphics Adapter) appeared in 1981: 16 KB of video memory and a 320×200 mode with just 4 colors from fixed palettes[27, 22].
The same class of IBM PC/XT compatibles was built in the USSR; all of them use the К1810ВМ86 (K1810VM86), a Soviet copy of the Intel 8086. Where sources disagree, we show both values.
Machine
Processor
Clock
RAM
Istra-4816
К1810ВМ86 + two КР580ВМ80А (Intel 8080 copies)[55, 57]
not stated in the sources we found
512 KB – 1 MB[57]; 1–4 MB per the designers[56], shared by all processors
Raycasting, 256-color VGA; needs a 286, designed for a 386[14, 15, 21]
2. The game loop: input, update, render, timing
🚀 Launch pad
Every game, from Martians to Wolfenstein 3D, is the same loop running many times a second. Think of a flip-book: on each page the hero has moved a little, and flipping fast turns the pages into motion[25].
Pseudocode
while the game is running:
read the keys # INPUT
move everything one step # UPDATE (rules, collisions, score)
draw the frame # RENDER
wait for the frame to end # TIMING: same speed on any computer
Why timing matters. Early programs often measured time by the speed of the processor. On faster computers those games ran too fast to play, which is why PC cases grew a Turbo button: switching it off slowed the machine down for old games[31, 25]. The real fix is to measure actual time and move things by however much time has passed[26].
A real example: Wolfenstein 3D. In id Software’s released source code, the PlayLoop function does exactly these steps. The timer ticks 70 times a second (TickBase 70), CalcTics counts how many ticks passed since the last frame, and all movement is multiplied by that number. A slower computer draws fewer frames, but the enemies still run at the same speed[18, 19, 20, 21].
C · Wolfenstein 3D (shortened)
/* Wolfenstein 3D, id Software, 1992 (released source, 1995) */
typedef long fixed; /* WL_DEF.H: 32-bit number, 16.16 fixed point */
#define GLOBAL1 (1l<<16) /* WL_DEF.H: 1.0 = 65536 = one map tile */
#define MAPSIZE 64 /* WL_DEF.H: the map is a 64 x 64 grid */
#define TickBase 70 /* ID_SD.H: the timer ticks 70 times a second */
/* WL_PLAY.C, PlayLoop (simplified order of calls): */
CalcTics (); /* how many 1/70 s ticks passed since the last frame */
PollControls (); /* input */
MoveDoors (); /* ... DoActor() for every enemy ... */ /* update */
ThreeDRefresh (); /* render: cast the rays, draw walls and sprites */
3. How 80s and 90s games faked physics
🛰️ Orbit
3.1 Four CGA colors
In 320×200 mode, CGA showed only 4 colors, and not just any four: one palette was green, red and brown, the other cyan, magenta and white, plus a background color[27, 22]. Artists drew so that the eye would fill in the detail.
3.2 Sprites
A sprite is a small picture that the program draws on top of the background and moves as one piece[32]. Grand Prix Circuit built its first-person race out of sprites, not polygons[4, 5]. Even the enemies in Wolfenstein 3D are flat sprites that simply scale with distance[14, 21].
3.3 Fixed point instead of floating point
The 8088, and a 386 without a coprocessor, had no FPU (floating-point unit), and emulating one in software was too slow. So fractions were stored as integers: the low 16 bits hold the fraction, the high 16 bits the whole part. That is 16.16 fixed point[30, 21]. Wolfenstein 3D stores the player’s position this way: typedef long fixed;, with one unit equal to 1<<16[17, 21].
A Wolfenstein 3D map is a 64×64 grid[17]. For each screen column (there are 320) the program casts one ray and steps through the grid cells until it hits a wall. This cell-by-cell walk is called DDA (digital differential analyzer). The farther the wall, the shorter its column on screen. To stop the walls from bulging like a fisheye lens, the distance is multiplied by the cosine of the angle between the ray and the viewing direction[24, 23, 33]. Wolfenstein 3D came out on May 5, 1992 (id Software, published by Apogee). It is written in ANSI C (the C standard from the American National Standards Institute), with the hottest parts, raycasting and scaling, in assembly, and it draws 320×200 VGA (Video Graphics Array) graphics in 256 colors[14, 21, 15]. In 1995 id Software released the source code[14, 16].
4. Martians: a code walkthrough
🪐 Mars base
Now let’s play. Martians is a terminal game: zeros fall from the top, and a carriage at the bottom catches them. A catch is worth 10 points; a miss costs a life and briefly inverts the screen. You have three lives. Below is the browser version: 320×200 logical resolution, black-and-white graphics, ← → or A/D to move, R to restart, Q to pause, with on-screen buttons on phones. Further down: how a human and an AI (artificial intelligence) built it together.
A faithful remake of the founder's first game, reconstructed from his description. Original code coming soon.Open full screen →The original in a terminal: silent video. Recorded on the original system: an airgapped HP 255 G10 laptop (AMD Ryzen 5 7530U, 16 GB RAM, 512 GB SSD) running Omarchy Linux.
4.1 Human + AI: how it was built
The founder of Starbound came up with the game and drove it to a working version; Grok helped as an engineer: code, troubleshooting and math. The gameplay itself is the human’s idea. The times below count from the first “let’s build the game” request (minute 0), using the message timestamps in the session log.
Elapsed (h:mm)
Milestone
Who drove it
Grok’s part
0:00
The idea: “let’s build that game”
Founder
—
0:02
Choice: bash, as short as possible. First version of the code
Founder + Grok
code
0:05
A second, minimal version
Grok
code
0:50
First version typed in by hand
Founder
—
0:57
First error found: a missing do
Grok
troubleshooting
0:59
First run: the zeros blink but do not fall
Founder
—
0:59
Falling version: +10 points, 3 lives, catch check, game over
Grok
code
1:03
At the founder’s request: a commented version
Founder + Grok
code
1:31
Commented version typed in
Founder
—
1:31–1:54
Debugging: array syntax, if/fi pairs, bash -n, set -x. The founder suggested echo debugging and asked for set -x
Founder + Grok
troubleshooting
2:27
The founder found a missing “)” himself
Founder
—
2:29
The game runs: the carriage moves, but nothing falls
Founder
—
2:36
The arrow-key quirk is kept as a feature (the founder’s call; Grok explained escape sequences)
Founder + Grok
troubleshooting
2:40
Two typos found in the fall logic: >= instead of ++, and a missing then
Grok
troubleshooting
2:46
Catching works, but everything is too fast
Founder
—
2:47
Zeros move only every 3rd frame (tick % 3)
Grok
math
2:58
It works. Spawn rate: RANDOM % 12 == 0, at most 5 zeros at once
Founder + Grok
math
3:03–3:19
Math recap: probability ≈ 1/12 and the general rule (x mod n = 0) ∧ (c < m)
Grok
math
In total: 2 h 58 min from the first request to the tuned working version, or 3 h 19 min including the math recap. That is 200 messages. Restart and the inverted flash came later, outside this log.
4.2 The commented code
We carefully rewrote the game as a teaching version: every setting sits in a constants block at the top, the loop is split into input, update and render, and there is a terminal-size check and a clean exit. It needs only bash and the standard tput and stty tools, and no network. Download martians_v1_commented.sh and run it with bash martians_v1_commented.sh. This is not the founder’s own file: his original code will be published later.
The heart of the game is the update step. Zeros fall only on every 3rd frame, so the carriage stays quick while the zeros fall slowly. Whether a zero is caught comes down to one comparison: carriage ≤ x < carriage + width.
bash · update
# 5.3 Zeros fall only every FALL_EVERY-th frame, so the carriage stays quick
# while zeros fall slowly (the fix from the build session: tick % 3).
if (( tick % FALL_EVERY == 0 )); then
local i kept_x=() kept_y=()
for i in "${!zero_x[@]}"; do
local x=${zero_x[i]} y=$(( zero_y[i] + 1 ))
if (( y >= FIELD_H )); then
# Landed. Caught if it is over the carriage: carriage <= x < carriage + width
if (( x >= carriage && x < carriage + CARRIAGE_W )); then
(( score += POINTS ))
else
(( lives-- ))
flash=$FLASH_FRAMES # start the inverted flash
fi
# A landed zero is not kept (this replaces unset + re-pack of the arrays).
else
kept_x+=( "$x" ); kept_y+=( "$y" )
fi
done
zero_x=( "${kept_x[@]}" ); zero_y=( "${kept_y[@]}" )
fi
And here is the loop itself: input, update, render, then wait for the end of the frame, just like the pseudocode in section 2.
bash · main loop
while (( lives > 0 )); do
start=${EPOCHREALTIME/./} # microseconds (bash 5+; empty on bash 4)
read_key # INPUT (waits up to one frame)
[[ $key == quit ]] && exit 0
update # UPDATE
render # RENDER
# WAIT: a key press ends `read` early; sleep the rest of the frame so
# the game runs at the same speed whether or not keys are pressed.
if [[ -n $start ]]; then
now=${EPOCHREALTIME/./}
spent=$(( now - start ))
if (( spent < FRAME_US )); then
sleep "0.$(printf '%06d' $(( FRAME_US - spent )))"
fi
fi
done
The chance of a new zero in any frame is about 1/12, because RANDOM % 12 == 0 is true for one remainder out of twelve. In general: (x mod n = 0) ∧ (c < m), so a zero appears with probability ≈ 1/n while fewer than m zeros are on screen.
Coming in v2: an AI model plays the game
In v1, a human plays. In the next version, an AI model takes the keyboard.
5. Security corner
The browser version is one page and one JavaScript file: the game code itself makes no network requests, downloads nothing and uses no external fonts. The high score stays in your own browser. In this lesson it runs inside a sandbox. Like the rest of the site, this page uses Cloudflare’s cookieless page analytics, which store nothing in your browser (Cloudflare docs). Before you run any script from the internet, read it and check its syntax without running it: bash -n file.sh.
6. Summary
A game is a loop: input → update → render → timing.
Measure speed with a clock, not with the processor.
Sprites, 4 CGA colors and fixed point let games do without powerful hardware.
Raycasting turns a flat map into a 3D picture: one ray per screen column.
Credit where credit is due: here is who made every game this class talks about. Where a game has no official page, the link goes to the most reliable page available.
We do not show screenshots of the other games: we found no free license for their images, so we link to them instead. All trademarks are the property of their respective owners. This class is not affiliated with or endorsed by them. The Martians game font is font8x8 by Daniel Hepper (public domain)[34].
Built by the Starbound crew with Grok. Game font: font8x8 (public domain)[34].
With care, the Starbound team
Clase nueva · 24 nov 2026
Cómo funcionaban los juegos clásicos de PC: de Sopwith a Wolfenstein 3D
Academia Starbound · Taller de Arquímedes · Clase 4 · Unos 25 minutos
¿Cómo mostraban los juegos aviones, carreras y laberintos en 3D en los computadores de la época, como los PC soviéticos Istra-4816, Iskra-1030M y ES-1840/1841, con un procesador de 16 bits y 640 KB de memoria? Sin tarjeta 3D, sin números de coma flotante y casi sin memoria. La respuesta está en unos pocos trucos que siguen vigentes: el bucle de juego, los sprites, la aritmética de punto fijo y el raycasting. Cada fecha y cada nombre se comprobaron con dos fuentes independientes; los números entre corchetes remiten a la lista final.
1. Los equipos de la época y los juegos de esta clase
Hablamos de PC de la época (IBM PC/XT, Intel 8088, CGA). El Intel 8088 salió en 1979; en el IBM PC y el IBM PC XT funcionaba a 4,77 MHz[29, 28]. El IBM PC XT llegó el 8 de marzo de 1983; tenía zócalo para el coprocesador matemático 8087, que se compraba aparte[28]. CGA (Color Graphics Adapter, adaptador de gráficos en color) apareció en 1981: 16 KB de memoria de video y un modo de 320×200 con solo 4 colores de paletas fijas[27, 22].
En la URSS se fabricaron compatibles IBM PC/XT de la misma clase; todos usan el К1810ВМ86 (K1810VM86), una copia soviética del Intel 8086. Cuando las fuentes no coinciden, mostramos ambos valores.
Equipo
Procesador
Frecuencia
RAM
Istra-4816
К1810ВМ86 + dos КР580ВМ80А (copias del Intel 8080)[55, 57]
no figura en las fuentes encontradas
512 KB – 1 MB[57]; 1–4 MB según los diseñadores[56], compartida por todos los procesadores
Raycasting, VGA de 256 colores; necesita un 286, pensado para un 386[14, 15, 21]
2. El bucle de juego: entrada, actualización, dibujo, tiempo
🚀 Plataforma de lanzamiento
Todo juego, de Marcianos a Wolfenstein 3D, es el mismo bucle repetido muchas veces por segundo. Como un libro animado: en cada página el personaje se movió un poco y, al pasar las páginas rápido, aparece el movimiento[25].
Pseudocódigo
mientras el juego siga:
leer las teclas # ENTRADA
mover todo un paso # ACTUALIZAR (reglas, choques, puntos)
dibujar el cuadro # DIBUJAR
esperar al final del cuadro # TIEMPO: misma velocidad en cualquier equipo
Por qué importa el tiempo. Los primeros programas solían medir el tiempo según la velocidad del procesador. En equipos más rápidos esos juegos iban demasiado deprisa, y por eso las cajas de PC tenían un botón Turbo: al apagarlo, la máquina se ralentizaba para los juegos antiguos[31, 25]. La solución correcta es medir el tiempo real y mover cada cosa según el tiempo transcurrido[26].
Un ejemplo real: Wolfenstein 3D. En el código fuente publicado por id Software, la función PlayLoop sigue exactamente esos pasos. El temporizador marca 70 veces por segundo (TickBase 70), CalcTics cuenta cuántos ticks pasaron desde el último cuadro y todo movimiento se multiplica por ese número[18, 19, 20, 21].
C · Wolfenstein 3D (resumido)
/* Wolfenstein 3D, id Software, 1992 (released source, 1995) */
typedef long fixed; /* WL_DEF.H: 32-bit number, 16.16 fixed point */
#define GLOBAL1 (1l<<16) /* WL_DEF.H: 1.0 = 65536 = one map tile */
#define MAPSIZE 64 /* WL_DEF.H: the map is a 64 x 64 grid */
#define TickBase 70 /* ID_SD.H: the timer ticks 70 times a second */
/* WL_PLAY.C, PlayLoop (simplified order of calls): */
CalcTics (); /* how many 1/70 s ticks passed since the last frame */
PollControls (); /* input */
MoveDoors (); /* ... DoActor() for every enemy ... */ /* update */
ThreeDRefresh (); /* render: cast the rays, draw walls and sprites */
3. Cómo los juegos de los 80 y 90 fingían la física
🛰️ Órbita
3.1 Cuatro colores CGA
En el modo 320×200, CGA mostraba solo 4 colores: una paleta con verde, rojo y marrón, otra con cian, magenta y blanco, más un color de fondo[27, 22].
3.2 Sprites
Un sprite es una imagen pequeña que el programa dibuja sobre el fondo y mueve de una pieza[32]. Grand Prix Circuit armaba su carrera en primera persona con sprites, no con polígonos[4, 5]. Incluso los enemigos de Wolfenstein 3D son sprites planos que se escalan con la distancia[14, 21].
3.3 Punto fijo en lugar de coma flotante
El 8088, y un 386 sin coprocesador, no tenían FPU (floating-point unit, unidad de coma flotante), y emularla por software era demasiado lento. Por eso las fracciones se guardaban como enteros: los 16 bits bajos son la parte fraccionaria y los altos, la entera. Es el punto fijo 16.16[30, 21]. Wolfenstein 3D guarda así la posición del jugador: typedef long fixed;, con la unidad igual a 1<<16[17, 21].
Un mapa de Wolfenstein 3D es una cuadrícula de 64×64[17]. Para cada columna de la pantalla (hay 320) el programa lanza un rayo y avanza celda a celda hasta chocar con una pared; este recorrido se llama DDA (digital differential analyzer, analizador diferencial digital). Cuanto más lejos está la pared, más baja es su columna. Para evitar el efecto «ojo de pez», la distancia se multiplica por el coseno del ángulo entre el rayo y la dirección de la mirada[24, 23, 33]. Wolfenstein 3D salió el 5 de mayo de 1992 (id Software, editado por Apogee); está escrito en ANSI C (el estándar de C del American National Standards Institute), con el raycasting y el escalado en ensamblador, y usa VGA (Video Graphics Array) de 320×200 con 256 colores[14, 21, 15]. En 1995 id Software publicó el código fuente[14, 16].
4. Marcianos: recorrido por el código
🪐 Base en Marte
Ahora a jugar. Marcianos es un juego de terminal: caen ceros desde arriba y un carro abajo los atrapa. Cada captura vale 10 puntos; cada fallo quita una vida e invierte la pantalla un instante. Hay tres vidas. Abajo está la versión para navegador: ← → o A/D para mover, R para reiniciar, Q para pausar, y botones en pantalla en el teléfono. Más abajo: cómo la hicieron juntos una persona y una IA (inteligencia artificial).
Una versión fiel del primer juego del fundador, reconstruida a partir de su descripción. El código original llegará pronto.Abrir a pantalla completa →El original en una terminal: video sin sonido. Grabado en el sistema original: una laptop HP 255 G10 aislada de la red (AMD Ryzen 5 7530U, 16 GB de RAM, SSD de 512 GB) con Omarchy Linux.
4.1 Humano + IA: cómo se hizo
El fundador de Starbound ideó el juego y lo llevó hasta una versión que funciona; Grok ayudó como ingeniero: código, depuración y matemáticas. La jugabilidad es idea humana. Los tiempos cuentan desde la primera petición «hagamos el juego» (minuto 0), según las marcas de tiempo de los mensajes del registro de la sesión.
Transcurrido (h:mm)
Hito
Quién lo llevó
Aporte de Grok
0:00
La idea: «hagamos ese juego»
Fundador
—
0:02
Elección: bash, lo más corto posible. Primera versión del código
Fundador + Grok
código
0:05
Una segunda versión mínima
Grok
código
0:50
Primera versión tecleada a mano
Fundador
—
0:57
Primer error encontrado: falta un do
Grok
depuración
0:59
Primera ejecución: los ceros parpadean pero no caen
Fundador
—
0:59
Versión con caída: +10 puntos, 3 vidas, comprobación de captura, fin del juego
Grok
código
1:03
A petición del fundador: una versión comentada
Fundador + Grok
código
1:31
Versión comentada tecleada
Fundador
—
1:31–1:54
Depuración: sintaxis de arreglos, pares if/fi, bash -n, set -x. El fundador propuso depurar con echo y pidió set -x
Fundador + Grok
depuración
2:27
El fundador encontró solo un «)» que faltaba
Fundador
—
2:29
El juego arranca: el carro se mueve, pero nada cae
Fundador
—
2:36
La rareza de las flechas se queda como función (decisión del fundador; Grok explicó las secuencias de escape)
Fundador + Grok
depuración
2:40
Dos erratas en la lógica de caída: >= en lugar de ++, y falta un then
Grok
depuración
2:46
Atrapar funciona, pero todo va demasiado rápido
Fundador
—
2:47
Los ceros se mueven solo cada 3.er cuadro (tick % 3)
Grok
matemáticas
2:58
Funciona. Aparición: RANDOM % 12 == 0, como máximo 5 ceros a la vez
Fundador + Grok
matemáticas
3:03–3:19
Repaso matemático: probabilidad ≈ 1/12 y la regla general (x mod n = 0) ∧ (c < m)
Grok
matemáticas
En total: 2 h 58 min desde la primera petición hasta la versión ajustada, o 3 h 19 min con el repaso matemático; 200 mensajes. El reinicio y el destello invertido se añadieron después, fuera de este registro.
4.2 El código comentado
Reescribimos el juego como versión didáctica: ajustes en un bloque de constantes arriba, el bucle dividido en entrada, actualización y dibujo, comprobación del tamaño de la terminal y salida limpia. Solo necesita bash y las herramientas estándar tput y stty, sin red. Descargue martians_v1_commented.sh y ejecútelo con bash martians_v1_commented.sh. No es el archivo del fundador: su código original se publicará más adelante.
bash · actualización
# 5.3 Zeros fall only every FALL_EVERY-th frame, so the carriage stays quick
# while zeros fall slowly (the fix from the build session: tick % 3).
if (( tick % FALL_EVERY == 0 )); then
local i kept_x=() kept_y=()
for i in "${!zero_x[@]}"; do
local x=${zero_x[i]} y=$(( zero_y[i] + 1 ))
if (( y >= FIELD_H )); then
# Landed. Caught if it is over the carriage: carriage <= x < carriage + width
if (( x >= carriage && x < carriage + CARRIAGE_W )); then
(( score += POINTS ))
else
(( lives-- ))
flash=$FLASH_FRAMES # start the inverted flash
fi
# A landed zero is not kept (this replaces unset + re-pack of the arrays).
else
kept_x+=( "$x" ); kept_y+=( "$y" )
fi
done
zero_x=( "${kept_x[@]}" ); zero_y=( "${kept_y[@]}" )
fi
bash · bucle principal
while (( lives > 0 )); do
start=${EPOCHREALTIME/./} # microseconds (bash 5+; empty on bash 4)
read_key # INPUT (waits up to one frame)
[[ $key == quit ]] && exit 0
update # UPDATE
render # RENDER
# WAIT: a key press ends `read` early; sleep the rest of the frame so
# the game runs at the same speed whether or not keys are pressed.
if [[ -n $start ]]; then
now=${EPOCHREALTIME/./}
spent=$(( now - start ))
if (( spent < FRAME_US )); then
sleep "0.$(printf '%06d' $(( FRAME_US - spent )))"
fi
fi
done
La probabilidad de un cero nuevo en cada cuadro es de alrededor de 1/12, porque RANDOM % 12 == 0 se cumple para un resto de cada doce. En general: (x mod n = 0) ∧ (c < m).
Próximamente en v2: un modelo de IA juega el juego
En v1 juega una persona. En la próxima versión, un modelo de IA tomará el teclado.
5. Rincón de seguridad
La versión para navegador es una página y un archivo JavaScript: el código del juego en sí no hace solicitudes de red, no descarga nada y no usa fuentes externas. El récord se queda en su propio navegador. Aquí se ejecuta dentro de un sandbox. Como el resto del sitio, esta página usa la analítica de páginas sin cookies de Cloudflare, que no guarda nada en su navegador (documentación de Cloudflare). Antes de ejecutar cualquier script de internet, léalo y compruebe su sintaxis sin ejecutarlo: bash -n archivo.sh.
6. Resumen
Un juego es un bucle: entrada → actualización → dibujo → tiempo.
La velocidad se mide con un reloj, no con el procesador.
Sprites, 4 colores CGA y punto fijo permitían prescindir de hardware potente.
El raycasting convierte un mapa plano en imagen 3D: un rayo por columna.
Reconocemos el mérito de quien lo tiene: aquí está quién hizo cada juego del que habla esta clase. Si un juego no tiene página oficial, el enlace lleva a la página más fiable disponible.
No mostramos capturas de los demás juegos: no encontramos una licencia libre para sus imágenes, así que enlazamos a ellos. Todas las marcas comerciales pertenecen a sus respectivos dueños. Esta clase no está afiliada a ellos ni cuenta con su respaldo. La fuente del juego Martians es font8x8, de Daniel Hepper (dominio público)[34].
/* Wolfenstein 3D, id Software, 1992 (released source, 1995) */
typedef long fixed; /* WL_DEF.H: 32-bit number, 16.16 fixed point */
#define GLOBAL1 (1l<<16) /* WL_DEF.H: 1.0 = 65536 = one map tile */
#define MAPSIZE 64 /* WL_DEF.H: the map is a 64 x 64 grid */
#define TickBase 70 /* ID_SD.H: the timer ticks 70 times a second */
/* WL_PLAY.C, PlayLoop (simplified order of calls): */
CalcTics (); /* how many 1/70 s ticks passed since the last frame */
PollControls (); /* input */
MoveDoors (); /* ... DoActor() for every enemy ... */ /* update */
ThreeDRefresh (); /* render: cast the rays, draw walls and sprites */
# 5.3 Zeros fall only every FALL_EVERY-th frame, so the carriage stays quick
# while zeros fall slowly (the fix from the build session: tick % 3).
if (( tick % FALL_EVERY == 0 )); then
local i kept_x=() kept_y=()
for i in "${!zero_x[@]}"; do
local x=${zero_x[i]} y=$(( zero_y[i] + 1 ))
if (( y >= FIELD_H )); then
# Landed. Caught if it is over the carriage: carriage <= x < carriage + width
if (( x >= carriage && x < carriage + CARRIAGE_W )); then
(( score += POINTS ))
else
(( lives-- ))
flash=$FLASH_FRAMES # start the inverted flash
fi
# A landed zero is not kept (this replaces unset + re-pack of the arrays).
else
kept_x+=( "$x" ); kept_y+=( "$y" )
fi
done
zero_x=( "${kept_x[@]}" ); zero_y=( "${kept_y[@]}" )
fi
bash · メインループ
while (( lives > 0 )); do
start=${EPOCHREALTIME/./} # microseconds (bash 5+; empty on bash 4)
read_key # INPUT (waits up to one frame)
[[ $key == quit ]] && exit 0
update # UPDATE
render # RENDER
# WAIT: a key press ends `read` early; sleep the rest of the frame so
# the game runs at the same speed whether or not keys are pressed.
if [[ -n $start ]]; then
now=${EPOCHREALTIME/./}
spent=$(( now - start ))
if (( spent < FRAME_US )); then
sleep "0.$(printf '%06d' $(( FRAME_US - spent )))"
fi
fi
done
各フレームで0が出る確率は約1/12です。RANDOM % 12 == 0は12通りの余りのうち1つで成り立つからです。一般形は (x mod n = 0) ∧ (c < m) です。