gpt4 book ai didi

python - 国际象棋程序OO设计

转载 作者:行者123 更新时间:2023-12-01 05:57:47 26 4
gpt4 key购买 nike

在我的国际象棋程序中,我有一个名为 Move 的类。它存储了工件被取出和放置的位置。这是什么棋子以及被捕获的棋子是什么。

问题是,为了获取被移动和捕获的棋子,我将整个 Board 对象传递给 __init__ 方法。因此,在我看来,我似乎应该将所有 Move 类方法存储到 Board 类,该类也有一个方法可以获取给定方 block 上的棋子。

我刚刚开始学习面向对象,因此非常感谢有关此的一些建议,也许还有一些更通用的设计决策。

这是我认为最好省略的 Move 类?

class Move(object):

def __init__(self, from_square, to_square, board):
""" Set up some move infromation variables. """
self.from_square = from_square
self.to_square = to_square
self.moved = board.getPiece(from_square)
self.captured = board.getPiece(to_square)

def getFromSquare(self):
""" Returns the square the piece is taken from. """
return self.from_square

def getToSquare(self):
""" Returns the square the piece is put. """
return self.to_square

def getMovedPiece(self):
""" Returns the piece that is moved. """
return self.moved

def getCapturedPiece(self):
""" Returns the piece that is captured. """
return self.captured

最佳答案

当您创建一个对象时,您正在创建一个事物。棋盘和棋盘上的棋子都是东西。当您希望与这些事物交互时,您需要一种方式来做到这一点 - 或一个动词。

这仅作为建议方法,以避免使用 Move 类。我打算做什么:

  • 创建代表棋盘和棋盘上所有棋子的对象。
  • Subclass代表单个 block 运动特征的所有 block 的类,以及 override特定于片段的 Action ,例如移动。

我从编写Board开始;您可以稍后决定如何表示位置。

class Board:
def __init__(self):
self.board = [['-' for i in xrange(8)] for j in xrange(8)]
# You would have to add logic for placing objects on the board from here.

class Piece:
def __init__(self, name):
self.name = name
def move(self, from, to):
# You would have to add logic for movement.
def capture(self, from, to):
# You would have to add logic for capturing.
# It's not the same as moving all the time, though.

class Pawn(Piece):
def __init__(self, name=""):
Piece.__init__(self, name)
def move(self, from, to):
# A rule if it's on a starting block it can move two, otherwise one.
def capture(self, from, to):
# Pawns capture diagonal, or via en passant.

关于python - 国际象棋程序OO设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11711860/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com