象棋中的毕肖普运动

2024-06-26 13:25:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我在为Python3号的一个学校项目做象棋游戏。 我被主教运动困住了。我做了所有的动作,但主教真的很难。下面是我如何编码我的董事会:

board=[["R1W","C1W","F1W","K1W","D1W","F2W","C2W","R2W"],
       ["P1W","P2W","P3W","P4W","P5W","P6W","P7W","P8W"],
       ["___","___","___","___","___","___","___","___"],
       ["___","___","___","___","___","___","___","___"],
       ["___","___","___","___","___","___","___","___"],
       ["___","___","___","___","___","___","___","___"],
       ["P1N","P2N","P3N","P4N","P5N","P6N","P7N","P8N"],
       ["R1N","C1N","F1N","D1N","K1N","F2N","C2N","R2N"]]

下面是我如何规划我的主教:

^{pr2}$

只有lmn、和{}改变了一半代码。 我的问题是即使n>c,它也显示"fau",而不是{}

以下是我申请职位的方式:

l = int(input("ligne de selection?:\n"))-1 #on demande au joueur la ligne de la piece a selectionné
c = int(input("colonne de selection?:\n"))-1#on demande au joueur la colonne de la piece a selectionné
m = int(input("ligne de destination ?:\n"))-1#on demande au joueur la ligne ou il veut pose la piece
n = int(input("colonne de destination?:\n"))-1#on demande au joueur la colonne ou il veut pose la piece
piece = board[l][c] # piece correspond a la piece selectionné

Tags: boardinputpieceondelaintau
2条回答

多亏了布鲁诺L,它现在工作得很好,这是我使用的主教代码,这是一个简化版本:

def fou_valide(piece,l,m,c,n,):
if piece[0]=="F":#F in french stand for bishop, "Fou", 
    if l!=m and  n!=c  and abs(l-m)==abs(c-n): #the condition for the bishop movement
        dl = sign(m - l)#it get the me direction of the movement
        dc = sign(n - c)
        x, y = c + dc, l + dl
        while x != n and y != m:#This check if they are any non-empty cell on the way
            if board[y][x] != '___': # non empty cell
                return False
            x += dc
            y += dl
        return True
    return False
return True

符号功能如下:

^{pr2}$

实际上,piece是有用的,因为你有l和{}。
在您的函数中,您必须验证四件事。在

1)这件作品确实是主教
2) l和{}不同于m和{}
3) 它们在同一对角线上
4) 两者之间的细胞是自由的

4)是最难的,除非你注意到你需要检查的方向是(sign(m - l), sign(n - c))。不需要为每个方向或每种颜色编写不同的代码。在

编辑:没有内置的sign函数,您需要自己编写。在

def sign(n):
    return 1 if n >= 0 else -1

然后,您可以用一个while循环检查单元格,该循环适用于任何方向。在

^{pr2}$

相关问题 更多 >