Well, I thought to open a topic where we could share some useful code examples or ideas.
1. A method for switching buffer addresses (for drawing to the correct buffer) when using double buffering.
It comes from the source code for Rigor Mortis for the CPC which is based on disassembly of Elmar Krieger's (author of "Prehistorik 2" and "Super Cauldron" for the amstrad) game engine. The Source (among many others) can be found at
http://cpcrulez.fr/coding_menu-src.htm We prepare a LUT for the two buffer addresses:
first_buffer_address dw $0000
second_buffer_address dw $4000
...and we use a 16-bit variable for choosing between the two addresses:
double_buffer_offset dw $0002
We use it to offset to the wanted address so should be $0000 or $0002.
Everytime we want to change the offset we do:
ld hl,double_buffer_offset
ld a,(hl)
xor 2
ld (hl),a
To get the correct buffer address:
ld bc,(double_buffer_offset)
ld hl,first_buffer_address
add hl,bc
Now the wanted address is stored in memory at hl, so to get the address:
ld e,(hl)
inc l
ld d,(hl)
The address is now in de.
Earlier I switched the addresses by storing additional address variables for the active and hidden buffer address and switch the two for every game frame and also have a variable that stored the number of active buffer (0 or 1), because many times you have to choose which sprite background buffer to use (for which screen).
I find the one by Elmar Krieger to be somewhat cleaner and prettier...
2. Second is something like the strategy pattern in OOP (at least reminds me of it)...
When you want to use some optional code, like for example an optional gfx effect, additional game mode mechanic, switching music or something like that then you can do:
in your mainloop:
call something_dispatcher
the called subroutine is a simple jump:
something_dispatcher:
jp something
You can set the jump to what you want it to do...
For example for switching music/sfx/no sound you could set the dispatch address to the right routine...
When you don't want to do the "something" you set the jp address to a ret:
just_a_ret:
ret
To set the dispatch address to it:
ld hl,something_dispatch+1
ld (hl),just_a_ret
Else you can do conditionals every time but the presented method is a little quicker and cleaner (at least for me)...
One disadvantage would be that it's self modyfying code...