Button Combos, Sound Engines and Scopes

February 8th, 2010

It’s been a while since I posted here. I took a break from my homebrew to write some tutorials on how to code a sound engine for the NES. You can find them here: NES Sound Tutorials.

After a long break I finally got back to some homebrew coding. I worked in 6502 for a few hours today. I didn’t work on Explorer, but rather a different game project that is less ambitious. I’ll introduce the game properly in a future post.

What I Did Today

Button Combos

One thing that I needed for the new game project was a way to detect button combinations like up+A or right+B – the kind that you use to select plays in TecmoBowl. It was a little tricky to pull off. For one thing, if the player presses something like up+left+A, I need to resolve that to either up+A or left+A. I need to work that out for all possible combinations of button presses. This includes taking care of cases where A+B are pressed at the same time.

Another issue is with holding buttons. If the player holds B down and makes circles around the dpad, I only want it to catch the first combination. To do two combos in a row, they should release the B button and press it again. But what if the player hits up+B, and then while still holding B they press A+left? Does the holding of B stop the 2nd combination from being picked up or not? There are a lot of possible cases since the controller reading routine is called 60 times per second. The player can’t control their input on a frame-by-frame scale. Sliding from B to A might very well contain several frames (fraction of a second) where both buttons are held down before the B button is released. Not impossible to solve, but it wasn’t as straightforward as I had expected.

Sound Engine

Another thing I did today was port my sound engine to ca65. I wrote my NES sound tutorials for the NESASM assembler. My tutorials are a continuation of another set of tutorials which use NESASM and I wanted to stay consistent. Plus most new nesdevers start with NESASM as it is very newbie-friendly.

My tutorial sound engine was an improvement over the one I had previously written in ca65, so I wanted to replace the old with the new. So I spent some time today porting my sound engine from NESASM to ca65. I was sure everything was going to break as soon as I got all the syntax converted. But it didn’t! Once I got it to assemble it worked perfectly on the first try! That was a relief.

Scopes

ca65 lets you define scopes. Scopes enable you to keep parts of your program hidden from the other parts of your program. It’s good to separate modules, especially in large programs, so that you don’t have variable conflicts and the like. These bugs are the hardest to trace in assembly language.

I didn’t use scopes before because I didn’t really know how. But I found a great thread on nesdev about ca65 scopes that told me how to do it, so I spent some time today separating my sound and controller reading modules from the main program. Everything feels much … cleaner now. Like washing your hands after working outside on a summer day. I can physically feel how much easier things are going to be in the future for me with scopes.

New NES

I bought an NES! Ordered it on Yahoo Auctions on Saturday and it arrived at my house on Sunday! All I need now is a PowerPak and I can start testing my programs on real hardware. I can’t wait!

I’m too lazy to upload pictures here, but you can see the ones I posted to twitter here:

My new NES 1
My new NES 2

Explorer: 12 – Monster Art

August 17th, 2009

Took some time away from work and hobbies to spend some time with the family. Before I left I was working on adding some enemies into the game. I made three different monsters and added enemy-loading logic to the room-loading routines. The enemies display onscreen fine and die when you shoot their HP to 0. Tomorrow I’m going to work on some movement patterns.

I felt I should do some kind of update though, so here are the terrifying monsters I whipped up in GIMP. Turn on the lights before looking at them or you might die in your sleep:

  1. Purple Tongue Head
    When you see it coming, the shit runs down your leg.

    When you see it coming, the shit runs down your leg.

  2. Eyeball
    It's looking for something to KILL!

    It's looking for something to KILL!

  3. Shuriken
    It's pointy.

    It's pointy.

Explorer: 11 – Sobjects

August 6th, 2009

I haven’t posted in a few days and that’s because I’ve been spending my time doing research. I’ve been peeking at other games and seeing how they handle sprite objects. By sprite object, I mean entities in a game that are represented on screen with sprites: enemies, projectiles, powerups, etc. When I was trying to code bullets, I didn’t really know how to go about it. Should I keep them separate from other sobjects (sprite objects) or are there enough similarities to lump them together?

If you think about it, a bullet isn’t much different from an enemy. It has an x and a y. It has a speed and a movement pattern. It has a palette. It has a hit box. The main difference is what you check for collision against. Enemies collide with the hero. Hero bullets don’t. They collide with enemies instead.

So some logic is different, but the data (or rather type of data stored) is the same! As far as turning the sobject data into actual sprites, bullets can be treated just the same as enemies (the hero too). Why do I care? If I am able to lump them all together, I can make all the sprites in a single loop. Here’s an example of what I mean:

Sobjects to Sprites

Let’s say I have a hero. That’s one sobject. He can shoot bullets. Let’s say I want to allow 3 bullets maximum on the screen at a time. That’s three more potential sobjects. Then enemies. Just pulling a number out of the air, lets say I want there to be 10 enemies on the screen at a time maximum. That’s ten more potential sobjects.

1 hero + 3 bullets + 10 enemies = 14.

So I have 14 sobjects that could be represented on the screen at any one time. If I treat them all the same, I can hold all of the data in arrays, like this:

sobj_id: .res 14
sobj_hp: .res 14
sobj_x: .res 14
sobj_y: .res 14
sobj_hitbox_top: .res 14
sobj_hitbox_bottom: .res 14
...etc

Then whenever I need to turn them into sprites, I can just loop through them all using an index register:

sobjects_to_sprites:
    ldx #$00
@loop:
    lda sobj_id, x
    ;do stuff
    ;calculate y, CHR#, attrib and x
    ;for each sprite of the sprite object
    ;and store in DMA sprite RAM

    inx
    cpx #.sizeof(sobj_id) ;loop through all 14
    bne @loop
    rts

And that will cover all my sobjects as far as turning their data into sprites. I don’t need to write more than one routine!

To differentiate between sobject types (bullet vs. enemy vs. hero), I can just have their index range set. For example, hero is always index 0. Bullets are always 1-3. And enemies are always 4-13. This way I always know what to test for collisions against: enemies will always test against index 0 (hero) and deal damage on a collision. Enemies will also test against index 1-3 (bullets) and receive damage on a collision.

With defined index ranges, limit testing is easy too: If the player presses the fire button, check sobjects 1-3. If they are full already, don’t create a new bullet. If there is an open space there, create a new bullet.

Conclusion

I think I finally figured out how I’m going to arrange sprite objects. Today I rewired all of my previous hero-moving code to fit into this new data model and I think I have it working. Tomorrow I’m going to try to add bullets for real!

Explorer: 10 – Refocus

August 1st, 2009

I originally started working on this game as an entry for a coding competition. The genre was puzzle games and I thought a switch-throwing maze game would be fun to write. I missed the deadline for the contest long ago but I kept working on the game anyway. Now I’m thinking about taking the game in a new direction.

The decision to make a maze-only game was made because there was a deadline, and because the genre for the contest was “puzzle”. But now that I have as much time and freedom as I want, I think I’m going to expand the game beyond just finding your way through a maze. Specifically, here are some things I want to add that weren’t in the original plan:

  1. Enemies and bosses
  2. Weapons
  3. A way to die (ie, health bar)
  4. A way to improve (more weapons. powerups… level ups?)

In addition to these changes, I’m also going to change the setting and storyline completely. No more treasure hunting archaeologist. I haven’t worked out all the details but I think it’s going to be somewhat sci-fi, with the hero as a cyborg (ie, guns not swords). I think using the Guardian Legend girl as my test sprite has influenced me in some way. :).

Anyway, this comes at just the right time. I just got switches and doors working and the next thing I was going to write was a way to break the breakable blocks. In the original maze-game concept there was going to be an item (like a hammer) that the archaeologist hero would find to allow him to break blocks. Now I think it will be a powerup that makes your gun blast stronger.

Next objective: make the hero shoot a projectile when pressing A.

Explorer: 10 – Sprite Collision

July 29th, 2009

In the last post, I got the hero sprite moving. But there’s a problem: she can walk through walls. I need to add collision detection with background tiles. Collision detection with the background can be summed up like this:

if the player tries to move:
    check the space they want to move to
    if that space is solid/blocked:
        don't move
    else:
        move

The looks pretty easy, but it can actually be quite complicated. Here are some issues:

  1. The hero sprite has x and y coordinates, which are on the pixel level. My room tile data is stored in ram on the metatile level. We need to make a conversion there.
  2. There isn’t any one point on the hero that is a catch-all for movement checks. If the player tries to move left, we will want to check for a collision with the left side of the hero. If the player tries to move right, we want to check for a collision with the right side of the hero. So we will need to make a hit box.
  3. Each side of the hit box will have a length > 1, so we may have to check for a collision with more than one background tile. For example, say the player wants to move right. We will check using the right side of the hit box. But it’s possible that the top half of the hit box will be adjacent to one tile, while the bottom half is adjacent to another.
    If we only checked the top-right corner of this hit box for collision, it would show the way as clear.  But it really isn't, because the bottom half of the hit box collides with a solid tile.

    If we only checked the top-right corner of this hit box for collision, it would show the way as clear. But it really isn't, because the bottom half of the hit box collides with a solid tile.

Step 1

First thing I want to do is make a hit box. I’m going to put it around the hero sprite’s feet. I define where the edges are relative to the hero’s X/Y coords, then make a subroutine to calculate the box every frame:

;collision box for the hero sprite (box around the feet)
HERO_MOVEMENT_BOX_TOP = 26
HERO_MOVEMENT_BOX_BOTTOM = 31
HERO_MOVEMENT_BOX_LEFT = 5
HERO_MOVEMENT_BOX_RIGHT = 11

hero_box: .res 4 ;top bottom left right

set_hero_box:
    lda hero_x
    clc
    adc #HERO_MOVEMENT_BOX_LEFT
    sta hero_box+2
    lda hero_x
    clc
    adc #HERO_MOVEMENT_BOX_RIGHT
    sta hero_box+3
    lda hero_y
    clc
    adc #HERO_MOVEMENT_BOX_TOP
    sta hero_box
    lda hero_y
    clc
    adc #HERO_MOVEMENT_BOX_BOTTOM
    sta hero_box+1
    rts

Movement within a metatile

