Prev: ACE2 Up: Map Next: AD17
ACE4: Start Berk Script
Used by the routine at Update_Berk_State.
Pick a Berk script row from the table at HL and enter ScriptInstruction.
Input
HL Base of the Berk script table to sample
A Number of candidate rows to skip / try
Start_Berk_Script ACE4 LD ($ACE2),HL Save the script-table base at Pointer_BerkScriptTableBase.
ACE7 LD ($AD03),A Remember the original row count at AD03.
Pick a random Berk script-table row from the candidate base.
Start_Berk_Script_PickRandom ACEA PUSH AF Stash AF on the stack.
ACEB CALL PseudoRandom Call PseudoRandom to pick a pseudo-random offset and keep it in C.
ACEE LD C,A
ACEF LD B,$00 Clear B so BC is the random offset alone.
ACF1 ADD HL,BC Advance HL to the randomly chosen table row.
ACF2 POP AF Restore AF from the stack.
Claim a free script row, or step on / reload the table when the candidate is busy.
Start_Berk_Script_TestRowInUse ACF3 BIT 7,(HL) Is this script row already marked in-use (bit 07)? If not, take it at Start_Berk_Script_ClaimRow.
ACF5 JR Z,Start_Berk_Script_ClaimRow
ACF7 INC HL Step to the flags byte of the next candidate.
ACF8 BIT 6,(HL) Is this candidate free (bit 06 clear)? If so, restart from the saved base at Start_Berk_Script_CountTries.
ACFA JR Z,Start_Berk_Script_CountTries
ACFC LD HL,($ACE2) Reload the script-table base from Pointer_BerkScriptTableBase.
Count down remaining script-row tries; when exhausted, clear in-use bits and retry.
Start_Berk_Script_CountTries ACFF DEC A Count down the remaining tries, then loop to Start_Berk_Script_TestRowInUse while tries remain.
AD00 JR NZ,Start_Berk_Script_TestRowInUse
AD02 LD B,$01 Only one clear-pass remains, then continue into the in-use-bit reset at Start_Berk_Script_Branch.
AD04 LD HL,($ACE2) Reload the script-table base from Pointer_BerkScriptTableBase.
AD07 PUSH HL Stash HL on the stack.
Clear every script-row in-use flag, then retry a fresh random pick.
Start_Berk_Script_Branch AD08 RES 7,(HL) Clear the script-row in-use flag (bit 07 of the Berk script table entry).
AD0A INC HL Advance the current pointer by one byte.
AD0B DJNZ Start_Berk_Script_Branch Decrease the loop counter in B and jump to Start_Berk_Script_Branch if more iterations remain.
AD0D POP HL Restore HL from the stack.
AD0E LD A,($AD03) Reload the original row-count from the self-modifying byte at AD03.
AD11 JR Start_Berk_Script_PickRandom Jump to Start_Berk_Script_PickRandom to try another Berk script row.
Claim this script row by setting its in-use flag and return the selected byte.
Start_Berk_Script_ClaimRow AD13 LD A,(HL) Fetch the next byte from the current pointer.
AD14 SET 7,(HL) Set the script-row in-use flag (bit 07 of the Berk script table entry).
AD16 RET Return.
Prev: ACE2 Up: Map Next: AD17