about « all posts

Tinybricks: A Bootsector Game

Jun 18 2021 · 2 min read
#assembly #boot-sector #game #x86

After this piece of code has been lying around for too long, it is finally time to publish it. Back in 2019, I spent a weekend writing a small game that fits in one boot sector. A boot sector is 512 bytes in size, with 2 bytes being a magic word. In the end, 510 bytes of plain memory are left for the program code itself. With that restriction, every possible measure must be taken to minimize the binary size.

To name just a few of those measures: Complex instructions are used to lower the instruction count. Prologs and epilogs of function calls are removed if possible and jumps are preferred over calls. Variables are placed in the screen memory of the graphics card. Thus, the state of the variables is visible in the top right corner as flashing pixels. There are also algorithmic tricks used that result in less size: Once the ball hits a brick, one pixel is colored in the background color. Then, an algorithm searches for black pixels in brick areas. If such a pixel is found, the brick is re-colored in another color code. Luckily, there are two different color codes available for the color black. This trick lets the code distinguish between the background and a dead brick without being visible on the screen anymore.

Tinybricks example

In the end, a somewhat playable game was the result. Unluckily, there is no randomness. The ball takes the same trajectory each time. BUT … the thing is bootable without an OS which was great fun developing.

Full code: GitHub

;
; LET THE FUN BEGIN :)
;
boot_game:
  mov ax, 0x0013      ; VGA 320x200 256 color mode (bottom line for vars)
  int 0x10
  mov ax, 0xa000      ; set segments
  mov ds, ax          ; video segment
  mov es, ax
  cld                 ; and some basic adjustments

init_bricks:
  mov cx, BRICKS_NR   ; init this number of bricks  
  mov ax, BK_LIVE_COLOR ; ... with color: living
  xor di, di
  rep stosb

; ...
; ...
; ...