Intel 8080 CPU emulation in JavaScript

Space InvadersThis week end, I wanted to try a real world project to play more with TypeScript. Why TypeScript? Because I wanted to leverage a few ES6 features but also type checking. Note that I did not use strong typing, but just relied on the inference of types provided by the TypeScript compiler.

A few years ago, I wrote an Intel 8080 CPU emulator in ActionScript 3 and thought this would be a great fit for a TypeScript exercise. For the context, the Intel 8080 is a 2Mhz 8bit CPU. Through an Uint8Array (typed array), we can read each instruction (byte per byte) coming from a ROM and fully emulate the CPU.

So which game could we run to test the CPU? The Intel 8080 CPU was used inside the famous Space Invaders arcade machine, so using the original Space Invaders ROM, we can emulate the whole arcade system entirely in JavaScript (CPU/RAM/Input/Screen). Check the different files on the github repo. The CPU is the most important part, but I recommend you guys checking the other pieces, really fun to see how things work and how hardware is emulated.

The tricky thing is that because of the lack of byte type (ActionScript 3 has the same limitation), CPU registers (which are originally 8-bit) use the Number type, which is 64-bit, so each register needs to be masked constantly (register & 0xFF) to avoid overflow.

Here is the game playable here. It runs nicely on most browsers on desktop, it even runs nicely on mobile, except on UIWebView based browsers, where the lack of jitting seriously impacts performance.

(Space Invaders art by Alfimov)