DEV Community

Cover image for Writing a NES game day 4: Start code analysis
Draculinio
Draculinio

Posted on

Writing a NES game day 4: Start code analysis

Continuing from day three, let's continue looking at this code.

After telling the emulator that this is a NES program we have to establish a couple of segments:

.segment "ZEROPAGE" ; $0000 hasta $00FF 256bytes - the fastest ram
.segment "STARTUP"

The first segment is Zeropage, this is the fastest part of the memory that goes from $00 to $FF (256 bytes) and in the future we will put here whatever we need to run fast.

We are not using the startupsegment and still don't know what it is used for but I feel that we will discover this later (remember that I am learning this as I am writing)

Next is the code segment:

`.segment "CODE"

RESET:
SEI ; disable IRQs
CLD ; disable decimal mode
LDX #$40
STX $4017 ; disable APU frame counter IRQ - disable sound
LDX #$ff
TXS ; setup stack starting at FF as it decrements instead if increments
INX ; overflow X reg to $00
STX $2000 ; disable NMI - PPUCTRL reg
STX $2001 ; disable rendering - PPUMASK reg
STX $4010 ; disable DMC IRQs`

And the first label we see here is RESET which is kind of starting point for when the game starts.
SEI, interrupts the IRQ. What is an IRQ? They are hardware interruptions (we can talk a little more about this but there is plenty of information with a simple google).
Then CLD (Clear Decimal) that disables decimal mode.
The rest of the lines are a way to put everything in kind of initial mode for the game.

vblankwait1: ; wait for vblank to make sure PPU is ready
BIT $2002 ; returns bit 7 of ppustatus reg
BPL vblankwait1

Now, we are waiting for vblank moment to make sure that the PPU is ready. vblank is the moment when nothing is sent to the video so we can do the changes we want to the graphics (the explanation is bigger, but for now this will do it).

BIT $2002 returns the 7th. bit of ppu status, this bit holds the vblank status (0 = no vblank, 1 = vblank). This affects N flag.
Then it will jump until N flag is 1 (BPL branches if N = 0)

clearmem:
LDA #$00
STA $0000, x
STA $0100, x
STA $0300, x
STA $0400, x
STA $0500, x
STA $0600, x
STA $0700, x
LDA #$fe
STA $0200, x ; Set aside space in RAM for sprite data
INX
BNE clearmem

Next step is clearing the memory so, let's loop until all is clear!

vblankwait2: ; Second wait for vblank, PPU is ready after this
BIT $2002
BPL vblankwait2

A second wait for vblank... I think is needed given the time passed but, still don't understand lots of things here

Well, tomorrow we will clear the screen put a background color and if possible finish week 3.

So far: I barely understand what is happening and I am writing to teach myself, but there are still a lot of things that I don't get.

Top comments (0)