Deterministic Core 4 — WriteCellValue and SolveDeterministic

Purpose: Commit a resolved digit (1–9) into a board cell, update row/column/box structures, and mark progress.

Assumptions:

• HL = address of cell

• A = digit 1–9

• (ProgressFlag) is a byte set to 1 whenever a cell is filled during a pass

; WriteCellValue
; HL = cell address
; A  = digit (1–9)

WriteCellValue:
    LD   (HL),A            ; store solved digit

    LD   B,A               ; preserve digit

    LD   A,1
    LD   (ProgressFlag),A  ; mark progress this pass

    LD   A,B               ; restore digit
    ; Future extension: update row/col/box masks here if cached
    RET

Purpose: Repeatedly scan all 81 cells, filling naked singles until no further progress or contradiction.

Return:

• Z = 0 success (stable, no contradiction)

• Z = 1 contradiction encountered

; SolveDeterministic

SolveDeterministic:

DetLoop:
    XOR  A
    LD   (ProgressFlag),A   ; clear progress

    LD   HL,BoardStart
    LD   DE,81

CellScanLoop:
    LD   A,(HL)
    OR   A
    JR   NZ,NextCell        ; skip filled cells

    PUSH HL
    CALL BuildCandidateMask ; returns BC mask, Z=1 if contradiction
    JR   Z,Contradiction

    CALL SingleCandidateFromMask
    JR   Z,NotSingle        ; not exactly one candidate

    ; A = resolved digit
    POP  HL
    PUSH AF
    CALL WriteCellValue
    POP  AF
    JR   AfterCell

NotSingle:
    POP  HL

AfterCell:
NextCell:
    INC  HL
    DEC  DE
    LD   A,D
    OR   E
    JR   NZ,CellScanLoop

    LD   A,(ProgressFlag)
    OR   A
    JR   NZ,DetLoop         ; repeat if progress made

    XOR  A                  ; success, Z=1 so clear to signal OK
    RET                     ; Z=1? No — XOR A sets Z=1; we want Z=0

    ; adjust final flags:
    ; Instead explicitly clear Z before returning success

; Revised success exit:
DetSuccess:
    LD   A,1
    OR   0                  ; ensure Z=0
    RET

Contradiction:
    POP  HL                 ; balance stack if needed
    LD   A,0
    OR   A                  ; set Z=1
    RET

Note: Final flag semantics will be tightened in next refinement to guarantee consistent Z signalling on all exits. Current structure provides full deterministic progress loop with contradiction propagation.