Since every metatile is 16 pixels wide and 16 pixels tall, I can take a shortcut if I determine that the player is not at the edge of a tile. Check out these two cases:

We don't need to check for a collision in the left case.  The player is already on a walkable tile, and will remain on that tile if they move a pixel to the right.

We don't need to check for a collision in the left case. The player is already on a walkable tile, and will remain on that tile if they move a pixel to the right.

Let’s assume the player is trying to move right. The player is on a walkable tile in both cases. In the first case, they are in the middle of the tile. In the second case they are at the edge. We only need to check for a collision in the second case. Checking the first case would be a waste of time, because we’d be checking the tile the player is already on for walkability, but we know it must be walkable since the player is already on it. So right away we can skip over a collision check if we determine the player to be in the middle of the tile (ie, not on the edge).

This is very easy to pull off with 16×16 metatiles. In all cases, the left edge of a metatile will have an x-coord of $x0, and the right edge will be $xF. The top edge of a metatile will have a y-coord of $x0 and the bottom will be $xF. So in our collision detection routines, we can do something like this:

can_move_right:
    ldx hero_box+3 ;right edge of movement box
    inx ;we want to peek at the next pixel over
    txa

    and #$0F ;isolate right nibble,
         ; tells us where we are WITHIN a tile

    bne @move_ok ;not on the edge.  movement within current
                 ;square OK (in other words, if the right
                 ;nibble is 0, we are on the left edge of the
                 ;NEXT tile, and therefore need to check
                 ;for collision)

    ;... check for collisions

@move_ok:
    sec  ;return a 1 if movement is OK
    rts

I use a similar check at the beginning of can_move_left, can_move_up and can_move_down.

How many checks?

Do I need to check one bg tile for collision or two? It depends on the hero sprite’s position. Imagine the player is moving right again. If the top and bottom edges of the hit box are both within the boundaries of a single tile, we only need to check one bg tile for collision. But check this picture (should look familiar):

moving right, the top and bottom edges of the hit box touch two different bg tiles.  We need to make two checks.

moving right, the top and bottom edges of the hit box touch two different bg tiles. We need to make two checks.

In this case, the top and bottom edges of our hit box line up with two different bg tiles. So we need to check both. If either of them are unwalkable, we don’t allow movement.

So, two checks or one check? There are a couple of ways to determine if the top and bottom edges of our hit box touch different tiles. I do it this way:

    ;find how many tiles to check (1 or 2)
    lda hero_box ;top edge of movement hit box

    ora #$F0 ;we are going to add the box height,
             ;so set us up to check for a FF->00 transition

    adc #HERO_MOVEMENT_BOX_HEIGHT ;negative means our box is
                                  ;h-aligned with one tile.
                                  ;positive = 2 tiles
    bmi @not_two

    ;... check a tile

@not_two:
    ;... check a tile

I do similar tests for the other directions, but for can_move_up and can_move_down I will check the left and right edges instead of the top and bottom edges.

Hero pixel coords to a room coords

I need to turn the hero’s pixel coordinates into room coordinates so that I can find which bg tiles to check. Here’s my subroutine to do that:

;------------------------------
; set_hero_map_coords finds the x and y room coords for the 
; topleft pixel of the player's movement hit box
set_hero_map_coords:
    lda hero_box+2 ;left
    ldx #$00
    sec
:
    sbc #$10
    bcc :+
    inx
    jmp :-
:
    stx hero_map_x

    lda hero_box ;top
    ldx #$00
    sec
:
    sbc #$10
    bcc :+
    inx
    jmp :-
:
    dex
    dex ;correct y for the status bar
    stx hero_map_y
    rts

Once I have the hero’s room coordinates, I can add to or subtract from them to find the coordinates for the adjacent tiles I want to check for walkability.

Walkability

How do I check for walkability? With a lookup table:

;tile ids
.enum
    floor
    wall
    block
    water
    block_breakable
    stairs_up
    stairs_down
    pitfall
.endenum

.enum ;walkability
    unwalkable
    walkable
.endenum

tile_walkability:
    .byte walkable, unwalkable, unwalkable, unwalkable
    .byte unwalkable, walkable, walkable, walkable

I read a tile id from the room map in RAM and use it to index into the tile_walkability table.

Here’s a simplified can_move_right. (I took out checks for room boundaries to make it more readable):

can_move_right:
    ldx hero_box+3 ;right edge of movement box
    inx
    txa

    and #$0F ;isolate right nibble, where are we WITHIN a tile?

    bne @move_ok ;not on edge. move within current square OK

    ;how many tiles to check (1 or 2)
    lda hero_box ;top edge of movement box
    ora #$F0
    adc #HERO_MOVEMENT_BOX_HEIGHT
    bmi @not_two

    ldy hero_map_y
    iny
    ldx hero_map_x
    inx
    jsr get_room_offset ;takes x/y room coords and returns an
                        ;array index in y

    lda room, y
    tay
    lda tile_walkability, y
    beq @no_move

@not_two:
    ldy hero_map_y
    ldx hero_map_x
    inx
    jsr get_room_offset

    lda room, y
    tay
    lda tile_walkability, y
    beq @no_move
@move_ok:
    sec return 1 in the carry if we can move
    rts
@no_move:
    clc return 0 in the carry if we can't move
    rts

I have seperate routines for the other 3 directions. They are all very similar. The last step is to update my move_hero subroutine to call these collision detection routines before moving, and then skip movement on carry clear.

Conclusion

Now I have a sprite that changes direction, moves, animates and bumps into walls. Here’s the latest video demo:

Explorer: 9 – Sprite Movement

July 26th, 2009

Ok, I got the hero to change directions based on user input. Now it’s time to move her. The first step for this is to have a hero_moving flag that the input handler will set if there is d-pad input:

hero_moving: .res 1
handle_joypad:
    lda joypad1
    and #$F0
    beq @end
    lsr
    lsr
    lsr
    lsr
    tay
    lda direction_change_table, y
    sta hero_direction
    lda #$01
    sta hero_moving
    rts
@end:
    lda #$00
    sta hero_moving
    rts

With this updated input handler, the hero_moving flag will be 1 when the d-pad is pressed, and 0 when it is not. And as before, our hero’s direction will be stored in hero_direction.

Next, I need to check the hero moving flag in my update_hero_sprite routine, which is called every frame:

update_hero_sprite:
    lda hero_moving
    beq @hero_moving_done

    jsr move_hero
@hero_moving_done:
    ;...
    ;write sprite data to RAM as before

Now that I have the foundation laid, I need to write the move_hero routine.

move_hero

There are 8 possible directions the hero could be facing. The current direction is stored in a variable called hero_direction. The possible values for this variable are 0-7, as assigned by these constants:

;direction indexes for tables
SPRITE_UP =         $00
SPRITE_DOWN =       $01
SPRITE_LEFT =       $02
SPRITE_RIGHT =      $03
SPRITE_UP_LEFT =    $04
SPRITE_UP_RIGHT =   $05
SPRITE_DOWN_LEFT =  $06
SPRITE_DOWN_RIGHT = $07

I need to alter the hero’s coordinates based on the direction the player is moving. If they are moving left, I need to subtract from hero_x. If they are moving right, I need to add to hero_x. If they are moving up, I need to subtract from hero_y. If they are moving down, I need to add to hero_y. If they are moving diagonally, I need to update both hero_x and hero_y. There are many possibilities, and rather than have a million branch instructions, I’ll use table lookups again. I will have one table for horizontal movement and one table for vertical movement. I will index into these tables using hero_direction. The tables look like this:

;up, down, left, right, up_left, up_right, down_left, down_rt
hero_movement_x:
    .byte $00, $00, $FF, $01, $FF, $01, $FF, $01

hero_movement_y:
    .byte $FF, $01, $00, $00, $FF, $FF, $01, $01

My move_hero routine will read from these tables and add to the hero coordinates. Note that adding $FF to a number (on an 8-bit system) is the same as subtracting 1, since it will wrap around from $FF to $00. Here is move_hero:

move_hero:
    ldy hero_direction
    lda hero_movement_x, y
    clc
    adc hero_x
    sta hero_x

    ldy hero_direction
    lda hero_movement_y, y
    clc
    adc hero_y
    sta hero_y

    rts

And now she’s moving.

miau pointed out in a comment that diagonal movement should really alter x and y by SQRT(2) rather than 1 (see Pythagorean Theorum). This is something I didn’t consider before, so my hero covers ground a little more quickly when moving diagonally. I’m not sure yet if this is undesirable behavior or not. If I keep it a simple maze-solving game, it probably won’t be an issue. If I get more ambitious and change it to a more action-oriented game with enemies (something I’ve been seriously thinking about), it may be an issue. We’ll see :).

Animation

I want to talk very briefly about animating the sprite. To do animation, I need a few things:

  1. Graphics for the various frames of animation
  2. A counter to tell me when to change animation frames
  3. A variable telling me the current animation frame

I already have the graphics for my test sprite. The other two I need to make myself.

frame_counter: .res 1
hero_anim_frame: .res 1

The animation is a walking animation, so I don’t want the hero to animate unless she is moving. It makes sense then to do the animation frame-changing logic in the move_hero routine. The Guardian Legend hero sprite has a 4-frame walking animation, so here’s how I do it:

move_hero:
    ldy hero_direction
    lda hero_movement_x, y
    clc
    adc hero_x
    sta hero_x

    ldy hero_direction
    lda hero_movement_y, y
    clc
    adc hero_y
    sta hero_y

    inc frame_counter
    lda frame_counter
    cmp #$0B ;change anim frame every 11 "moving frames"
             ;found this number by trial and error
    bcc @end

    lda #$00
    sta frame_counter ;reset counter
    inc hero_anim_frame ;go to next anim frame
    lda hero_anim_frame ;make sure we stay between 0 and 3
    and #$03
    sta hero_anim_frame
@end:
    rts

Then I will modify my CHR tile lookup tables to handle graphics for all four frames of animation for all 8 directions. Then I will update my update_hero_sprite routine to read from these tables based on the values of hero_anim_frame and hero_direction. I’m not going to post the code, because it’s a little long and there are a lot of tables. If anybody wants me to elaborate more, let me know in the comments :)

