#python #python-3.x #refactoring #code-reuse
#python #python-3.x #рефакторинг #повторное использование кода
Вопрос:
У меня есть функция, которая отображает «доску» игры battleships. Затем другая функция, которая отображает ту же доску, но скрывает места, на которых есть лодки (чтобы не отдавать их пользователю). Код:
def display(self):
os.system("cls")
print("Displaying {} grid n".format(self.name))
i = 0 #this block prints column numbers
print("O", end=" ")
for h in range(1,10 1):
print(h,end=" ")
print("n")
while i < 10: #this block prints row letters and board
print(chr(i 65), end= " ")
row = self.board[i]
for j in row:
print(j, end=" ")
i = 1
print("n")
def hide (self):
os.system("cls")
print("Displaying {} grid n".format(self.name))
i = 0 #this block prints column numbers
print("O", end=" ")
for h in range(1,10 1):
print(h,end=" ")
print("n")
while i < 10: #this block prints row letters and board
print(chr(i 65), end= " ")
row = self.board[i]
for j in row:
if j == self.aboathere:
print(self.noboat, end=" ")
else:
print(j, end=" ")
i = 1
print("n")
Есть небольшая разница, структура if ниже «для j в строке» в hide, но в основном это та же функция. Это работает нормально, но кажется излишним. Как это можно улучшить?
Ответ №1:
Самым простым решением может быть добавление аргумента switch в вашу функцию, которая будет показывать / скрывать лодки:
def show_board(self, show_boats=False):
os.system("cls")
print("Displaying {} grid n".format(self.name))
i = 0 # this block prints column numbers
print("O", end=" ")
for h in range(1, 10 1):
print(h, end=" ")
print("n")
while i < 10: # this block prints row letters and board
print(chr(i 65), end=" ")
row = self.board[i]
for j in row:
if j == self.aboathere:
print(j if show_boats else self.noboat, end=" ")
else:
print(j, end=" ")
i = 1
print("n")