/** * 棋盘布局纯数学核心(引擎无关) * 给定棋盘行列数和可用空间,计算格子大小和偏移。 * Phaser 版和 Three.js 版都可以引用此模块。 */ export interface BoardLayoutParams { rows: number; cols: number; availableWidth: number; availableHeight: number; marginRatio?: number; // 边距比例,默认 0.07 spacingMultiplier?: number; // 格子间距放大系数,默认 1.15 } export interface BoardLayoutResult { cellSize: number; // 基础格子大小 cellWidth: number; // 实际格子宽度(含间距) cellHeight: number; // 实际格子高度(含间距) boardWidth: number; // 棋盘总宽度 boardHeight: number; // 棋盘总高度 offsetX: number; // 棋盘左上角 X 偏移(居中) offsetY: number; // 棋盘左上角 Y 偏移(居中) } /** * 计算棋盘布局(纯数学,零引擎依赖) */ export function computeBoardLayout(params: BoardLayoutParams): BoardLayoutResult { const { rows, cols, availableWidth, availableHeight, marginRatio = 0.07, spacingMultiplier = 1.15, } = params; const usableWidth = availableWidth * (1 - 2 * marginRatio); const usableHeight = availableHeight * (1 - 2 * marginRatio); // 计算基础格子大小(取宽高中更受限的方向) const baseSize = Math.max( 4, Math.floor(Math.min(usableWidth / cols, usableHeight / rows)) ); // 应用间距系数 const cellWidth = Math.floor(baseSize * spacingMultiplier); const cellHeight = cellWidth; // 正方形格子 const boardWidth = cellWidth * cols; const boardHeight = cellHeight * rows; // 居中偏移 const offsetX = (availableWidth - boardWidth) / 2; const offsetY = (availableHeight - boardHeight) / 2; return { cellSize: baseSize, cellWidth, cellHeight, boardWidth, boardHeight, offsetX, offsetY, }; } /** * 计算格子中心坐标(基于偏移和格子大小) */ export function getCellCenter( col: number, row: number, cellWidth: number, cellHeight: number, offsetX: number, offsetY: number ): { x: number; y: number } { return { x: offsetX + col * cellWidth + cellWidth / 2, y: offsetY + row * cellHeight + cellHeight / 2, }; }