assemblycorewarsredcode

Helping understanding RedCode


I'm trying to learn redcode, because it looks fun to make a bot.

Introduction

For those who don't know what redcode is, here's a short explanation. It's an ASM-like language, but far more easy and stripped. It is used to write little programs that need to shut down other programs in virtual memory. (See for more info here: http://vyznev.net/corewar/guide.html)

Here's a piece of code:

;redcode
;name Mice
;author Chip Wendell
;strategy paper (replicator)
;history Winner of the 1986 ICWS tournament
Top dat #0, #0
Start   mov #12,    Top
Loop    mov @Top,   <Target
    djn Loop,   Top
    spl @Target,0
Spacer  equ 653
    add #Spacer,Target
    jmz Start,  Top
Target  dat #0, #833
    end Start

Problem

The basic strategy is to replicate itself to another place, and the fork the process. What I don't understand is this rule:

Loop    mov @Top,   <Target

I understand the meaning of this line. It says, move the B-Field of target to the line where the B-Field of top points, and decrease the value of the B-Field of target.

When loop is executed for the first time, the first line will be:

Top dat #0, #12

As far as I get, the line with Loop means: Move the instruction 12 lines ahead (filled with dat #0, #0) to line 833.

But when this code is executed, the line of code is placed at line 839.

Does someone understand what is happening really?


Solution

  • Okay, that took quite a bit of reading, but here's your answer:

    The first instruction, as you correctly surmise, makes Top into DAT #0, #12. Simple enough, but the next instruction is trickier. First, it decrements the B-value of Target (making it 832). Then, it copies the instruction at Top into the location 832 lines ahead relative to Target. That's the key: the indirect addressing mode means the destination is relative to the B-value read for the offset. Now look at the code after compilation, with line numbers in front:

    0000 Top    DAT.F  #0        #0       
    0001 Start  MOV.AB #12       $-1      
    0002 Loop   MOV.I  @-2       <5       
    0003        DJN.B  $-1       $-3      
    0004        SPL.B  @3        $0       
    0005        ADD.AB #653      $2       
    0006        JMZ.B  $-5       $-6      
    0007 Target DAT.F  #0        #833  
    

    As you can see, Target is on line 7, so 832 lines ahead relative to Target is line 839.

    Hope that clears it up for you.