019. Lda 绝对,Y 寻址

添加绝对,Y 寻址的 LDA($B9)。

19 / 356 · tests/chapter_01_cpu/test_019_LDA_absolute_y.py

要更新的文件

emulator/cpu/addressing_modes.py
emulator/cpu/opcodes.py

位置

addressing_modes.absolute_y
opcodes.lda_absolute_y
opcodes.OPCODE_TABLE[$B9]

为什么需要这一步

绝对,Y 与绝对,X 具有相同的 16 位寻址行为,但使用的是寄存器 Y。保留各自独立的辅助函数,能让实际选用的变址寄存器显式可见且可测试。

完整示例实现

# emulator/cpu/addressing_modes.py
def absolute_y(cpu) -> int:
    base = cpu.fetch_word()
    return base + cpu.y


# emulator/cpu/opcodes.py
from emulator.cpu.addressing_modes import absolute_y


def lda_absolute_y(cpu) -> None:
    address = absolute_y(cpu)
    lda(cpu, cpu.bus.read(address))


OPCODE_TABLE = {
    # Preserve existing entries.
    0xB9: lda_absolute_y,
}

重要不变量

  • 该辅助函数使用 Y,而不是 X
  • 在加上 Y 之前先消耗两个操作数字节
  • 跨页时保留完整的 16 位结果

常见误解

复制 absolute_x 却忘记把 cpu.x 改成 cpu.y,当两个寄存器恰好包含相同的值时,测试仍可能通过。

范围之外

  • 跨页周期惩罚
  • 先间接后变址寻址模式
  • 通用的变址地址辅助函数

运行本课

uv run pytest tests/chapter_01_cpu/test_019_LDA_absolute_y.py -v