繁体   English   中英

如何从二维列表中的坐标获取对角线?

[英]How to get diagonals from a coordinate in a 2D list?

我想做主教。

这是我现在所拥有的快速追赶:

class Piece:
    def __init__(self, team, coord, name):
        self.naame = name
        self.value = 0
        self.team = team
        self.coord = coord
        legal_moves = []
        capture_moves = []


class Pawn(Piece):
    def __init__(self, team, coord):
        super().__init__(team, coord, name='Pawn')
        legal_moves = [[0, 1]]
        capture_moves = [[-1, 1], [1, 1]]
        self.value = 1


class Bishop(Piece):
    def __init__(self, team, coord):
        super().init(team, coord, name='Bishop')
        legal_moves = 


class Board():
    def __init__(self):
        self.grid = [['x' for i in range(8)] for i in range(8)]

    def get_coord(self, x, y):
        return self.grid[x][y]

坐标基本上是[['x' for i in range(8)] for i in range(8)] ,并且在我为 pawn 给出的示例中最容易解释合法移动。 我如何为主教做这样的事情? 我在想一个很长的列表理解,但我不完全知道它的语法。

我不太了解装饰器,但我看到了一些关于@property东西,看起来很有趣

您可以使用itertools.product和嵌套理解:

from itertools import product

moves = [(i*x, i*y) for x, y in product((-1, 1), repeat=2) for i in range(1, 8)]
# [(-1, -1), (-2, -2), (-3, -3), (-4, -4), (-5, -5), (-6, -6), (-7, -7), 
#  (-1, 1), (-2, 2), (-3, 3), (-4, 4), (-5, 5), (-6, 6), (-7, 7), 
#  (1, -1), (2, -2), (3, -3), (4, -4), (5, -5), (6, -6), (7, -7),
#  (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7)]

由于您使用coord调用它,因此您可能已经限制了此处的移动以保持在板的范围内:

x, y = coord = (3, 3)
legal_moves = [(dx, dy) for dx, dy in moves if 0 <= x+dx < 8 and 0 <= y+dy < 8]
# [(-1, -1), (-2, -2), (-3, -3), 
#  (-1, 1), (-2, 2), (-3, 3), 
#  (1, -1), (2, -2), (3, -3), 
#  (1, 1), (2, 2), (3, 3), (4, 4)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM