目前已更新,所以每个旧的“功能”都已移到我的课程之下。现在似乎我唯一的问题之一就是找出所有这些drawBoard() takes 1 positional argument but 2 were given
这只是我当前课程的开始,只是为了向您展示我目前正在处理的内容
答案 0 :(得分:0)
正如我在评论中所说,我认为你应该在类BoardHandler
的方法中创建两个函数。这将为您提供更好的encapsulation,而且相当容易实现,具体如下:
class BoardHandler:
def __init__ (self, size, board):
self.size = size
self.board = board
def ask_size(self):
try:
self.size = int(input("Which size would you want?"))
except ValueError:
print("Wrong! try again")
ask_size()
def getNewBoard(self):
board=[]
for i in range(self.size):
board.append([' ']* self.size)
self.board = board
def resetBoard(self):
for x in range(self.size):
for y in range(self.size):
self.board[x][y] = ' '
n=int(size/2-1)
self.board[n][n] = 'B'
self.board[n+1][n] = 'W'
self.board[n][n+1] = 'W'
self.board[n+1][n+1] = 'B'
def drawBoard(self):
HLINE = ' ----------------------------------------'
for y in range(self.size):
print(y+1, end=' ')
for x in range(Q):
print('| %s' % (self.board[x][y]), end=' ')
print('|')
print(HLINE)
如果由于某种原因想要将它们保留在类之外,则需要修改它们中的每一个以接受BoardHandler
类实例作为参数:
def resetBoard(board_handler):
for x in range(board_handler.size):
for y in range(board_handler.size):
board_handler.board[x][y] = ' '
n=int(board_handler.size/2-1)
board[n][n] = 'B'
board[n+1][n] = 'W'
board[n][n+1] = 'W'
board[n+1][n+1] = 'B'
def drawBoard(board_handler):
HLINE = ' ----------------------------------------'
for y in range(board_handler.size):
print(y+1, end=' ')
for x in range(Q):
print('| %s' % (board_handler.board[x][y]), end=' ')
print('|')
print(HLINE)
这假设您的程序创建了一个BoardHandler
类实例,并对该对象执行了所有操作。
答案 1 :(得分:0)
根据以下内容进行更新:
程序的每次运行都会给出选项的大小 应该 ... 代码中的每个板都应该是相同的大小
我们将size
设为一个类变量,如果尚未设置,则只提示大小。所有后续的电路板创建将使用与第一块电路板相同的尺寸:
class BoardHandler:
size = None
def __init__(self):
self.board = None
if BoardHandler.size is None:
self.ask_size()
self.getNewBoard()
def ask_size(self): # no self use, method could be a function
while True:
try:
BoardHandler.size = int(input("Which size would you want? "))
break
except ValueError:
print("Wrong! try again")
def getNewBoard(self):
self.board = []
for _ in range(BoardHandler.size):
self.board.append([' '] * BoardHandler.size)
def resetBoard(self):
for x in range(BoardHandler.size):
for y in range(BoardHandler.size):
self.board[x][y] = ' '
n = int(BoardHandler.size / 2 - 1)
self.board[n][n] = 'B'
self.board[n + 1][n] = 'W'
self.board[n][n + 1] = 'W'
self.board[n + 1][n + 1] = 'B'
def drawBoard(self):
HLINE = ' ' + '-' * (4 * BoardHandler.size) + '-'
print(HLINE)
for y in range(BoardHandler.size):
print("{:2d}".format(y + 1), end=' ')
for x in range(BoardHandler.size):
print('| {}'.format(self.board[x][y]), end=' ')
print('|')
print(HLINE)
handler = BoardHandler()
handler.resetBoard()
handler.board[0][0] = 'W'
handler.drawBoard()
print(BoardHandler.size)
handler2 = BoardHandler()
handler2.drawBoard() # empty board but same size as first