Class: Amaterasu::GameBoy::Cpu::Instructions::Sub

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

Overview

Handles the logic related to all possible SUB instructions

  • SUB A, r8
  • SUB A, [HL]
  • SUB A, n8

Instance Attribute Summary

Attributes inherited from Base

#mnemonic

Instance Method Summary collapse

Methods inherited from Base

#execute, #format_operand

Constructor Details

#initialize(cpu:, source:) ⇒ Sub

Returns a new instance of Sub.

Parameters:

  • cpu (Cpu)

    Holds a direct reference to the main Cpu object.

  • source (Symbol)

    Operator, can be a register, :mem_hl, :imm8.

  • cpu: (Cpu)
  • source: (Symbol)


15
16
17
18
19
20
# File 'lib/amaterasu/game_boy/cpu/instructions/sub.rb', line 15

def initialize(cpu:, source:)
  super(cpu:)

  @mnemonic = "SUB A, #{format_operand(source)}"
  @logic    = build_logic(source)
end

Instance Method Details

#build_logic(source) ⇒ Proc

Builds the logic for all SUB instructions. Returns a lambda object to be called by the CPU.

Parameters:

  • source (Symbol)

Returns:

  • (Proc)


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/amaterasu/game_boy/cpu/instructions/sub.rb', line 26

def build_logic(source)
  case source
  when :a      then -> { sub_a(@registers.a) }
  when :b      then -> { sub_a(@registers.b) }
  when :c      then -> { sub_a(@registers.c) }
  when :d      then -> { sub_a(@registers.d) }
  when :e      then -> { sub_a(@registers.e) }
  when :h      then -> { sub_a(@registers.h) }
  when :l      then -> { sub_a(@registers.l) }
  when :mem_hl then -> { sub_a(@cpu.bus_read(address: @registers.hl)) }
  when :imm8   then -> { sub_a(@cpu.fetch_next_byte) }
  else
    -> { raise 'Not implemented Sub operation' }
  end
end

#sub_a(value) ⇒ void

This method returns an undefined value.

Subtracts a given value from register A and stores it back into A.

  • Sets the Zero flag if the result is zero, otherwise clears it.
  • Always sets the Subtraction flag.
  • Sets the Half Carry flag if it needed to borrow from Bit 4.
  • Sets the Carry flag if it needed to borrow (acc < value).

Parameters:

  • value (Integer)


48
49
50
51
52
53
54
55
56
57
58
# File 'lib/amaterasu/game_boy/cpu/instructions/sub.rb', line 48

def sub_a(value)
  acc = @registers.a
  result = @registers.a - value

  @registers.z_flag = result.nobits?(0xFF)
  @registers.n_flag = true
  @registers.h_flag = (acc & 0x0F) < (value & 0x0F)
  @registers.c_flag = acc < value

  @registers.a = result
end