nand2tetris - Fill Screen..

..while a key is pressed..

Fill.asm
// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/04/Fill.asm
 
// Runs an infinite loop that listens to the keyboard input.
// When a key is pressed (any key), the program blackens the screen,
// i.e. writes "black" in every pixel;
// the screen should remain fully black as long as the key is pressed. 
// When no key is pressed, the program clears the screen, i.e. writes
// "white" in every pixel;
// the screen should remain fully clear as long as no key is pressed.
 
(GETINPUT)
    @KBD
    D = M
    @FILLSCREEN
    D;JGT
    @CLEARSCREEN
    D;JEQ
 
(FILLSCREEN)
    @8192
    D = A
    @counter
    M = D
 
    (FILLLOOP)
        @counter
        D = M
 
        // If counter < 0, jump to END
        @GETINPUT
        D;JLT
 
        // else..
        @fillbits
        0;JMP
        (fillbitscallback)
 
        // Decrement counter
        @counter
        M = M - 1
 
    @FILLLOOP
    0;JMP
 
(CLEARSCREEN)
    @8192
    D = A
    @counter
    M = D
 
    (CLEARLOOP)
        @counter
        D = M
 
        // If counter < 0, jump to END
        @GETINPUT
        D;JLT
 
        // else..
        @clearbits
        0;JMP
        (clearbitscallback)
 
        // Decrement counter
        @counter
        M = M - 1
 
    @CLEARLOOP
    0;JMP
 
(fillbits)
    @SCREEN
    D = A
    @counter
    D = D + M
    A = D
    M = -1
    @fillbitscallback
    0;JMP
 
(clearbits)
    @SCREEN
    D = A
    @counter
    D = D + M
    A = D
    M = 0
    @clearbitscallback
    0;JMP