diff --git a/src/cpu.ml b/src/cpu.ml index 27295e5..3b20f23 100644 --- a/src/cpu.ml +++ b/src/cpu.ml @@ -76,7 +76,7 @@ let update_flag_reg cpu = cpu.reg.f <- char_of_int @@ z + n + h + c let inc_pc cpu count = - cpu.reg.pc <- cpu.reg.pc + count + cpu.reg.pc <- (cpu.reg.pc + count) mod 0xFFFF let inc_cycles cpu count = cpu.cycles <- cpu.cycles + count @@ -118,6 +118,14 @@ let read_pc_2bytes cpu mem = inc_pc cpu 2; word +let pop_stack cpu mem = + let low = Memory.get mem cpu.reg.sp in + cpu.reg.sp <- (cpu.reg.sp + 1) mod 0xFFFF; + let high = Memory.get mem cpu.reg.sp in + cpu.reg.sp <- (cpu.reg.sp + 1) mod 0xFFFF; + merge_bytes low high + + (** http://imrannazar.com/GameBoy-Z80-Opcode-Map @@ -135,12 +143,35 @@ let run cpu (mem: Memory.map) = | '\x7E' -> printf " LD \tA, (HL)\n"; let hl = merge_bytes cpu.reg.l cpu.reg.h in cpu.reg.a <- Memory.get mem hl; - inc_cycles cpu 8; + inc_cycles cpu 8 + + | '\x36' -> let n = read_pc_byte cpu mem in + printf " LD \t(HL) 0x%02X\n" n; + let hl = merge_bytes cpu.reg.l cpu.reg.h in + Memory.set mem hl (char_of_int n); + inc_cycles cpu 12 + (* CPU control *) | '\x00' -> printf " NOP\n"; inc_cycles cpu 4 + + (* jump *) + | '\xC9' -> printf " RET\n"; + cpu.reg.pc <- pop_stack cpu mem; + inc_cycles cpu 16 + + | '\xC0' -> printf " RET \tNZ\n"; + if cpu.flag.z = false then + begin + cpu.reg.pc <- pop_stack cpu mem; + inc_cycles cpu 20 + end else + inc_cycles cpu 8 + + + | '\x03' -> printf " INC \tBC\n"; inc_BC cpu; inc_cycles cpu 8 @@ -218,14 +249,6 @@ let run cpu (mem: Memory.map) = cpu.reg.a <- char_of_int @@ int_A lxor int_A; inc_cycles cpu 4 - | '\xC0' -> printf " RET \tNZ\n"; - if cpu.flag.z = false then - begin - cpu.reg.pc <- cpu.reg.sp; - inc_cycles cpu 20 - end else - inc_cycles cpu 8 - | '\xC3' -> let addr = read_pc_2bytes cpu mem in printf " JP \t0x%04X\n" addr; cpu.reg.pc <- addr; inc_cycles cpu 16