HarmonyOS数独候选台连载16:题面导入导出与回归核验【共创稿事节】
HarmonyOS数独候选台连载08:题面导入导出与回归核验【共创稿事节】
数独页面已经能够编辑、撤销、查询候选和进行有界搜索,但一次进度交换不能只搬走八十一个数字。固定题面身份需要保留,导入数字需要重新检查冲突,候选缓存和搜索报告也必须对应新内容。本篇让数独候选台围绕同一固定题目的进度完成文本导入导出,并把导入作为新的历史起点。

题目身份与当前进度分开保存
固定题面是题目给出的事实,当前board包含用户已经填入的数字。两者可能在同一位置拥有不同含义:固定格不能修改,可编辑格的非零数字却可以撤销或清空。如果导入时只根据当前非零值重新创建givens,所有用户填入数字都会被错误地锁定。
本篇沿用前文的固定题目,导出内容包含结构标识、固定题面字符串和当前进度字符串。固定题面字符串必须与initialPuzzle一致,导入其他题目时明确拒绝。后续扩展题库,应增加题目身份和对应固定格构造入口,不把不同题目的数字当成当前题的进度接收。
下面保留已有八个模型和服务的完整实现,路径相对于entry/src/main/ets。文本服务调用既有身份与冲突校验,页面在导入后重新建立候选缓存和提示。
// model/Puzzle.ets
export function initialPuzzle(): number[] {
const rows: string[] = ['530070000','600195000','098000060',
'800060003','400803001','700020006','060000280','000419005','000080079'];
const board: number[] = [];
for (const row of rows) for (let col: number = 0; col<9; col++) board.push(Number(row[col]));
return board;
}
export function requireBoard(board: number[]): void {
if (board.length!==81) throw new Error('题面需为81格');
for (const value of board) if (!Number.isInteger(value) || value<0 || value>9)
throw new Error('题面格值需为0至9');
}
export function parseCell(rowText: string,colText: string): number {
const row: string = rowText.trim(); const col: string = colText.trim();
if (!/^[1-9]$/.test(row) || !/^[1-9]$/.test(col)) throw new Error('行列需为1至9');
return (Number(row)-1)*9+Number(col)-1;
}
// service/Candidates.ets
import { requireBoard } from '../model/Puzzle';
export interface CandidateInfo { rowUsed: number[]; colUsed: number[]; boxUsed: number[]; values: number[]; }
function uniqueDigits(values: number[]): number[] {
const result: number[] = [];
for (let value: number = 1; value<=9; value++) if (values.indexOf(value)>=0) result.push(value);
return result;
}
export function queryCandidates(board: number[],index: number): CandidateInfo {
requireBoard(board);
if (!Number.isInteger(index) || index<0 || index>=81) throw new Error('目标格超出范围');
if (board[index]!==0) throw new Error('目标格已有数字');
const row: number = Math.floor(index/9); const col: number = index%9;
const rowValues: number[] = []; const colValues: number[] = []; const boxValues: number[] = [];
for (let offset: number = 0; offset<9; offset++) {
rowValues.push(board[row*9+offset]); colValues.push(board[offset*9+col]);
}
const top: number = Math.floor(row/3)*3; const left: number = Math.floor(col/3)*3;
for (let dr: number = 0; dr<3; dr++) for (let dc: number = 0; dc<3; dc++)
boxValues.push(board[(top+dr)*9+left+dc]);
const rowUsed: number[] = uniqueDigits(rowValues);
const colUsed: number[] = uniqueDigits(colValues);
const boxUsed: number[] = uniqueDigits(boxValues);
const used: boolean[] = [false,false,false,false,false,false,false,false,false,false];
for (const value of rowUsed.concat(colUsed,boxUsed)) used[value]=true;
const result: number[] = [];
for (let value: number = 1; value<=9; value++) {
if (!used[value]) result.push(value);
}
return {rowUsed,colUsed,boxUsed,values:result};
}
export function digitsText(values: number[]): string { return values.length===0 ? '无' : values.join('、'); }
// service/PuzzleEdit.ets
import { initialPuzzle, requireBoard } from '../model/Puzzle';
export interface PuzzleState { board: number[]; givens: boolean[]; }
export type UnitKind = 'row' | 'col' | 'box';
export interface Conflict { kind: UnitKind; unit: number; digit: number; indices: number[]; }
export function createPuzzleState(): PuzzleState {
const board: number[] = initialPuzzle();
return {board,givens:board.map((value: number) => value!==0)};
}
export function requirePuzzleState(state: PuzzleState): void {
requireBoard(state.board);
if (state.givens.length!==81) throw new Error('固定格标记长度错误');
const seed: number[] = initialPuzzle();
for (let i: number = 0; i<81; i++) {
if (state.givens[i] !== (seed[i]!==0) || (seed[i]!==0 && state.board[i]!==seed[i]))
throw new Error('固定题面不一致');
}
}
export function unitIndices(kind: UnitKind,unit: number): number[] {
if (!Number.isInteger(unit) || unit<0 || unit>=9) throw new Error('区域位置错误');
if (kind!=='row' && kind!=='col' && kind!=='box') throw new Error('区域类型错误');
const result: number[] = [];
for (let offset: number = 0; offset<9; offset++) {
if (kind==='row') result.push(unit*9+offset);
else if (kind==='col') result.push(offset*9+unit);
else result.push((Math.floor(unit/3)*3+Math.floor(offset/3))*9+(unit%3)*3+offset%3);
}
return result;
}
export function findConflicts(board: number[]): Conflict[] {
requireBoard(board);
const result: Conflict[] = [];
const kinds: UnitKind[] = ['row','col','box'];
for (const kind of kinds) for (let unit: number = 0; unit<9; unit++) {
const points: number[] = unitIndices(kind,unit);
for (let digit: number = 1; digit<=9; digit++) {
const matches: number[] = points.filter((index: number) => board[index]===digit);
if (matches.length>1) result.push({kind,unit,digit,indices:matches});
}
}
return result;
}
export function conflictText(conflict: Conflict): string {
const name: string = conflict.kind==='row' ? '行' : conflict.kind==='col' ? '列' : '宫';
return `第${conflict.unit+1}${name}数字${conflict.digit}重复`;
}
export function parseDigit(text: string): number {
const value: string = text.trim();
if (!/^[0-9]$/.test(value)) throw new Error('填入值需为0至9,0表示清空');
return Number(value);
}
export function commitEdit(state: PuzzleState,index: number,value: number): PuzzleState {
requirePuzzleState(state);
if (!Number.isInteger(index) || index<0 || index>=81) throw new Error('目标格超出范围');
if (!Number.isInteger(value) || value<0 || value>9) throw new Error('填入值超出范围');
if (state.givens[index]) throw new Error('固定题面格不可修改');
if (findConflicts(state.board).length>0) throw new Error('当前题面存在冲突');
const next: number[] = state.board.slice(); next[index]=value;
const conflicts: Conflict[] = findConflicts(next);
if (conflicts.length>0) throw new Error(conflictText(conflicts[0]));
return {board:next,givens:state.givens.slice()};
}
// service/SingleHint.ets
import { CandidateInfo, queryCandidates } from './Candidates';
import { PuzzleState, requirePuzzleState, findConflicts, commitEdit } from './PuzzleEdit';
export interface SingleHint { index: number; value: number; boardKey: string; info: CandidateInfo; }
export function findSingleHints(state: PuzzleState): SingleHint[] {
requirePuzzleState(state);
if (findConflicts(state.board).length>0) throw new Error('当前题面存在冲突');
const result: SingleHint[] = [];
const boardKey: string = state.board.join('');
for (let index: number = 0; index<81; index++) {
if (state.board[index]!==0) continue;
const info: CandidateInfo = queryCandidates(state.board,index);
if (info.values.length===1) {
result.push({index,value:info.values[0],boardKey,info});
}
}
return result;
}
export function applySingleHint(state: PuzzleState,hint: SingleHint): PuzzleState {
requirePuzzleState(state);
if (state.board.join('')!==hint.boardKey) throw new Error('题面已变化,请刷新提示');
const current: CandidateInfo = queryCandidates(state.board,hint.index);
if (current.values.length!==1 || current.values[0]!==hint.value)
throw new Error('当前格不满足单格唯一候选');
return commitEdit(state,hint.index,hint.value);
}
export function hintText(hint: SingleHint): string {
return `${Math.floor(hint.index/9)+1}行${hint.index%9+1}列填${hint.value}`;
}
// service/History.ets
import { PuzzleState, createPuzzleState, commitEdit } from './PuzzleEdit';
export interface EditStep { index: number; before: number; after: number; group: string; }
export interface PuzzleHistory { state: PuzzleState; steps: EditStep[]; cursor: number; }
export function createHistory(): PuzzleHistory { return {state:createPuzzleState(),steps:[],cursor:0}; }
function copyStep(step: EditStep): EditStep {
return {index:step.index,before:step.before,after:step.after,group:step.group};
}
export function recordEdit(history: PuzzleHistory,index: number,value: number,group: string): PuzzleHistory {
const next: PuzzleState = commitEdit(history.state,index,value);
const before: number = history.state.board[index];
if (before===value) return history;
const steps: EditStep[] = history.steps.slice(0,history.cursor).map(copyStep);
const last: EditStep | undefined = steps.length>0 ? steps[steps.length-1] : undefined;
const atEnd: boolean = history.cursor===history.steps.length;
if (atEnd && group.length>0 && last!==undefined && last.index===index && last.group===group && last.after===before) {
if (last.before===value) steps.pop();
else steps[steps.length-1]={index,before:last.before,after:value,group};
} else steps.push({index,before,after:value,group});
return {state:next,steps,cursor:steps.length};
}
export function undo(history: PuzzleHistory): PuzzleHistory {
if (history.cursor===0) throw new Error('没有可撤销步骤');
const step: EditStep = history.steps[history.cursor-1];
if (history.state.board[step.index]!==step.after) throw new Error('历史与题面不一致');
return {state:commitEdit(history.state,step.index,step.before),steps:history.steps.map(copyStep),cursor:history.cursor-1};
}
export function redo(history: PuzzleHistory): PuzzleHistory {
if (history.cursor===history.steps.length) throw new Error('没有可重做步骤');
const step: EditStep = history.steps[history.cursor];
if (history.state.board[step.index]!==step.before) throw new Error('历史与题面不一致');
return {state:commitEdit(history.state,step.index,step.after),steps:history.steps.map(copyStep),cursor:history.cursor+1};
}
// service/Search.ets
import { requireBoard } from '../model/Puzzle';
import { queryCandidates } from './Candidates';
import { findConflicts } from './PuzzleEdit';
export interface SearchReport { status: string; solutions: number; nodes: number; cutoff: boolean; first: number[]; boardKey: string; }
export function idleReport(): SearchReport {
return {status:'待分析',solutions:0,nodes:0,cutoff:false,first:[],boardKey:''};
}
export function parseBudget(text: string): number {
const value: string = text.trim();
if (!/^[1-9][0-9]{0,4}$/.test(value) || Number(value)>10000) throw new Error('节点预算需为1至10000');
return Number(value);
}
export function analyzePuzzle(source: number[],budget: number): SearchReport {
requireBoard(source);
if (findConflicts(source).length>0) throw new Error('当前题面存在冲突');
if (!Number.isInteger(budget) || budget<1 || budget>10000) throw new Error('节点预算超出范围');
const board: number[] = source.slice();
const report: SearchReport = idleReport(); report.boardKey=source.join('');
function visit(): void {
if (report.solutions>=2 || report.cutoff) return;
if (report.nodes>=budget) { report.cutoff=true; return; }
report.nodes++;
let target: number = -1; let values: number[] = [];
for (let i: number = 0; i<81; i++) {
if (board[i]!==0) continue;
const options: number[] = queryCandidates(board,i).values;
if (options.length===0) return;
if (target<0 || options.length<values.length) { target=i; values=options; }
}
if (target<0) {
report.solutions++;
if (report.solutions===1) report.first=board.slice();
return;
}
for (const value of values) {
board[target]=value; visit(); board[target]=0;
if (report.solutions>=2 || report.cutoff) return;
}
}
visit();
report.status=report.solutions>=2 ? '至少两解' : report.cutoff ? '尚未判定' : report.solutions===1 ? '唯一解' : '无解';
return report;
}
// service/CandidateCache.ets
import { requireBoard } from '../model/Puzzle';
import { CandidateInfo, queryCandidates } from './Candidates';
import { PuzzleState, requirePuzzleState, findConflicts, unitIndices } from './PuzzleEdit';
import { SingleHint } from './SingleHint';
export interface CandidateCache { board: number[]; entries: (CandidateInfo | null)[]; }
export interface CacheUpdate { cache: CandidateCache; changed: number; affected: number; recomputed: number; }
function copyInfo(info: CandidateInfo): CandidateInfo {
return {rowUsed:info.rowUsed.slice(),colUsed:info.colUsed.slice(),boxUsed:info.boxUsed.slice(),values:info.values.slice()};
}
export function createCache(board: number[]): CandidateCache {
requireBoard(board);
const entries: (CandidateInfo | null)[] = [];
for (let i: number = 0; i<81; i++) entries.push(board[i]===0 ? queryCandidates(board,i) : null);
return {board:board.slice(),entries};
}
export function updateCache(previous: CandidateCache,board: number[]): CacheUpdate {
requireBoard(previous.board); requireBoard(board);
if (previous.entries.length!==81) throw new Error('候选缓存长度错误');
const flags: boolean[] = [];
for (let i: number = 0; i<81; i++) flags.push(false);
let changed: number = 0;
for (let i: number = 0; i<81; i++) {
if (previous.board[i]===board[i]) continue;
changed++;
const row: number = Math.floor(i/9); const col: number = i%9;
const points: number[] = unitIndices('row',row).concat(unitIndices('col',col),unitIndices('box',Math.floor(row/3)*3+Math.floor(col/3)));
for (const point of points) flags[point]=true;
}
const entries: (CandidateInfo | null)[] = [];
let affected: number = 0; let recomputed: number = 0;
for (let i: number = 0; i<81; i++) {
if (flags[i]) affected++;
if (board[i]!==0) { entries.push(null); continue; }
const old: CandidateInfo | null = previous.entries[i];
if (flags[i] || old===null) { entries.push(queryCandidates(board,i)); recomputed++; }
else entries.push(copyInfo(old));
}
return {cache:{board:board.slice(),entries},changed,affected,recomputed};
}
export function readCandidate(cache: CandidateCache,index: number): CandidateInfo {
if (!Number.isInteger(index) || index<0 || index>=81) throw new Error('缓存位置错误');
const entry: CandidateInfo | null = cache.entries[index];
if (entry===null) throw new Error('目标格已有数字');
return copyInfo(entry);
}
export function hintsFromCache(cache: CandidateCache,state: PuzzleState): SingleHint[] {
requirePuzzleState(state);
if (cache.board.join('')!==state.board.join('')) throw new Error('缓存题面不一致');
if (findConflicts(state.board).length>0) throw new Error('当前题面存在冲突');
const hints: SingleHint[] = []; const boardKey: string = state.board.join('');
for (let index: number = 0; index<81; index++) {
if (state.board[index]!==0) continue;
const info: CandidateInfo = readCandidate(cache,index);
if (info.values.length===1) hints.push({index,value:info.values[0],boardKey,info});
}
return hints;
}
// service/AccessibleEdit.ets
import { PuzzleState, requirePuzzleState } from './PuzzleEdit';
export function moveCell(index: number,delta: number): number {
if (!Number.isInteger(index) || index<0 || index>=81 || (delta!==-1 && delta!==1))
throw new Error('位置移动参数错误');
return Math.max(0,Math.min(80,index+delta));
}
export function describeCell(state: PuzzleState,index: number): string {
requirePuzzleState(state);
if (!Number.isInteger(index) || index<0 || index>=81) throw new Error('目标格超出范围');
const role: string = state.givens[index] ? '固定题面格' : '可编辑格';
const value: string = state.board[index]===0 ? '空格' : `当前数字${state.board[index]}`;
return `第${Math.floor(index/9)+1}行第${index%9+1}列,${role},${value}`;
}
三行文本表达一个可校验的状态
第一行为SUDOKU1,第二行是固定题面的八十一个数字,第三行是当前board的八十一个数字。数字零表示空格,一至九表示已有数字;行列位置使用行优先顺序,由字符下标确定。格式中的换行负责分隔记录,题盘自身九行不另加分隔符。
在一行三列填入一以后,完整文本如下。固定题面保持不变,第三行第三个字符由零变为一,其他位置仍对应原题。
SUDOKU1
530070000600195000098000060800060003400803001700020006060000280000419005000080079
531070000600195000098000060800060003400803001700020006060000280000419005000080079
格式不保存步骤数组、候选集合、提示列表或搜索报告。步骤属于当前会话的操作路径,派生内容则可以从合法board重新取得。导出进度与完整会话归档是不同的数据目标,本篇选择前者,让内容简单且恢复规则清晰。
校验字符之后仍要校验约束
解析前限制文本长度,换行统一处理为换行符,再检查三行结构与版本。固定题面行按完整字符串比较,进度行使用八十一个数字的正则约束。这样短行、超长行、非数字字符和缺失字段都会在构造状态之前被拒绝。
// service/PuzzleText.ets
import { initialPuzzle } from '../model/Puzzle';
import { PuzzleState, requirePuzzleState, findConflicts } from './PuzzleEdit';
export function exportPuzzle(state: PuzzleState): string {
requirePuzzleState(state);
if (findConflicts(state.board).length>0) throw new Error('题面存在冲突');
return ['SUDOKU1',initialPuzzle().join(''),state.board.join('')].join('\n');
}
export function importPuzzle(text: string): PuzzleState {
if (text.length>200) throw new Error('题面文本过长');
const lines: string[] = text.replace(/\r\n/g,'\n').trim().split('\n');
if (lines.length!==3 || lines[0]!=='SUDOKU1') throw new Error('题面格式或版本错误');
if (lines[1]!==initialPuzzle().join('')) throw new Error('固定题面不匹配');
if (!/^[0-9]{81}$/.test(lines[2])) throw new Error('进度需为81个数字');
const state: PuzzleState = {board:lines[2].split('').map((v: string) => Number(v)),
givens:initialPuzzle().map((v: number) => v!==0)};
requirePuzzleState(state);
if (findConflicts(state.board).length>0) throw new Error('导入题面存在冲突');
return state;
}
export function checkPuzzleRoundTrip(state: PuzzleState): boolean {
const text: string = exportPuzzle(state);
return exportPuzzle(importPuzzle(text))===text;
}
数字数组构造完成后,givens只来自initialPuzzle。requirePuzzleState检查固定题面数字与标记,findConflicts检查整盘行列宫约束。这两步缺一不可:改动固定格可能不产生重复数字,却仍违反题目身份;在可编辑格写入重复数字没有改变身份,却违反数独规则。

