I have been having trouble with high and low bytes of 16-bit numbers. Once in a while I almost understand things, but then it flies out the window the next.
I think, possibly, the part that I don't understand is the FLOW of what's needed. When do I start with the low byte and add the carry into the high byte? When do I start with the high byte?
Here's my current problem:
I want to make a healing spell that transfers HP from one character to another - damaging the healer, healing the patient.
The original code, which I understand perfectly, is:
LDA hp_recovery ; healing potency
CLC
ADC ch_curhp, X ; add healing potency to low byte of HP
STA ch_curhp, X
LDA ch_curhp+1, X ; add 0 to high byte of HP (to catch carry from low byte)
ADC #0
STA ch_curhp+1, X
Originally I was just going to have "hp_recovery" subtract from the healer's HP after. The issue is, what if the patient is almost healthy? The healer's potency would damage them far more than they healed the patient. I need to cap the damage done to the healer if they overheal the patient.
So first I thought, maybe...
LDA ch_maxhp+1, X
SEC
SBC ch_curhp+1, X
STA MMC5_tmp+1
LDA ch_maxhp, X
SEC
SBC ch_curhp, X
STA MMC5_tmp
And that gets the amount of healing needed, stored in MMC5_tmp and +1. Then I could compare it to "hp_recovery" and do something to cut off the overheal amount before healing even begins...
But where to begin? High byte or low byte? "hp_recovery" is only one byte, so would I need to use #0 in the second comparison again, so it only compares the carry?
________
Edit: Slugged away at it a little more. Maybe made progress?
MenuRecoverHP_Magic:
LDA ch_maxhp, X
SEC
SBC ch_curhp, X
STY MMC5_tmp
LDA ch_maxhp+1, X
SEC
SBC ch_curhp+1, X
STA MMC5_tmp+1
BEQ :+ ; if high bytes are 0, then Z is set. Z is clear if there is high byte HP to heal
CPY hp_recovery ; compare the amount of lost low byte HP to the amount to be healed
; C is clear if there is overheal. C and Z is set if its exactly equal.
BCS @NoOverheal
STY hp_recovery ; cap hp_recovery at what will fill up the low byte.
JMP @NoOverheal ; and now there's no more overheal, so jump to healing!
: ; jump here if there is healing to be done in the high bytes...
;; now I'm not sure what to do
;; Heal the low bytes and then do this all over again with the carry, somehow?
@NoOverheal:
LDA hp_recovery ; healing potency
CLC
ADC ch_curhp, X ; add healing potency to low byte of HP
STA ch_curhp, X
LDA ch_curhp+1, X ; add 0 to high byte of HP (to catch carry from low byte)
ADC #0
STA ch_curhp+1, X
CMP ch_maxhp+1, X ; then compare against max HP to make sure we didn't go over
BEQ _MenuRecoverHP_CheckLow ; if high byte of cur = high byte of max, we need to check the low byte
BCS _MenuRecoverHP_OverMax ; if high byte of cur > high byte of max... we went over