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

如何为棋盘数组索引匹配国际象棋代数记法?

解决国际象棋棋盘数组索引与代数记法的映射问题

先明确你的棋盘索引和代数记法的对应规则:

  • 数组行索引(board[row][col]):0对应代数记法的8,7对应1,即数字部分为 8 - row
  • 数组列索引:0对应a,1对应b……7对应h,即字母部分为 chr(ord('a') + col)

方法1:封装转换函数

写一个简单函数,输入数组的行、列索引,直接返回对应的代数记法:

def index_to_algebraic(row, col):
    letter = chr(ord('a') + col)
    number = 8 - row
    return f"{letter}{number}"

测试验证:

print(index_to_algebraic(0, 0))  # 输出 'a8'
print(index_to_algebraic(7, 7))  # 输出 'h1'

方法2:遍历棋盘时同步生成位置

如果要遍历整个棋盘,同时获取每个格子的代数记法,可结合枚举实现:

board = [
['|__|', '|__|', '|__|', '|__|', '|__|', '|__|', '|__|', '|__|'],
['|__|', '|__|', '|__|', '|__|', '|__|', '|__|', '|__|', '|__|'],
['|__|', '|__|', '|__|', '|__|', '|__|', '|__|', '|__|', '|__|'],
['|__|', '|__|', '|__|', '|__|', '|__|', '|__|', '|__|', '|__|'],
['|__|', '|__|', '|__|', '|__|', '|__|', '|__|', '|__|', '|__|'],
['|__|', '|__|', '|__|', '|__|', '|__|', '|__|', '|__|', '|__|'],
['|__|', '|__|', '|__|', '|__|', '|__|', '|__|', '|__|', '|__|'],
['|__|', '|__|', '|__|', '|__|', '|__|', '|__|', '|__|', '|__|'],
]

for row_idx, row in enumerate(board):
    for col_idx, cell in enumerate(row):
        pos = index_to_algebraic(row_idx, col_idx)
        print(f"格子 {pos} 的内容:{cell}")

方法3:反向转换(代数记法转数组索引)

如果需要从代数记法反推数组索引,也可以写对应的函数:

def algebraic_to_index(pos):
    letter = pos[0].lower()
    number = int(pos[1])
    row = 8 - number
    col = ord(letter) - ord('a')
    return (row, col)

测试验证:

print(algebraic_to_index('a8'))  # 输出 (0, 0)
print(algebraic_to_index('h1'))  # 输出 (7, 7)

内容的提问来源于stack exchange,提问作者Justin Young

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 11:24:59