导出也执行同样的业务检查。内部状态应由合法编辑入口维护,但交换函数仍是数据边界,不能因为它通常从页面调用就省去身份和冲突判断。将拒绝规则放在服务中,按钮、快捷操作和后续其他导出入口便可共用一致的条件。
新进度成为新的历史起点
导入文本成功并不意味着直接覆盖history.state。页面先建立新状态、候选缓存、单格提示和当前目标描述所需数据,再统一发布。新的PuzzleHistory保留导入后的state,steps为空,cursor为零。用户随后新增的合法填数,才会成为可以撤销的第一步。
// pages/Index.ets
import { initialPuzzle, parseCell } from '../model/Puzzle';
import { CandidateInfo, queryCandidates, digitsText } from '../service/Candidates';
import { PuzzleState, createPuzzleState, commitEdit, findConflicts, parseDigit } from '../service/PuzzleEdit';
import { SingleHint, findSingleHints, applySingleHint, hintText } from '../service/SingleHint';
import { PuzzleHistory, createHistory, recordEdit, undo, redo } from '../service/History';
import { SearchReport, idleReport, analyzePuzzle, parseBudget } from '../service/Search';
import { CandidateCache, CacheUpdate, createCache, updateCache, readCandidate, hintsFromCache } from '../service/CandidateCache';
import { moveCell, describeCell } from '../service/AccessibleEdit';
import { exportPuzzle, importPuzzle, checkPuzzleRoundTrip } from '../service/PuzzleText';
@Entry
@Component
struct Index {
@State exchangeText: string = '';
@State exchangeStatus: string = '等待操作';
@State cache: CandidateCache = createCache(initialPuzzle());
@State changedCount: number = 0;
@State affectedCount: number = 0;
@State recomputedCount: number = 51;
@State report: SearchReport = idleReport();
@State budgetText: string = '10000';
@State history: PuzzleHistory = createHistory();
@State hints: SingleHint[] = hintsFromCache(createCache(initialPuzzle()),createPuzzleState());
@State hintIndex: number = 40;
@State digitText: string = '1';
@State candidateText: string = '候选:1、2、4';
@State rowText: string = '1';
@State colText: string = '3';
@State selected: number = 2;
@State info: CandidateInfo = queryCandidates(initialPuzzle(),2);
@State status: string = '已更新';
@State areaWidth: number = 360;
private moveTarget(delta: number): void {
const index: number = moveCell(this.selected,delta);
this.selected=index; this.rowText=`${Math.floor(index/9)+1}`; this.colText=`${index%9+1}`;
if (this.history.state.board[index]===0) {
this.info=readCandidate(this.cache,index); this.candidateText=`候选:${digitsText(this.info.values)}`;
} else this.candidateText='目标格已填';
this.status='已切换目标';
}
private publishCache(update: CacheUpdate): void {
this.cache=update.cache; this.changedCount=update.changed;
this.affectedCount=update.affected; this.recomputedCount=update.recomputed;
}
private analyze(): void {
try {
const report: SearchReport = analyzePuzzle(this.history.state.board,parseBudget(this.budgetText));
this.report=report; this.status='分析完成';
} catch (error) { this.status=error instanceof Error ? error.message : '分析失败'; }
}
private query(): void {
try {
const index: number = parseCell(this.rowText,this.colText);
const next: CandidateInfo = readCandidate(this.cache,index);
this.selected=index; this.info=next; this.candidateText=`候选:${digitsText(next.values)}`; this.status='已查询';
} catch (error) { this.status=error instanceof Error ? error.message : '查询失败'; }
}
private submit(): void {
try {
const index: number = parseCell(this.rowText,this.colText);
const value: number = parseDigit(this.digitText);
const history: PuzzleHistory = recordEdit(this.history,index,value,`manual:${index}`);
const next: PuzzleState = history.state;
const update: CacheUpdate = updateCache(this.cache,next.board);
const hints: SingleHint[] = hintsFromCache(update.cache,next);
this.publishCache(update);
this.history=history; this.refreshHints(hints); this.selected=index;
if (value===0) {
this.info=readCandidate(update.cache,index);
this.candidateText=`候选:${digitsText(this.info.values)}`;
} else this.candidateText='目标格已填';
this.status=`已写入${Math.floor(index/9)+1}行${index%9+1}列`;
} catch (error) { this.status=error instanceof Error ? error.message : '提交失败'; }
}
private refreshHints(hints: SingleHint[]): void {
const retained: boolean = hints.some((hint: SingleHint) => hint.index===this.hintIndex);
this.hints=hints;
if (!retained) this.hintIndex=hints.length>0 ? hints[0].index : -1;
}
private applyHint(hint: SingleHint): void {
try {
const next: PuzzleState = applySingleHint(this.history.state,hint);
const history: PuzzleHistory = recordEdit(this.history,hint.index,hint.value,'hint');
const update: CacheUpdate = updateCache(this.cache,next.board);
const hints: SingleHint[] = hintsFromCache(update.cache,next);
this.publishCache(update);
this.history=history; this.refreshHints(hints); this.selected=hint.index;
this.candidateText='目标格已填'; this.status=`已应用${hintText(hint)}`;
} catch (error) { this.status=error instanceof Error ? error.message : '提示应用失败'; }
}
private travel(back: boolean): void {
try {
const next: PuzzleHistory = back ? undo(this.history) : redo(this.history);
const update: CacheUpdate = updateCache(this.cache,next.state.board);
const hints: SingleHint[] = hintsFromCache(update.cache,next.state);
this.publishCache(update);
const index: number = back ? this.history.steps[this.history.cursor-1].index : this.history.steps[this.history.cursor].index;
this.history=next; this.refreshHints(hints); this.selected=index;
if (next.state.board[index]===0) {
this.info=readCandidate(update.cache,index); this.candidateText=`候选:${digitsText(this.info.values)}`;
} else this.candidateText='目标格已填';
this.status=back ? '已撤销' : '已重做';
} catch (error) { this.status=error instanceof Error ? error.message : '历史操作失败'; }
}
private reset(): void {
this.history=createHistory(); this.cache=createCache(this.history.state.board); this.changedCount=0; this.affectedCount=81; this.recomputedCount=51; this.refreshHints(hintsFromCache(this.cache,this.history.state)); this.selected=2;
this.rowText='1'; this.colText='3'; this.digitText='1';
this.info=queryCandidates(this.history.state.board,2); this.candidateText='候选:1、2、4'; this.status='已恢复题面';
}
@Builder
accessiblePanel(width: number) {
Column({space:12}) {
Text(describeCell(this.history.state,this.selected)).fontSize(22)
.accessibilityText(describeCell(this.history.state,this.selected))
Text(this.candidateText)
Text('F6提交 · F7查询 · F8撤销 · F9重做')
Button('上一格').accessibilityText('选择前一个格子,不改动数字').onClick(() => { this.moveTarget(-1); })
Button('下一格').accessibilityText('选择后一个格子,不改动数字').onClick(() => { this.moveTarget(1); })
Text(`有效步骤:${this.history.cursor}`)
Text(`已填格:${this.history.state.board.filter((v: number) => v!==0).length} · 空格:${this.history.state.board.filter((v: number) => v===0).length}`)
Text(this.status)
}.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
}
@Builder
cachePanel(width: number) {
Column({space:12}) {
Text(`当前:${Math.floor(this.selected/9)+1}行${this.selected%9+1}列`).fontSize(22)
Text(`当前格值:${this.history.state.board[this.selected]}`)
Text(`变化格数:${this.changedCount}`)
Text(`影响格数:${this.affectedCount}`)
Text(`重算空格:${this.recomputedCount}`)
Text(`缓存空格:${this.cache.entries.filter((item: CandidateInfo | null) => item!==null).length}`)
Text(this.candidateText)
Text(`已填格:${this.history.state.board.filter((v: number) => v!==0).length} · 空格:${this.history.state.board.filter((v: number) => v===0).length}`)
}.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
}
@Builder
searchPanel(width: number) {
Column({space:12}) {
if (this.report.boardKey===this.history.state.board.join('')) {
Text(`分析结论:${this.report.status}`).fontSize(26)
Text(`已找到解数:${this.report.solutions}`)
Text(`搜索节点:${this.report.nodes}`)
Text(`预算截断:${this.report.cutoff ? '是' : '否'}`)
} else { Text('分析结论:待分析').fontSize(26) }
Text(`当前已填:${this.history.state.board.filter((v: number) => v!==0).length}`)
Text(`当前空格:${this.history.state.board.filter((v: number) => v===0).length}`)
Text(`已应用步骤:${this.history.cursor}`)
Text('搜索参数').fontSize(22)
TextInput({text:this.budgetText,placeholder:'节点预算1至10000'})
.onChange((v: string) => { this.budgetText=v; })
Button('分析当前题面').backgroundColor('#445F97').onClick(() => { this.analyze(); })
Text(this.status)
}.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
}
@Builder
historyPanel(width: number) {
Column({space:12}) {
Text(`当前:${Math.floor(this.selected/9)+1}行${this.selected%9+1}列`).fontSize(22)
Text(`当前格值:${this.history.state.board[this.selected]}`)
Text(`已应用步骤:${this.history.cursor}`)
Text(`可撤销:${this.history.cursor} · 可重做:${this.history.steps.length-this.history.cursor}`)
if (this.history.cursor>0) {
Text(`最近步骤:${this.history.steps[this.history.cursor-1].before}→${this.history.steps[this.history.cursor-1].after}`)
}
Button('撤销').keyboardShortcut(FunctionKey.F8,[]).accessibilityText('撤销上一条已应用步骤,快捷键F8').enabled(this.history.cursor>0).onClick(() => { this.travel(true); })
Button('重做').keyboardShortcut(FunctionKey.F9,[]).accessibilityText('重做下一条历史步骤,快捷键F9').enabled(this.history.cursor<this.history.steps.length).onClick(() => { this.travel(false); })
Text(`已填格:${this.history.state.board.filter((v: number) => v!==0).length} · 空格:${this.history.state.board.filter((v: number) => v===0).length}`)
Text(`题面冲突:${findConflicts(this.history.state.board).length}组`)
}.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
}
@Builder
hintDetail(hint: SingleHint) {
Column({space:12}) {
Text(`提示:${hintText(hint)}`).fontSize(22)
Text(`行已用:${digitsText(hint.info.rowUsed)}`)
Text(`列已用:${digitsText(hint.info.colUsed)}`)
Text(`宫已用:${digitsText(hint.info.boxUsed)}`)
Text(`剩余候选:${hint.value}`).fontSize(26).fontColor('#445F97')
Button('应用当前提示').backgroundColor('#445F97').onClick(() => { this.applyHint(hint); })
}.width('100%')
}
@Builder
hintPanel(width: number) {
Column({space:12}) {
Text('题面导入导出与回归核验').fontSize(22)
Text(`单格唯一候选:${this.hints.length}处`)
Flex({direction:FlexDirection.Row,wrap:FlexWrap.Wrap}) {
ForEach(this.hints,(hint: SingleHint) => {
Button(hintText(hint)).fontSize(12).width((width-56)/3).margin(4)
.backgroundColor(hint.index===this.hintIndex ? '#445F97' : '#A8B8D7')
.onClick(() => { this.hintIndex=hint.index; })
},(hint: SingleHint) => `${hint.index}`)
}.width('100%')
ForEach(this.hints.filter((hint: SingleHint) => hint.index===this.hintIndex),(hint: SingleHint) => {
this.hintDetail(hint)
},(hint: SingleHint) => `${hint.boardKey}:${hint.index}`)
if (this.hints.length===0) { Text('当前没有单格唯一候选') }
Text(`已填格:${this.history.state.board.filter((value: number) => value!==0).length} · 空格:${this.history.state.board.filter((value: number) => value===0).length}`)
Text(`题面冲突:${findConflicts(this.history.state.board).length}组`)
}.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
}
@Builder
inputPanel(width: number) {
Column({space:12}) {
Text('目标格输入').fontSize(22)
TextInput({text:this.rowText,placeholder:'行'}).accessibilityText('目标行,输入一至九')
.onChange((value: string) => { this.rowText=value; this.status='输入待查询'; })
TextInput({text:this.colText,placeholder:'列'}).accessibilityText('目标列,输入一至九')
.onChange((value: string) => { this.colText=value; this.status='输入待查询'; })
TextInput({text:this.digitText,placeholder:'填入0至9,0清空'}).accessibilityText('填入值,零表示清空')
.onChange((value: string) => { this.digitText=value; this.status='输入待提交'; })
Button('提交填数').keyboardShortcut(FunctionKey.F6,[]).accessibilityText('提交当前行列与填入值,快捷键F6').backgroundColor('#445F97').onClick(() => { this.submit(); })
Button('查询候选').keyboardShortcut(FunctionKey.F7,[]).accessibilityText('查询输入行列的候选,快捷键F7').backgroundColor('#445F97').onClick(() => { this.query(); })
Text(this.status)
Text(`已填格:${this.history.state.board.filter((value: number) => value!==0).length}`)
Text(`空格:${this.history.state.board.filter((value: number) => value===0).length}`)
}.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
}
@Builder
resultPanel(width: number) {
Column({space:14}) {
Text(`目标:${Math.floor(this.selected/9)+1}行${this.selected%9+1}列`).fontSize(22)
Text(`当前格值:${this.history.state.board[this.selected]}`)
Text(`题面冲突:${findConflicts(this.history.state.board).length}组`)
Text(`有效修改:${this.history.cursor}`)
if (this.history.state.board[this.selected]===0) {
Text(`行已用:${digitsText(this.info.rowUsed)}`)
Text(`列已用:${digitsText(this.info.colUsed)}`)
Text(`宫已用:${digitsText(this.info.boxUsed)}`)
}
Text(this.candidateText).fontSize(26).fontColor('#445F97')
Button('恢复题面').onClick(() => { this.reset(); })
}.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
}
private exportText(): void {
try { this.exchangeText=exportPuzzle(this.history.state);
this.exchangeStatus=checkPuzzleRoundTrip(this.history.state) ? '往返核验通过' : '往返核验失败';
} catch (error) { this.exchangeStatus=error instanceof Error ? error.message : '导出失败'; }
}
private importText(): void {
try {
const state: PuzzleState = importPuzzle(this.exchangeText);
const cache: CandidateCache = createCache(state.board);
const hints: SingleHint[] = hintsFromCache(cache,state);
const history: PuzzleHistory = {state,steps:[],cursor:0};
const info: CandidateInfo = state.board[this.selected]===0 ? readCandidate(cache,this.selected) : this.info;
this.history=history; this.cache=cache; this.hints=hints; this.info=info;
this.hintIndex=hints.length>0 ? hints[0].index : -1; this.report=idleReport();
this.changedCount=0; this.affectedCount=81; this.recomputedCount=state.board.filter((v: number) => v===0).length;
this.rowText=`${Math.floor(this.selected/9)+1}`; this.colText=`${this.selected%9+1}`;
this.candidateText=state.board[this.selected]===0 ? `候选:${digitsText(info.values)}` : '目标格已填';
this.status='已导入题面'; this.exchangeStatus='导入完成,历史已重置';
} catch (error) { this.exchangeStatus=error instanceof Error ? error.message : '导入失败'; }
}
@Builder
exchangePanel(width: number) {
Column({space:12}) {
Text('文本交换').fontSize(22)
TextArea({text:this.exchangeText,placeholder:'粘贴待导入文本'})
.height(150).onChange((value: string) => { this.exchangeText=value; this.exchangeStatus='文本待导入'; })
Button('导出当前数据').onClick(() => { this.exportText(); })
Button('导入文本').onClick(() => { this.importText(); })
Text(this.exchangeStatus)
}.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
}
build() {
Scroll() {
Column({space:16}) {
Text('数独候选台').fontSize(26).fontWeight(FontWeight.Bold)
Text('题面导入导出与回归核验')
if (this.areaWidth>=840) {
Row({space:16}) {
Column({space:16}) {
this.exchangePanel((this.areaWidth-56)/2)
this.accessiblePanel((this.areaWidth-56)/2)
this.cachePanel((this.areaWidth-56)/2)
this.searchPanel((this.areaWidth-56)/2)
this.historyPanel((this.areaWidth-56)/2)
this.hintPanel((this.areaWidth-56)/2)
}
Column({space:16}) {
this.inputPanel((this.areaWidth-56)/2)
this.resultPanel((this.areaWidth-56)/2)
}
}.alignItems(VerticalAlign.Top)
} else {
this.exchangePanel(this.areaWidth-40)
this.accessiblePanel(this.areaWidth-40)
this.cachePanel(this.areaWidth-40)
this.searchPanel(this.areaWidth-40)
this.historyPanel(this.areaWidth-40)
this.hintPanel(this.areaWidth-40)
this.inputPanel(this.areaWidth-40)
this.resultPanel(this.areaWidth-40)
}
}.width('100%').padding(20)
}.width('100%').height('100%').backgroundColor('#F1F4FA')
.onAreaChange((oldArea: Area,newArea: Area) => {
const width: number = Number(newArea.width);
if (Number.isFinite(width) && width>40 && width!==this.areaWidth) this.areaWidth=width;
})
}
}
这样处理可以避免旧步骤在新题盘上重放。即便前后内容同属固定题目,旧步骤中的before和after也未必满足导入后的状态。导入后清空历史,比保留一条看似可用的撤销链更明确;用户看见有效步骤为零,可以理解当前进度是新的编辑起点。
本篇没有把导入本身记成一条普通填数步骤,因为它可能改变多个位置,也没有单一格子的before和after。若产品要求撤销整次导入,应另设完整状态检查点,并定义它与逐格历史的关系,不能借用现有单格步骤结构硬塞多个变化。
候选与搜索各自恢复一致性
导入可能改变任意多个可编辑格,因此本篇使用createCache完整建立新缓存。统计中的受影响位置为八十一,重算数量为新状态中的空格数。它与上一章一次填数的局部刷新有不同触发条件,不把完整导入伪装成只改一个位置的增量更新。
单格提示使用新缓存和新状态生成。搜索报告恢复为待分析,旧报告的解数量、首个解和节点数不继续展示为新进度的结论。当前selected仍保留位置身份,输入框行列同步到它;若该格已填,摘要显示目标格已填,若为空则从新缓存读取候选。

示例文本导入后,一行三列为可编辑格、当前数字一,已填格三十一、空格五十,有效步骤为零。这里与手动填入一之后的区别在于历史游标,而不是board内容。比较这两条路径时,应同时检查棋盘与历史,不能只看相同的数字摘要。
文本编辑不触发题盘发布
交换面板的TextArea用onChange接收完整文本,并把交换提示更新为文本待导入。用户删掉一个字符时,当前board和历史不变化,只有点击导入文本才进入解析。错误文本仍留在输入框,提示说明拒绝原因,用户可以继续修正而不丢掉输入。
宽屏与窄屏使用同一份exchangeText和exchangeStatus,原有history、cache和selected也只有一份。布局回调只调整可用宽度。输入框中的换行与自动折行是不同层次:格式由实际换行字符解析,页面显示的折行不增加记录数量。
回归样本需要包含失败路径
可以先导出默认题目,再通过原编辑入口在一行三列填入一并导出;分别导入两份文本,核对空格数量、目标格描述、候选与提示是否随状态恢复。再检查导入后撤销与重做按钮均不可用,新增一步之后才重新出现有效的撤销路径。
拒绝样本包括未知版本、缺少进度行、额外非空行、固定题面改变、固定格被清空,以及一行三列写入与该行冲突的五。每次失败都应保留旧题盘、旧缓存和旧历史,只改变交换提示。保存失败前后的board字符串和游标进行比较,有助于发现解析中途发布状态的问题。
还要检查不同换行形式和数组隔离。服务接收常见的回车换行,并统一为换行符;导入生成的board与givens是新数组。修改返回对象不能反向修改导入前的状态,导出函数也不能改变源数组。往返字符串相等与独立副本检查共同覆盖了内容和引用两个层面。
这套进度交换把数独候选台的候选、冲突、提示、历史、搜索、缓存与可访问性描述重新连接到同一个事实来源。格式负责表达题目身份与数字,服务负责合法性,页面负责整体发布和新的历史起点。不同输入渠道沿用同一条恢复链,才能让相同进度得到一致的工程行为。
相关资料
更多推荐




所有评论(0)