assembly6502

6502 assembler random number problems


I am playing around with 6502 assembler here: http://skilldrick.github.io/easy6502

I have made this that just puts a random color pixel in a random place on the screen:

LDY #$00    ; Clear Y

loop:
 JSR genPos ; Put new position in memory
 LDA $fe    ; Get random number for color
 STA ($10), Y   ; Put pixel on screen
 JMP loop

genPos:
 STA $10    ; Store accumulator in low
 LDA $fe    ; Get new random number (WHY, oh why?)
 AND #$03   ; Mask out low two bits (=numbers 0-3)
 CLC        ; Clear carry flag
 ADC #2     ; Add 2 (= numbers 2-5)
 STA $11    ; Store number in high
 RTS

I am trying to use as few instructions as possible. My problem is that if I don't put an extra LDA $fe in the genPos sub routine the pixels are drawn in a very strange pattern where if I do have the extra LDA the code works perfectly. I can't comprehend why - can anyone give me a hint?

Regards, Jacob


Solution

  • It already is making a fine low byte! This line:

    LDA $fe    ; Get new random number (WHY, oh why?)
    

    goes on to decide the high byte, and if you don't generate a new random number, the y value will be dependent on the lowest two bits of the x value, causing the diagonals you're seeing: the value of x & 3 always equals which segment of screen the value is being drawn on, meaning you get a pattern like

    █   █   █   █   █   █   █   █    \
    █   █   █   █   █   █   █   █     |
    █   █   █   █   █   █   █   █     |  x & 3 == 0  in $200-$2FF
    █   █   █   █   █   █   █   █     |
    █   █   █   █   █   █   █   █    /
     █   █   █   █   █   █   █   █   \
     █   █   █   █   █   █   █   █    |
     █   █   █   █   █   █   █   █    |  x & 3 == 1  in $300-$3FF
     █   █   █   █   █   █   █   █    |
     █   █   █   █   █   █   █   █   /
      █   █   █   █   █   █   █   █  \
      █   █   █   █   █   █   █   █   |
      █   █   █   █   █   █   █   █   |  x & 3 == 2  in $400-$4FF
      █   █   █   █   █   █   █   █   |
      █   █   █   █   █   █   █   █  /
       █   █   █   █   █   █   █   █ \
       █   █   █   █   █   █   █   █  |
       █   █   █   █   █   █   █   █  |  x & 3 == 3  in $500-$5FF
       █   █   █   █   █   █   █   █  |
       █   █   █   █   █   █   █   █ /