Friday, September 24, 2010

Core War!

Two programs enter. One leaves. Picture this, tiny assembly language programs battling each other in core memory space* each trying to overwrite the other. Survival of the fittest.

Programs attack!
It's called Corewar. It's a game. A really cool, but kind of old programming game. I haven't looked at it in years but something made me think of it.

The appeal for me is the opportunity to think really creatively about assembly coding. It seems like good mental exercise. Maybe it will jar me into some epiphany about my vision code so I can get more than 3fps frame rate...

The game's assembly language, called Redcode, has 17 instructions and programs run on a virtual computer, the Memory Array Redcode Simulator (MARS) consisting of 8000 memory locations*. You can download various MARS implementations like A.R.E.S. or pMARS.
The goal is to try to get another program to execute a DAT opcode, which will crash it. To do this, your code (warrior) has to drop a DAT into memory right where the other warrior's Program Counter (PC) is pointing to run the next instruction.

Here's sample code from Corewars for Dummies.
;name Sleepy
;author John Q. Smith
;strategy bombing core

ADD #10, #-1
MOV 2, @-1
JMP -2, 0
DAT #33, #33

The instruction ADD #10, #-1 is a self-modifying instruction. It adds the constant 10 (# specifies immediate addressing) to the constant in the second argument. When done the instruction becomes ADD #10, #9

The instruction MOV   2,  @-1 attempts to move the data in the memory cell PC+2 (the line DAT #33, #33) to the location specified in the second argument of the previous instruction... #9, that is. So it attempts to copy DAT #33, #33 to a location in memory 9 cells beyond the current program counter. Or, PC+9.

You can imagine JMP -2, 0 jumps back to the ADD line. That is, it sets PC = PC-2. And the process starts over. Basically the code drops DAT bombs every 10 memory cells.

Here's what battling warriors look like. Dig the cool 8-bit game music.

* von Neumann architecture, of course.

No comments:

Post a Comment