BTW, before I forget! When adding new variables, it’s a good idea to initialize them. Here is my updated initialize_hero_sprite routine:

initialize_hero_sprite:
    lda #$50
    sta hero_x
    sta hero_y

    lda #$00
    sta hero_moving
    sta hero_anim_frame
    sta frame_counter

    lda #SPRITE_DOWN
    sta hero_direction

    jsr update_hero_sprite

    rts

Conclusion

Whew. I covered a lot of ground today. I probably should have made this two posts instead of one, but I want to hurry up and get to collision detection so I can put up the next demo video. :)

You may have noticed by now that I use hero_direction a lot to index into lookup tables. This is because everything changes based on the hero’s direction, and lookup tables are a great alternative to long sections of compare/branch code. Often when I find myself writing a lot of branching code I’ll see if I can come up with some scheme to turn the test value into a table index.

See you next time!

Explorer: 8 – Sprite Direction

July 24th, 2009

Last time I wrote code to put a hero sprite onscreen. In my first (pre-sprite) video demo, I had room changes triggered directly by player input. Today I’m going to recode the input handler to alter the hero instead, specifically the hero’s direction.

Joypad revisited

I posted my joypad reading code in a previous post, but here it is again for easy reference:

update_joypad_data: ;props to blargg for A-only joypad read.
    lda joypad1
    sta joypad1_old
    lda #%01111111
    sta joypad1
    sta $4016
    asl a
    sta $4016
@loop:
    lda $4016
    and #$03  ;props to Disch for Famicom support
    cmp #$01
    ror joypad1 ;right, left, down, up, start, select, B, A
    bcs @loop

    lda joypad1_old
    eor #$FF
    and joypad1
    sta joypad1_pressed ;this tracks off-to-on transitions.

    lda joypad1
    eor #$FF
    and joypad1_old
    sta joypad1_released ;this tracks on-to-off transitions
    rts

Before, I was checking joypad_pressed to determine whether or not to change a room. This was so that if the player held down a button, it would only change rooms once (instead of once per frame held). But now that I’m going to be using input to control the sprite, it makes more sense to check joypad1 and use every frame’s input. If the player holds down the d-pad, the sprite should keep moving.

But I’m not quite ready to move yet!

Changing Direction

I want to rewrite my input handler so that it takes d-pad input and uses it to set the hero’s direction. This sounds pretty straightforward, but there are some special cases I need to be wary of: what happens if the player presses left+right? or up+down? This isn’t likely to happen on a real controller, but most people play Nintendo games on emulators these days. If you don’t protect against these strange key combinations, you open yourself up to some pretty bizarre glitches, like the Zelda 2 acceleration glitch (commentator talks about it around the 4:20 mark):

I’m going to work around this problem by assigning a single direction to these weird combinations. But first we need to look at our input. In my joypad reading routine above, I store the button states in a variable called joypad1. The left 4 bits of joypad1 will hold the d-pad states and the right 4 bits will hold the states of the other four buttons. First I want to isolate the d-pad bits:

    lda joypad1
    and #$F0
    beq @end
    lsr
    lsr
    lsr
    lsr
    ;now the d-pad button states are in the right nibble.
    ;do change direction stuff here.
@end:
    rts

The right nibble of the A register now holds the d-pad button states. Next I will build a look-up table, assigning a direction to each possible combination of d-pad presses. Let’s look at the combinations. There are sixteen possibilities in all:

0000xxxx
    ||||
    |||+--up
    ||+---down
    |+----left
    +-----right

0000 = no arrows pressed (will never happen)
0001 = up
0010 = down
0011 = up+down
0100 = left
0101 = left+up
0110 = left+down
0111 = left+up+down
1000 = right
1001 = right+up
1010 = right+down
1011 = right+up+down
1100 = right+left
1101 = right+left+up
1110 = right+left+down
1111 = right+left+down+up

The highlighted ones are the problem combinations. I will need to assign a single, specific direction to them. For example in the case of right+left, I will just choose one: left. Let’s turn this into a lookup table. Recall that I have a set of constants assigning a value to each direction (for indexing into CHR lookup tables among other things):

;direction indexes for tables
SPRITE_UP =         $00
SPRITE_DOWN =       $01
SPRITE_LEFT =       $02
SPRITE_RIGHT =      $03
SPRITE_UP_LEFT =    $04
SPRITE_UP_RIGHT =   $05
SPRITE_DOWN_LEFT =  $06
SPRITE_DOWN_RIGHT = $07

Now I will make a lookup table assigning these constant values to the various button combinations:

direction_change_table:
    .byte $FF               ;0000 dummy value
    .byte SPRITE_UP         ;0001, up
    .byte SPRITE_DOWN       ;0010, down
    .byte SPRITE_UP         ;0011, up+down
    .byte SPRITE_LEFT       ;0100, left
    .byte SPRITE_UP_LEFT    ;0101, left+up
    .byte SPRITE_DOWN_LEFT  ;0110, left+down
    .byte SPRITE_UP_LEFT    ;0111, left+up+down
    .byte SPRITE_RIGHT      ;1000, right
    .byte SPRITE_UP_RIGHT   ;1001, right+up
    .byte SPRITE_DOWN_RIGHT ;1010, right+down
    .byte SPRITE_DOWN_RIGHT ;1011, right+up+down
    .byte SPRITE_LEFT       ;1100, left+right
    .byte SPRITE_UP_RIGHT   ;1101, left+right+up
    .byte SPRITE_DOWN_RIGHT ;1110, left+right+down
    .byte SPRITE_DOWN_LEFT  ;1111, left+right+up+down

