簡體   English   中英

go 那里可以嗎? 國際象棋 function 斗爭在 Python

[英]Can piece go there? Chess function struggle in Python

我有一個棋盤大小的元組,對象包含它們的坐標,如果為真(白色)或假(黑色)

板:元組[int,列表[Piece]]

我正在嘗試編寫一個 function 來檢查該部件是否可以移動,在這種情況下,如果單元格未被占用,或者如果它被占用,請檢查它是否是同一側。 如果兩者都在同一側,假設為 True,並且 True 它不能在那里移動,如果它不同的一側將能夠移動到那里。

到目前為止,我已經發現我可以將 self 與元組中的片段進行比較,而做到這一點的唯一方法似乎是通過 for 循環。 問題是它包含布爾值,它與每個布爾值進行比較並返回究竟是什么?

你可以看到我的代碼 output 是正確的,當 2 相同時,它會說你不能 go 在那里,反之亦然。 但我需要返回一個布爾值。

有人可以幫助實現這一點嗎?

class Rook(Piece):
    def __init__(self, pos_X : int, pos_Y : int, side_ : bool):
        '''sets initial values by calling the constructor of Piece'''
        super().__init__(pos_X, pos_Y, side_)


    def can_reach(self, pos_X : int, pos_Y : int, B: Board) -> bool:
        '''
        checks if this rook can move to coordinates pos_X, pos_Y
        on board B according to rule [vertical and Horizontal move] and 
        [Rule4] A piece of side X (Black or White) cannot move to a location occupied by a piece of side X.] (see section Intro)
        Hint: use is_piece_at
        '''
      
        is_occupied = is_piece_at(pos_X, pos_Y, Board)
        if is_occupied == False:
          return True  #if it is not occupied you can always go there.
        if is_occupied == True:
          for piece in B[1]:
            print ("piece",piece.side_)
            print ("self",self.side_)
            if piece.side_== self.side_:
              print ("you can't go there")
              yes=
            elif piece.side_!= self.side_:
              print ("yes you can go there")
              
R0.can_reach(1,1, Board)

piece True
self True
you can't go there
piece False
self True
yes you can go there
piece False
self True
yes you can go there
True

如果你想在 for 循環中任何可能的選項為 False 時返回 False,你可以將一個參數默認設置為 True,如果遇到 False 移動則將其切換為 False。

這能解決您的問題嗎?:

class Rook(Piece):
    def __init__(self, pos_X : int, pos_Y : int, side_ : bool):
        '''sets initial values by calling the constructor of Piece'''
        super().__init__(pos_X, pos_Y, side_)


    def can_reach(self, pos_X : int, pos_Y : int, B: Board) -> bool:
        '''
        checks if this rook can move to coordinates pos_X, pos_Y
        on board B according to rule [vertical and Horizontal move] and 
        [Rule4] A piece of side X (Black or White) cannot move to a location occupied by a piece of side X.] (see section Intro)
        Hint: use is_piece_at
        '''
        reachable = True
        is_occupied = is_piece_at(pos_X, pos_Y, Board)
        if is_occupied == False:
          return reachable  #if it is not occupied you can always go there.
        else:
          for piece in B[1]:
            if piece.side_== self.side_:
              print ("you can't go there")
              reachable = False
          return reachable

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM