如果我有一个功能与另一个功能基本相同,那么加入它们的最佳方法是什么?

问题描述

我有一个显示战舰游戏“面板”的功能。然后是另一个功能,该功能显示同一块木板,但隐藏其中有船的斑点(以免将其散发给用户)。代码是:

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")