You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何优化TypeScript跳棋游戏的棋子有效相邻坐标查询函数

TypeScript跳棋相邻坐标获取代码优化方案

核心优化点

  • 类型系统优化
    • 原CornerType使用任意字符串作为key过于宽松,可替换为固定方向的字面量类型,也可根据业务需要直接返回string[]格式的有效坐标数组,减少后续使用时的类型判断成本
    • 把玩家、方向这类固定值抽为枚举,避免硬编码字符串出现拼写错误
  • 消除魔法值
    • 把代码里硬编码的棋盘边界(0、7、9)、ASCII偏移量97、玩家标识等全部抽为常量,后续调整棋盘规则时只需要修改常量即可,无需到处查找硬编码值
  • 减少重复逻辑
    • 原代码四个方向的判断逻辑在王棋、玩家1、玩家2分支里重复写了三次,可以提前根据棋子属性拿到允许的移动方向,统一遍历生成坐标,大幅降低维护成本
  • 消除副作用与冗余流程
    • 去掉deleteNullCorners这个修改入参的副作用方法,改为仅当坐标合法时才加入返回对象,不需要先赋值null再执行删除操作
    • 简化边界判断逻辑,避免重复的false校验
  • 增加入参校验
    • 可增加对传入坐标格式的合法性校验,提前拦截非法输入避免后续逻辑报错

优化后代码示例

// 全局常量定义
const MIN_COL = 0
const MAX_COL = 7
const MIN_ROW = 1
const MAX_ROW = 8
const CHAR_CODE_A = 97

// 枚举定义
enum Player {
  One = "Player One",
  Two = "Player Two"
}

// 方向定义结构:[列偏移量, 行偏移量, 方向名]
const ALL_DIRECTIONS = [
  [-1, 1, 'leftUpper'],
  [1, 1, 'rightUpper'],
  [-1, -1, 'leftLower'],
  [1, -1, 'rightLower']
] as const

// 更严格的返回值类型
type CornerType = Partial<{
  leftUpper: string
  rightUpper: string
  leftLower: string
  rightLower: string
}>

interface Piece {
  isKing: boolean
  player: Player
}

const getPieceCornersCoordinates = (coordinates: string, piece: Piece): CornerType => {
  const {row, col} = convertStringCoordinatesToNumberCoordinates(coordinates)
  const corners: CornerType = {}

  // 筛选当前棋子允许的移动方向
  const allowedDirections = ALL_DIRECTIONS.filter(([_, rowOffset]) => {
    if (piece.isKing) return true
    return piece.player === Player.One ? rowOffset === -1 : rowOffset === 1
  })

  for (const [colOffset, rowOffset, direction] of allowedDirections) {
    const newCol = col + colOffset
    const newRow = row + rowOffset
    // 边界合法性校验
    if (newCol < MIN_COL || newCol > MAX_COL || newRow < MIN_ROW || newRow > MAX_ROW) continue
    // 转换为字符串坐标格式
    const colStr = String.fromCharCode(newCol + CHAR_CODE_A)
    corners[direction] = `${colStr}${newRow}`
  }

  return corners
}

内容的提问来源于stack exchange,提问作者Nero Bello

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 22:00:00