State Machines: Why Bitwise is Best

A State Machine manages the status of a system (e.g., a game character is ‘Jumping’, ‘Firing’, or ‘Hit’). In high-level languages, you might use three separate Boolean variables for these. In Z80 assembly, that’s inefficient.

By using a single register (like C) as a status register, you can manage up to eight independent Boolean flags, dedicating one bit to each status. This is the fastest method for context management.

Example Status Register (Register C):

Bit Position Status Flag Value (If Set)
Bit 0 Player Firing 01H
Bit 1 Player Jumping 02H
Bit 2 Game Paused 04H

Dedicated Bit Manipulation Instructions

The Z80’s BIT, SET, and RES instructions are perfect for this role as they target a specific bit without affecting any other bits in the register.

Checking a State (If…Then): Use BIT to check if a specific flag is active. It sets the Zero flag (Z) if the bit is cleared (0).

    ; Check if the Player is Firing (Bit 0 in register C)
    BIT  0, C
    JP   Z, NOT_FIRING        ; Jump if Bit 0 is 0 (NOT Firing)
    CALL HANDLE_FIRE_LOGIC   ; Run if Bit 0 is 1 (Firing)

Changing a State (SET and RES): Use SET to activate a flag (set it to 1) and RES to deactivate a flag (reset it to 0).

    ; Activate the Game Paused Flag (Bit 2 in register C)
    SET  2, C
    
    ; Deactivate the Player Jumping Flag (Bit 1 in register C)
    RES  1, C

Combining States with Logic Operations

If you need to change multiple flags simultaneously or read a set of flags from a mask, you can use the AND or OR instructions with an immediate value.

Example: Setting Multiple Flags (OR)

    ; Activate both Firing (01H) and Jumping (02H) flags
    OR   03H             ; 03H = 00000011B
    ; C now has bits 0 and 1 set.