Now all button combinations have a single direction associated with each of them. All that I have left to do is read from this table and set the hero’s direction, like so:

handle_joypad:
    lda joypad1
    and #$F0
    beq @end
    lsr
    lsr
    lsr
    lsr
    tay ;right nibble has the d-pad button states. use as index
    lda direction_change_table, y
    sta hero_direction
@end:
    rts

Changing the sprite

The rest of the work is already done for me. I already have a routine update_hero_sprite (see last post) that takes hero_direction and uses it to index into some CHR lookup tables. I don’t have to change anything to get the new sprites to display. It works! (you can see the input in the bottom left of each picture):

If I press up, the sprite faces up.

If I press up, the sprite faces up.

Pressing down+right makes her face southeast

Pressing down+right makes her face southeast

Left+Right gets mapped to left.

Left+Right gets mapped to left.

up+down+left+right

up+down+left+right

Conclusion

My hero sprite is now capable of looking in 8 directions. I use a lookup table to assign a specific direction to each possible d-pad button combination. The next step is to actually move her in the direction she is facing. And when she is moving, I will want to animate her. Stay tuned!

Explorer: 7 – Sprite Time

July 23rd, 2009

Now that I have some test rooms and can navigate between them, it’s time to stick a sprite in the game. I couldn’t draw a rock to save my life, much less a cool character sprite, so for now I am going to rip one from another game to use for testing. Here she is:

She's from The Guardian Legend.

She's from The Guardian Legend.

This is the sprite from The Guardian Legend. I chose her as my test sprite for a few reasons:

  1. Her dimensions. She is 16×32, which is the size I want for my game’s hero sprite.
  2. Her proportions. Specifically her feet. I have narrow 16 pixel passages that the player will need to fit through. I want to allow a small amount of left-to-right and up-to-down movement within those 16 pixel hallways. If the sprite is too fat it will look like they are stomping on the walls.
  3. Her directions. She can face 8 different directions, which is what I want for my game.
  4. Her animation. She has a 4-frame animation that looks smooth and is CHR-efficient. Something I want to imitate.

Getting a sprite onscreen

First things first I need some variables for the hero. Right off the bat I know I will need to track her coordinates and direction:

.segment "ZP": zeropage
hero_x: .res 1 ;based on top left of sprite
hero_y: .res 1
hero_direction: .res 1

Next I will need to initialize those variables. This subroutine will be called when the game engine is loaded:

;direction indexes for tables
SPRITE_UP =         $00
SPRITE_DOWN =       $01
SPRITE_LEFT =       $02
SPRITE_RIGHT =      $03
SPRITE_UP_LEFT =    $04
SPRITE_UP_RIGHT =   $05
SPRITE_DOWN_LEFT =  $06
SPRITE_DOWN_RIGHT = $07

initialize_hero:
    lda #$50    ;place her somewhere on the map
    sta hero_x
    sta hero_y

    lda #SPRITE_DOWN
    sta hero_direction

    jsr update_hero_sprite

    rts

The hero will have a different appearance based on the direction she is facing. I will have lookup tables to find which CHR tile number to use. I index into these tables with a direction index. Those constants at the top define the direction indexes (indices? whatever).

update_hero_sprite is a routine that will be called every frame. It’s job will be to calculate the sprites’ x, y, tile number and flip/palette settings and store them in RAM. Later, in the NMI we will copy those values to the PPU (Picture Processing Unit) using DMA transfer.

Speaking of which, the hero sprite is actually made up of 4 sprites. On the NES, you have a choice between 8×8 sprites and 8×16 sprites. I will be using 8×16 sprites. The hero is 16×32, which is 4 8×16 sprites:

This character sprite is actually made up of 4 8x16 sprites

This character sprite is actually made up of 4 8x16 sprites

So let’s get her on the screen:

update_hero_sprite:
    lda hero_direction
    tax       ;we use this index to read from tables

    lda #hero_top_left  ;sprite number.
    asl
    asl     ;each sprite has 4 bytes of data
    tay     ;we use this index to write sprite data to RAM

    ;sprite data is stored, in order: y, tile #, attrib, x
    lda hero_y
    sta sprite_RAM, y

    lda hero_x
    sta sprite_RAM+3, y

    lda sprite_tiles_top_left, x
    sta sprite_RAM+1, y

    lda hero_sprite_flips, x  ;right, up_right and down_right 
                              ;are just flips of left, up_left
                              ;and down_left. Flip values are
                              ; stored in a table
    sta sprite_RAM+2, y

    lda #hero_top_right    ;top right, sprite #
    asl
    asl
    tay

    lda hero_y
    sta sprite_RAM, y

    lda hero_x
    clc
    adc #$08    ;8 pixels to the right of the top left sprite
    sta sprite_RAM+3, y

    lda sprite_tiles_top_right, x
    sta sprite_RAM+1, y

    lda hero_sprite_flips, x
    sta sprite_RAM+2, y

    lda #hero_bottom_left    ;bottom left, sprite #

    ....
    ;etc.  add 16 to hero_y for the bottom two sprites

    rts
    

And in the NMI:

    ;sprite DMA transfer
    bit $2002
    lda #$00
    sta $2003
    lda #>sprite_RAM
    sta $4014
    

And she’s on the screen!

She's wearing green today.

She's wearing green today.

Conclusion

Today’s post was short and sweet. Getting the hero sprite on the screen was pretty easy. My next step is to change her direction based on joypad input. See you then!

Explorer: 6 – Navigation and Input

July 21st, 2009

Now that I have the ability to make some rooms, and connect them together into floors, it would be nice if I had some mechanism to go from one room to another. To do this, I will need some subroutines that will change the room coordinates in RAM and then load the new room. This is really easy to code:

move_east:
    ldx floor_roomx
    inx
    ldy floor_roomy
    jsr floor_load_room ;this subroutine takes coords in x and
                        ;y and loads the room at those
                        ;coordinates (within the same floor).
    rts

move_west:
    ldx floor_roomx
    dex
    ldy floor_roomy
    jsr floor_load_room
    rts

Subroutines for moving north and south look similar. But there’s room for improvement here. Notice that I load the new room coordinates into x and y in both subroutines. I can save some bytes if I shorten it up a little bit:

move_west:
    dec floor_roomx ;current room x coord for the floor
    jmp :+
move_east:
    inc floor_roomx
:
    ldx floor_roomx
    ldy floor_roomy
    jsr floor_load_room
    rts

If I really wanted to I could probably replace that JMP instruction with a BPL (branch if positive) and save an extra byte. I’ll leave it how it is for now for readability. I’ll save optimizations for the very end if I need them.

Changing Floors

Changing floors isn’t much harder. First I’ll have to load the new floor, and then I’ll have to load a room within that floor. Good thing I have the load_floor and load_room subroutines already written. Having a good foundation to build upon makes things easy:

floor_down:
    dec map_floor ;this var holds the current floor.
    jmp :+
floor_up:
    inc map_floor
:
    lda map_floor
    jsr load_floor ;loads the floor, setting up room ptrs, etc
    ldy floor_roomy
    ldx floor_roomx
    jsr floor_load_room
    rts

Floor Boundaries

The thing I need to watch out for now is the floor boundaries. I don’t want to call move_west when I’m currently at x=0 or my game will try to load a room at x=FF, which probably isn’t there. When the game tries to move west, I will want to check if x==0 or not. If it is, I will skip the call. If the game tries to move east, I will want to check if x is equal to floor’s x-dimension – 1. If I’m in the eastern-most room, skip the call. Likewise for moving downstairs or upstairs. I will want to check the current floor number against 0 or the top floor number, respectively.

Triggering a Room Change

I have everything set up to change rooms. Now I need something to trigger the room changes. Most games trigger room changes based on sprite position/collision. If the user moves their character sprite to the edge of the screen, change the room. I haven’t coded sprite-support in yet, so for testing purposes I’m going to trigger room changes directly to the input. Pressing right will move east. Pressing down will move south. Pressing left will move west. Pressing up will move north. I’ll use B and A for going downstairs and upstairs.

Reading Input

First I need a joypad reading routine. The one I’m using is based off a really cool one that blargg posted on a nesdev thread. It preserves both x and y.

update_joypad_data: ;thanks to blargg for this A-only joypad
                    ;read routine.
    lda joypad1
    sta joypad1_old  ;save previous joypad data
    lda #%01111111
    sta joypad1
    sta $4016
    asl a
    sta $4016
@loop:
    lda $4016
    and #$03  ;props to Disch for Famicon support
    cmp #$01
    ror joypad1 ;right, left, down, up, start, select, B, A
    bcs @loop

    lda joypad1_old
    eor #$FF
    and joypad1
    sta joypad1_pressed ;this tracks off-to-on transitions.

    lda joypad1
    eor #$FF
    and joypad1_old
    sta joypad1_released ;this tracks on-to-off transitions
    rts

For changing rooms I will want to check joypad1_pressed. This variable tracks off-to-on transitions for the buttons. Using joypad1_pressed instead of joypad1 ensures that I will only move once per button press.

The joypad reading routine is called once per frame. There are many frames in a second. If the player presses up for a second, the variable joypad1 will report an up press for each frame the button was held. That’s a lot of ups. joypad1_pressed will only report one up press – the first one. I only want to move once per button-press, so I’ll check my input using joypad1_pressed.

So I read the joypad, then I perform actions based on the input. If left was pressed I’ll check to make sure that our room x-coord isn’t 0, and then I’ll call move_west. If up was pressed I’ll check to make sure our room y-coord isn’t 0, then call move_north if it isn’t. ETC..

Take a look

I made a demo video showing room navigation. I hope to make several videos like this as I code the game. I think it will be cool to document the making of an NES game like this. Anyway, take a look:

Conclusion

Room navigation works great. The next step is to put a movable sprite into the game and have room changes triggered by that sprite’s coordinates. Then it will start to look like a real game!

Explorer: 5 – Walls Again

July 17th, 2009

In my first post about Explorer’s room data format, I said that I used 4 bytes to store the wall/gap information for each room. After some thinking, I realized that this was wasteful, as rooms will share wall data with their neighboring rooms. For example, look at these two rooms:

These two rooms share a wall.

These two rooms share a wall.

They share a wall. The south wall of the top room is the same as the north wall of the bottom room. With my old format, I’d be storing the data for this wall twice: once in the data for the top room and once in the data for the bottom room. Not very efficient. If you imagine a 3×3 (9-room) floor you can see that the room in the middle will share ALL of its walls! Yet here I am wasting 4 bytes of ROM space to declare them for that room.

I was going to hold off on fixing this until later in the project, but Roth left a comment with a great idea for a solution. Here’s what he said:

About the data redundancy deal, I’m not quite sure how this could be approached off the top of my head, but what about making a separate map? For instance, I would guess that you have an overall table map that describes what room is what:

.db $30,$31,$20

or whatever. What if there was a second map, but it was a mapping of the openings?

.db %00100100, %00011000, %00011000, %00011000

So when you go into whatever room, read from that offset and subtract/add to get to be able to get all four sides maybe?

This idea of separating the wall data completely from the room data was just what I was looking for! Each floor would have a lookup table of wall bytes, and I’d index into it based on my room coordinates. I worked it out on paper to see what kind of savings I could get and the difference was huge.

Yes, these are my actual notes.

These are my actual notes. Look at the savings!

God forbid I ever make a floor with 400 rooms, but if I did I’d save myself 840 bytes on the wall data! Assuming a square floor where “x” is the length of each dimension, the old method uses 4x^2 bytes to store all of the wall data. The new method uses 2x^2 – 2x. In other words, take 4x^2 and cut it in half, then subtract more! 50%+ savings. Thanks Roth!

This method saves me on bytes in two ways:

  1. redundant wall bytes – each wall is declared one time instead of two times.
  2. perimeter walls – since lookups are based on room coordinates, I can assume a solid wall if x=0 or y=0 or x=max_x or y=max_y. I don’t have to store any perimeter walls!

My test data has 3 floors. Each floor is 3×3 rooms. My wall data dropped from 108 bytes to 36 bytes! :)

Implementation

I found that it was less headache to calculate indexes if I separated East-West walls from North-South walls and made two lookup tables for each floor.

Click to enlarge.

Click to enlarge.

The cost of this approach is that I have to store pointers to two tables per floor instead of one, but I think the tradeoff is worth it at this stage.

Implementing this couldn’t be easier. First I add wall table pointers to my floor data:

;----------------
; floor data
floor_map0:
    .byte $03, $03 ;dimensions of floor
    .word floor0_ew_walls ;ptr to ew wall lookup table
    .word floor0_ns_walls ;ptr to ns wall lookup table
    .word f0_r00, f0_r10, f0_r20 ;ptrs to room data
    .word f0_r01, f0_r11, f0_r21
    .word f0_r02, f0_r12, f0_r22

Next I update my load_floor routine to read these new pointers and store them in RAM:

;----------------
; load_floor expects the floor number in A
load_floor:
    sta map_floor   ;current floor
    asl
    tay
    lda map_ptr   ;this is a pointer to the floor lookup table
    sta temp_ptr2
    lda map_ptr+1
    sta temp_ptr2+1

    lda (temp_ptr2), y   ;get the pointers to the floor data
    sta floor_ptr
    sta temp_ptr1
    iny
    lda (temp_ptr2), y
    sta floor_ptr+1
    sta temp_ptr1+1

    ldy #$00     ;now let's read and set the floor's dimensions
    lda (temp_ptr1), y
    sta floor_dim_x
    iny
    lda (temp_ptr1), y
    sta floor_dim_y
    iny

    lda (temp_ptr1), y ;store the ptrs to the wall tables
    sta ew_walls_ptr
    iny
    lda (temp_ptr1), y
    sta ew_walls_ptr+1
    iny

    lda (temp_ptr1), y
    sta ns_walls_ptr
    iny
    lda (temp_ptr1), y
    sta ns_walls_ptr+1
    iny

    tya  ;update floor_ptr to the first room after the header
    clc
    adc floor_ptr
    bcc @done
    inc floor_ptr+1
 @done:
    sta floor_ptr
    rts

Then I modify the wall-building routine to calculate indexes and read from the wall tables. The last step is to reorganize my data: remove wall bytes from the individual room data and stick them in tables. Very quick fix.

Conclusion

Separating the wall data from the room data is going to save me a lot of ROM space. It also prevents the possibility of non-matching shared walls (I’m still entering all the data by hand, and I mistype from time to time). It’s sped up the map-building process too.

Come to think of it, I might try to implement something similar for stairs. Stairs_up and stairs_down need to line up on the z-axis. In a way the ceilings and floors are like walls themselves, just with fewer openings (stairs) across the whole map. I’ll save that battle for another day.

Thanks again Roth!