Class: Amaterasu::GameBoy::Cpu::Instructions::Jr

Inherits:
Base
  • Object
show all
Defined in:
lib/amaterasu/game_boy/cpu/instructions/jr.rb,
sig/akane/game_boy/cpu/instructions/jr.rbs

Overview

Holds the logic of all the JR (Jump Relative) instructions.

Instance Attribute Summary

Attributes inherited from Base

#mnemonic

Instance Method Summary collapse

Methods inherited from Base

#execute, #format_operand

Constructor Details

#initialize(cpu:, condition: nil) ⇒ Jr

Returns a new instance of Jr.

Parameters:

  • cpu: (Cpu)
  • condition: (Symbol) (defaults to: nil)


9
10
11
12
13
14
# File 'lib/amaterasu/game_boy/cpu/instructions/jr.rb', line 9

def initialize(cpu:, condition: nil)
  super(cpu:)

  @mnemonic = "JR #{format_operand(condition)}, e8"
  @logic    = build_logic(condition)
end

Instance Method Details

#build_logic(condition) ⇒ Proc

Parameters:

  • (Symbol ?condition)

Returns:

  • (Proc)


18
19
20
21
22
23
24
25
26
# File 'lib/amaterasu/game_boy/cpu/instructions/jr.rb', line 18

def build_logic(condition)
  case condition
  when :nz then -> { jr(@registers.z_flag.zero?) }
  when :z  then -> { jr(@registers.z_flag == 1) }
  when :nc then -> { jr(@registers.c_flag.zero?) }
  when :c  then -> { jr(@registers.c_flag == 1) }
  else -> { jr(true) }
  end
end

#jr(cc) ⇒ void

This method returns an undefined value.

Jumps relative to a signed offset.

  • CPU always fetches the unsigned byte.
  • Calculates the offset by signing the value between -128 and +127.
  • If it's a conditional jump, check the condition and return early if it's false.
  • If the condition is true or there is no condition, jump.

Parameters:

  • condition (Boolean)


34
35
36
37
38
39
40
# File 'lib/amaterasu/game_boy/cpu/instructions/jr.rb', line 34

def jr(cc)
  unsigned_byte = @cpu.fetch_next_byte
  offset = @cpu.sign_value(unsigned_byte)
  return unless cc

  @cpu.jump_to(address: @registers.pc + offset)
end