Skip to content

Instantly share code, notes, and snippets.

@tobiasvl
Last active February 20, 2023 22:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tobiasvl/a9bcc216e4d474ad62eabde7a91d5bd5 to your computer and use it in GitHub Desktop.
Save tobiasvl/a9bcc216e4d474ad62eabde7a91d5bd5 to your computer and use it in GitHub Desktop.
RGBDS routine for verifying, clearing and loading SRAM in a Game Boy game
; Based on nitro2k01's code from https://forums.nesdev.org/viewtopic.php?t=14631
; Changes:
; - Retains all registers, so a call to this routine can be added anywhere
; - Instead of saving all WRAM, just save a set number of bytes (c)
; Usage:
; - On boot, call LoadSRAM (will init and zero SRAM if needed, then load from SRAM)
; - When saving, call SaveSRAM (and then potentially LoadSRAM.sramOK)
LoadSRAM:
call EnableSram
; Check for validity of SRAM by looking for the name of the game from the ROM header
ld de, $0134 ; Use the copy of the string that is already in the ROM header
ld hl, $A000 ; Bottom of SRAM
.verifyLoop
ld a, [de] ; Load character from the string in ROM
or a ; Zero check. If we reached the end of the string, the signature is valid.
jr z, .sramOk
cp [hl] ; Compare with the SRAM byte.
inc de
inc hl
jr z, .verifyLoop ; Continue checking the string?
ld de, $0134 ; Use the copy of the string that is already in the ROM header.
ld hl, $A000 ; Bottom of SRAM
.copySigLoop
ld a, [de] ; Load character from the string in ROM.
ld [hl+], a ; Copy the byte to SRAM and post-increment the RAM point.
inc de ; Increment the ROM pointer.
or a ; Zero check. If we reached the end of the string, clear the rest of SRAM instead
jr nz, .copySigLoop ; Continue copying the string?
.clearSramLoop
xor a ; Set the value of a to 00.
ld [hl+], a ; Clear the byte to SRAM and post-increment the RAM point.
ld a, h ; High byte of pointer
cp $C0 ; When H=$C0 we have reached outside of SRAM.
jr nz, .clearSramLoop
.sramOk
; The signature matched, or SRAM was cleared. Now copy from SRAM to work RAM
ld hl, $A010 ; SRAM location after string
ld de, $C130 ; WRAM location, edit this
.copyHiScore
ld c, 7 ; Number of bytes
; Restore WRAM from the copy in SRAM
.restorehiscoreloop
ld a, [hl+]
ld [de], a
inc de
dec c
;ld a, h
;cp $c0 ; Has the source address reached outside $b000-$bfff?
jr nz, .restorehiscoreloop
; Disable SRAM access and return.
xor a
ld [$0000], a
pop hl
pop de
pop bc
pop af
ret
SaveToSRAM:
call EnableSram
; Copy from WRAM to SRAM
ld hl, $C120 ; WRAM location, edit this
ld de, $A010 ; SRAM location after string
jp LoadSRAM.copyHiScore
EnableSram:
; Retain registers
push af
push bc
push de
push hl
; Enable SRAM
ld a, $0A
ld [$0000], a
ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment