19. More things

Now, for something completely different.

Random numbers.

The NES has no good way to generate random numbers.

neslib has rand8() and rand16() functions, but it doesn’t have a good way to seed it. It just uses a constant at startup, meaning that the random numbers will always be exactly the same at reset.

So I wrote a function that puts the frame count into the seed. So, you could put this on a title screen. seed_rng()

This just pushes the frame counter (an internal value) to the random seed. So it isn’t random at startup either, which is why you should wait for user input to randomly trigger it, like “PRESS START” on the title screen.

Here’s an example.




Note: seed_rng() only sets the low byte of the seed, which gives you 256 possibilities. If you want to set both seed bytes, use 1 user input to trigger the first seed_rng(), then call rand8() 3-4 times, then get user input to trigger a second seed_rng(). That should do it.




So far we’ve been using the most basic mapper, NROM. This is defined in the ines header in crt0.s, in the “HEADER” segment. That is actually importing a linker symbol from the .cfg file, and was zero. NROM is mapper zero. So, to change the mapper number, we change the .cfg file, at the bottom. NES_MAPPER, value = #.

Why change the mapper? Well, if we wanted more PRG space or more CHR, or more RAM, we would need a special cartridge that had those features.

It does that by taking the much larger ROM, and remapping a small piece of it to the CPU address $8000 (for example).

For C programming, it would be especially difficult to use most of the mappers. One function might expect another to exist and jump to it, except it’s not mapped into place…crashing the game.

Possibly, you could put data (not code) into several small chunks, and swap those into place as the game progresses. Another thing you could do is put the music data into alternate banks, and only put them in place when needed.

This is an advanced topic, and I won’t cover it as much as I should. Let’s discuss a few of the more common ones.

CNROM, allows you to change the entire graphics, between 4 options. (see examples below)

AxROM and UxROM have no CHR ROM. The graphics are in the (large) PRG ROM, and need to be loaded to the CHR RAM to be used. AxROM allows you to change the entire $8000-ffff banks where UNROM has $c000-ffff fixed, and allows you to change the $8000-bfff bank. I would prefer UNROM to AxROM, since you could put your C code in the fixed bank and swap data in and out. It would be very difficult to program a AxROM game in C, some ASM will be necessary.

AxROM is fixed mirroring to 1 nametable, but you could use the variation BNROM (Deadly Towers) which isn’t. Because the entire PRG ROM is changed, even the reset vectors, you need to have a reset vector in every set of banks, which should redirect you to the starting bank, if the user presses the RESET button.

In fact, never assume the startup state. The init code should explicitly put the correct initial banks in place before use. The user could press reset while the wrong bank is in place, for instance.

There is a homebrew version on UNROM, mapper 30, UNROM 256, which is much larger than any commercial game. NESmaker uses it. This might be useful for C programming.

Mojon twins made at least 1 game in C with standard UNROM…


For any mapper, you COULD specify that it has RAM at $6000-7fff, in the header. byte 10, bit 4. If you just start writing (reading) to this area, most emulators will assume a PRG RAM chip exists. But, if you want it battery backed (save RAM), you need to indicate it in the header, byte 6, bit 1.

GNROM, mapper 66 (or Wisdom Tree / Color Dreams, mapper 11) can swap the entire PRG and the entire CHR. Of course this presents the same problems as AxROM, getting one bank to call a function in another bank, and making sure the CRT library is available all the time.


More advanced mappers, like MMC1.

cppchriscpp uses MMC1 (SxROM) in his C project.


some of the bank switching code…


You can change the $8000-bfff areas. and you can change either tileset (ppu 0-fff or ppu 1000-1fff). and you can change mirroring from H to V. This is one of the most popular mappers.

And a bit more advanced, MMC3 (TxROM). You can change $8000-9fff, and/or $a000-bfff banks. You can change a smaller area of CHR ROM, as small as $800 sized, for animated backgrounds (waterfalls, etc). And you can use the scanline counter IRQ to do multiple background splits. However, the IRQ code needs to be written in ASM.


I made a simple CNROM example. There are 4 CHR files, and I’m simply swapping between them, and changing the palette.

CNROM has a technical problem, called bus conflicts. The mapper works by writing to the ROM, which if course you can’t do. If the byte at the ROM is different from the byte written, it might not work… so I made a const array, with values 0-3, and I’m simply writing the same value to the ROM value. I know technically, you’re not supposed to write to a const, but with a little trickery, it is easy. I’m using this POKE() macro:

POKE(address, value);

Which casts the address to a char * and then stores the value there.

Press start, the CHR changes (and the palette). It is entirely the POKE() statement that changes the CHR banks.

The corners are missing from the picture, because, I needed a blank tile for the rest of the BG, and the RLE compression required that I have 1 unused tile.






18. Sprite Zero

This one is a bit hard to explain. But SMB used it, so most people consider it a standard game element. When you have the top of the screen not scrolling, but the bottom of the screen scrolling, it’s probably a sprite zero screen split.

The sprite zero, is just the first Sprite in the OAM… addresses 0-3. The PPU marks a flag  (register $2002) the first time it sees the a non-transparent pixel of the zero sprite over a non-transparent pixel of the BG. We can look for this flag, and use it to time a mid-screen event, like changing the X scroll.

Waiting for this flag is wasted CPU time. It would be better to use a mapper generated IRQ, like MMC3 / MMC5 scanline counter or Konami VRC 2,4, or 6 scanline counter. Better, because the cartridge would count for you, and you don’t need to poll 2002 repeatedly for changes, and you can do multiple splits per frame.

But, I decided not to cover IRQs in this tutorial. You would need to learn ASM to use those, since IRQ code needs to be written in ASM.

Anyway. once it hits, you know the PPU is on a specific line on the screen, and you can change the scroll position.

Just writing to 2005 twice midscreen can only change the X scroll. This is just how the NES PPU works. You just can’t change the Y scroll by writing to the scroll register mid frame. But, you can change the X scroll. So, I changed the split function to only take 1 argument, X, to better reflect this limitation.

I want the top left screen to be the HUD, so we keep the regular scroll stuck at 0,0. When I set the regular set_scroll_x(0) and set_scroll_y(0), I just keep them at zero.

Then, first thing we do on each frame is poll for Sprite zero right away. We don’t want to miss it! It would crash the game. Send it the actual X. It will adjust the scroll mid screen.


We had to adjust the screen drawing code not to overwrite the top of the screen. Now we have a stable HUD that we can draw our stats to.





And, just to contradict myself, we actually can change the Y scroll midscreen with a complicated 2006 2005 2005 2006 trick. I’m doing this last (the bottom of the screen), and it’s more dangerous, because running past the end of the frame before running this function, and the whole game could crash, if it never finds the Sprite zero hit.

But, I wanted to show that it was possible, even if you should never use it. Perhaps for someone braver than me. Perhaps for the top of the screen in a vertically scrolling game.

Anyway, I made this function…


I had to make some changes to the platformer, since the entire screen is now aligned higher, so I had to adjust the y values of bg collisions. this is probably not the ideal setup, but I just wanted to demonstrate it. I’m putting the top of the screen at the bottom of the screen.

Here’s the example. I guess I should have used the vertical scrolling code to show this better. This could have been done with the regular split code.





And I was so worried about slowdown causing scrolling errors in the game, that I didn’t end up using the sprite zero hit in the final game, coming up later. These examples work fine, because there is not much game logic, but as soon as we add a few enemies and move them around and have to check collisions, the logic goes longer than 1 frame, and slowdown causes scolling errors on every 2nd frame.

It should be noted that Mojon Twins (na_th_an) uses this same sprite zero split in many of his games, and told me just refactor if scrolling problems happen. Split long tasks into 2 different frames. Check only half the collisions a frame, for example.


17. DPCM sound

This one is a bit tricky. DMC files are huge. You might want to avoid them altogether. Most games don’t use them.

However, you might want to put in a sound effect that sounds like a real thing, a voice saying one word “fight”, or a dog barking, or maybe some more realistic drums, or cool bass line.

Try to keep them very short, like 0.2 seconds. You can / should edit them down with a sound editor like Audacity. I’m using some royalty free samples.

The faster the frequency of the DMC sample, the more bytes of ROM it uses. Faster is higher quality… below rate A, the sound quality is terrible. Maybe split the difference and use C or D. I actually used rate F for mine, but I might have lowered that if I ran out of ROM space.

Famitracker can import the sample, and map them to a note. With famitone2, you must put the samples on instrument zero, and use note range C-1..D-6. Also, the instrument zero must have a volume sequence, even if you don’t use it (just a quirk of famitone2). That’s under 2a03 setting, instrument settings. Put a check mark next to volume (this is true for all instruments).


Even if you only want to use the sample as a stand alone sound effect, and not in the song, it must be included in the song like this.

Now, when you export the text it will have the dmc file defined. and when you use text2data it will output a dmc file. Include that in crt0.s in a “dmc” or “sample” or whatever, segment. I called it “SAMPLES”.

This is the tricky part. DMC samples must go between $c000 and $ffc0. preferably as far to the end as possible. Subtract the byte size of the samples from ffc0 and round down to the next xx40. In the cfg file, define the SAMPLE segment to start there.

Now, also, go to the top of crt0.s and define FT_DPCM_OFF to start at the same value.

The .dmc file is 5,248 bytes long. That’s rather large for a NES game. It will be ok for a simple example code, though.

Now, if the samples are in the music, they should play with the music.

But, if you wanted them to be sound effects, you have to call them in your code, like


How do we know what the sample number is? It depends on what note you mapped them to in your famitracker file. If you look at the output file from text2data (mine is “DMCmusic.s”), you see a samples area. You can tell by the non-zero lengths at the right side, that our samples are at 25, 27, 29, 30 and 32. It counts up from C1, so if we had mapped it to C1, it would be sample_play(1). But the sample I want is at G3, so we need sample_play(32).

I put this with a new jump. It’s just my voice, saying “jump”, to be silly. 🙂

Hope this makes sense.




16. Sound effects

Even if you have no music talent, you might be able to make some cool sound effects. Music is nice, but sound effects make if feel like a real game.

Again, open famitracker. You can use mostly all the fx and any notes. Put all the sound effects in 1 file, each as its own “song”. Add a song in module properties…


Try to write the music so pulse channel 1 or triangle play the main melody. And then use pulse channel 2 (or noise channel) for sound effects. That way they don’t collide. If you are having problems with sfx cutting out, you could also try to make the sound effects volume louder than the music (at least a little bit). I actually made my sfx quieter than the music, but louder than the Square 2 channel, where most of the sfx play.

They should be rather short. End every effect with C00, and put the C00 on its own line.

Save. Now, export to NSF file.


Open the command prompt and use nsf2data with the -ca65 option. I’m using famitone 2 v1.15. The sound effect code changed in the last update, so use 1.15 to make the data.

Include the sounds data in crt0.s under sounds_data:, and make sure FT_SFX_ENABLE is set at the top, and also that FT_SFX_STREAMS is 1. The init code will initialize our sound effects. Having 1 stream means that only 1 sfx can play at once.

We just need to call the sound effects like…
sfx_play(sfx,channel). Channel means stream, use channel = 0, since we have only 1 activated.

If you want 2-4 streams defined, you could set a channel to 1,2,3. Higher having higher priority. I would caution against having too many, they might conflict. I have used 2 before.

I made it so that jump calls sfx_play(SFX_JUMP, 0). B button plays a noise sfx, and Select button plays a “ding” sfx. I’m going to use that for coin collecting, later.

Start still changes the song.




15. Music

I wrote a page a while back about the NES Audio.


But, mostly you shouldn’t have to know that much about the sound registers. We are going to use Famitracker to write the music and Famitone 2 v1.15 to play the music. I have been including the famitone code in every example, so that it’s already in place for you. All you have to do is to include the music data file in crt0.s right below music_data:

I’m not the best famitracker musician, so maybe you should watch a tutorial about using it, like this one.


I like this tool chain, but famitone2 has some limitations.

  1. No volume column.
  2. Allowed notes are C-1..D-6, Note Cut
  3. Only Volume, Arpeggio, and Pitch sequences
  4. All instruments should have a volume envelope assigned
  5. no Duty sequence
  6. 64 instruments max
  7. no fx except Tempo Fxx, Looping backwards Bxx, and ending the frame early D00
  8. Up to 17 sub songs in a file

Because there is no volume column, you might want to make a few instruments of different max volume.

And a warning, don’t set ROWS = 256. The text2data program won’t work right.

Put every song into the same file, use “module properties” to add a song.


Once everything is done, export a txt file. You need to process this file with famitone2 program text2data.exe. Use the command line, and add the -ca65 switch so that our assembler won’t have any problems reading it. I left all the files in /MUSIC if you want to see what they look like.


I wrote 2 songs and imported them into the platformer game.

music_play(0) plays the first song.

music_play(1) plays the second song.

Press “start” to switch between the songs.

The neslib code automatically updates the audio registers to match the song. At the end of the nmi code, FamiToneUpdate is called, once per frame.

If you need to, you can pause the song music_pause(1) and unpause the song music_pause(0). And you can stop the song altogether music_stop().

Oh, and one more side note. I wrote a function that allows you to change the speed of the music with your code. Normally, you could only set the speed inside the famitracker file. But, what if you wanted to speed it up for a boss fight, or slow it down if you are in some stunned state? Well, now you can easily do that with this function…


Lower numbers mean faster, bigger means slower. 6 is the default.




On a side note, there are other music drivers.

Pently, has been used in a few games, and might be good for you if you like to write your music with a sheet music tool. It uses a descriptive language. Music Macro Language (MML) or LilyPond can be used.



ggsound is another options. NESmaker is using it. I am not familiar enough to give details.



The full famitracker driver is another option, but it’s very large, and a bit slower than other drivers. You can get it from shiru’s example file.


Or you could look at cppchriscpp’s example code, which uses it, I think (?).



I also wrote 2 unofficial updates to famitone, which I talk about here.





14. Platformer

Believe it or not, this is basically the same as the scrolling right code. What makes a platform game different? Gravity. And we need a 16 bit X and Y speed and position. The lower byte represents sub pixel positions. I believe it’s called fixed point math. (I even splurged, and used a signed int or 2, gasp!).

Anyway, for gravity, we add a little to the Y speed every frame. Not too fast, or we might fall right through a floor. So we have a max allowable speed.

And moving left and right I’m slowly accelerating, up to a maximum speed. These define statements in the .h file control all this physics. It should be easy to fine tune now. These are 16 bit values, where the low byte is sub-pixel. So the max speed is really 2.25.

#define ACCEL 0x20
#define GRAVITY 0x50
#define MAX_SPEED 0x240
#define JUMP_VEL -0x600
#define MAX_RIGHT 0xb000

And I didn’t want all the platforms to act like solid brick walls. I wanted to be able to jump upward into the platform, but it would catch your feet. So, I added a collision array, which defines how each metatile behaves.

#define COL_DOWN 0x80
#define COL_ALL 0x40

const unsigned char is_solid[]={

I had to hand edit these, which is a bit awkward.

The BG collision code parses the collision bits, and sends a collision signal, depending on the direction. The main movement code ignores the feet collision if Y speed is negative (rising)

if(BoxGuy1.vel_y > 0) {
BoxGuy1.vel_y = 0;

And only sets feet collisions if the feet are just barely inside the block.

if((temp3 & 0x0f) > 3) collision_D = 0;

This is why it’s important that Y speed down can’t exceed 3 pixels per frame. Any faster, and you might miss the floor hit.

So I made some new blocks in NES Screen Tool, and screenshot to GIMP, save as metatiles.png, import that as a tileset to Tiled. Make some rooms. Export to .csv. Convert to C array. Import to the C code. (easy, right?)


Now it’s starting to feel like a real game.




13. Scrolling up

This was much harder than scrolling right. If I had chosen to scroll downward, it might have been easier, because scrolling up is like going backwards in the code.

Skipping over the y values of 0xf0-ff wasn’t that bad as long as you use my functions add_scroll_y() and sub_scroll_y() that handles this for you. But, I also had to add them to the BG collision code, since you can be half in one nametable and half in another. And, the code assumes that Y position is between 0 and $ef.

Since scrolling up is going backwards, I’m starting at the maximum scroll position, and going backwards to 0.

I had to build the array of room arrays backwards too.

const unsigned char * const Rooms[]= {
Room5, Room4, Room3, Room2, Room1

Anyway, I made 5 more rooms, in Tiled, and exported 5 more csv files, converted to C arrays, and imported those into the code.


And after a few days of debugging (yikes) it finally works. I have to give some due respect to the guys who made games like Kid Icarus, or Metroid, or Ice Climber, because scrolling upward is not easy.