如何解决如果我有一个功能与另一个功能基本相同,那么加入它们的最佳方法是什么?
我有一个显示战舰游戏“面板”的功能。然后是另一个功能,该功能可显示同一块木板,但隐藏其中有船的斑点(以免将其散发给用户)。代码是:
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= " ")
row = self.board[i]
for j in row:
if j == self.aboathere:
print(self.noboat,end=" ")
else:
print(j,end=" ")
i += 1
print("\n")
有一个微小的区别,即隐藏在“ for j in row”下面的if结构,但其功能基本相同。它工作正常,但似乎有点多余。如何改善呢?
解决方法
最简单的解决方案可能是在函数中添加一个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")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。