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

Python判断国际象棋象能否单次沿对角线移动到达目标位置

象棋象步合法性判断逻辑修正

现有代码问题

  • 仅判断了坐标的增减方向匹配,未校验横纵移动的距离是否相等,会把非对角线的斜向移动误判为合法,比如起点(2,3)、终点(3,5)就会被错误判定为合法移动
  • 仅校验了终点坐标在棋盘范围内,未校验起点坐标的合法性
  • 没有处理起点和终点为同一格子的边界情况

核心逻辑提示

国际象棋的象沿对角线移动的核心数学特征是:横纵坐标的差值的绝对值完全相等,无需单独判断增减方向,只要满足abs(终点列号 - 起点列号) == abs(终点行号 - 起点行号),就属于合法的一步移动。

修正后代码示例

# 读取输入
initial_x = int(input('enter the initial x'))
initial_y = int(input('enter the initial y'))
final_x = int(input('enter the final x'))
final_y = int(input('enter the final y'))

# 校验所有坐标都在棋盘范围内
if 1 <= initial_x <=8 and 1 <= initial_y <=8 and 1 <= final_x <=8 and 1 <= final_y <=8:
    # 校验不是同一个格子 + 对角线判断
    if (initial_x != final_x or initial_y != final_y) and abs(final_x - initial_x) == abs(final_y - initial_y):
        print("YES")
    else:
        print("NO")
else:
    print("illegal move, you moved outside the chessboard")

内容的提问来源于stack exchange,提问作者Emilia Delizia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 19:57:03