【发布时间】:2020-10-05 05:50:15
【问题描述】:
我有一个显示战舰游戏“棋盘”的功能。然后是另一个功能,显示相同的板,但隐藏其中有船的地点(以免将它们交给用户)。代码是:
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")
在hide中“for j in row”下面的if结构略有不同,但功能基本相同。它工作正常,但似乎有点多余。如何改进?
【问题讨论】:
标签: python python-3.x refactoring code-reuse