【问题标题】:Queen moves function does not return correct number of moves皇后移动功能不返回正确的移动数量
【发布时间】:2021-07-25 11:41:56
【问题描述】:

这是我计算女王对角线所有可能移动的函数:

def dia(n, r_q, c_q, obs):
    ans = 0

    # up right
    cnt = 1
    while cnt + r_q <= n and cnt + c_q <= n:
        if [cnt + r_q, cnt + c_q] in obs:
            break
        ans += 1 
        cnt += 1
    
    # down left    
    cnt = 1
    while r_q - cnt >= 1 and c_q - cnt >= 1: 
        if [r_q - cnt, c_q - cnt] in obs:
            break
        ans += 1 
        cnt += 1

    # left up
    cnt = 1
    while r_q - cnt >= 1 and c_q + cnt <= n:      
        if [r_q - cnt, c_q + cnt] in obs:
            break
        print([r_q - cnt, c_q + cnt])
        ans += 1 
        cnt += 1

    # right down   
    cnt = 1
    while r_q + cnt <= n and c_q - cnt >= 1:      
        if [r_q + cnt, c_q - cnt]  in obs:
            break
        print([r_q + cnt, c_q - cnt])
        ans += 1 
        cnt += 1
    return ans

参数为:

  • n 电路板尺寸,即n=8 表示它是8x8 电路板。
  • r_q皇后区,
  • c_q女王专栏,
  • obs 皇后对角线上的所有障碍物。

有时它不能提供正确数量的可能移动。

我遗漏了什么,我该如何修复或找到此功能的更好实现?

【问题讨论】:

  • 如果障碍物的颜色是相反的(而不是国王,但这绝不应该发生),你需要在休息前添加一个,因为捕获那块是合法的。
  • 不,我不想考虑捕捉碎片,例如,正如您在图片中看到的那样,可能的移动只有 10 个,不包括障碍物(换句话说,如果障碍物是来自同一团队的作品)。
  • 图像显示垂直和水平线也应该被扫描。您的代码只查看对角线。你的问题的文字说你想计算对角线上的可能性:如果这是目的,你的代码会返回正确的结果:6。但图像还包括直线上的移动,然后等于 10。只需添加该逻辑如果这是你需要的,也可以。
  • 我知道,我已经构建了函数来计算行和列中可能的移动,仍然是对角线,并且计算行和列中的移动就好了唯一的问题是这个功能吗?
  • 请提供一个可重新创建的示例,其中您的代码输出不正确。

标签: python function chess python-chess


【解决方案1】:

此代码更好,您可以使用它来获取(对角线和直线)。

queenpos = [x, x]
directions = [(1, 0), (0, 1), (1, 1), (1, -1)]
for dir in directions:
    for m in [-1, 1]:
        d = dir * m
        for i in range(8):
            row = queenpos[0] + d[0]
            col = queenpos[1] + d[1]
            if row < 8 and row > -1 and col < 8 and col > -1:
            obs = board.getpiece(row, col)
            if obs is not None: break
            print(row, col)

这有点难以理解,但应该可以。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    • 2015-05-10
    • 2018-01-22
    相关资源
    最近更新 更多