009. CPU 步进

执行第一个操作码:立即寻址 LDA ()。

9 / 356 · tests/chapter_01_cpu/test_009_cpu_step.py

需要更新的文件

emulator/cpu/cpu.py

位置

CPU.step

参考

https://www.nesdev.org/wiki/Instruction_reference#LDA

此步骤存在的原因

CPU.step 引入了最基本的取指-译码-执行循环。立即寻址 LDA 会直接读取操作码 $A9 后面的字节,并将其存入累加器 A。

完整示例实现

class CPU:
    # Keep the state, fetch, and reset behavior from earlier tests.

    def step(self) -> None:
        opcode = self.fetch_byte()

        if opcode == 0xA9:
            self.a = self.fetch_byte()
            return

        raise NotImplementedError(
            f"Opcode {opcode:02X} not implemented"
        )

执行时间线

PC=$8000 -> fetch $A9 -> PC=$8001
PC=$8001 -> fetch operand $42 -> PC=$8002 -> A=$42

重要不变量

  • 每次 step 恰好执行一条指令
  • 未知的操作码会明显地失败
  • 立即寻址 LDA 总共消费两个字节

常见误解

操作数 $42 是一个数值,不是一个地址。立即寻址模式不会再用 $0042 去做一次总线查找。

范围之外

  • 测试 010 中引入的 Zero 和 Negative 标志位更新
  • LDA 的其他寻址模式
  • 操作码表和周期计数

运行本课

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