2017-10-28 93 views
0

我一直在努力從HackerRank的問題的實施。也就是這個:https://www.hackerrank.com/challenges/battleship1p/problem循環創建了太多的孩子

我選擇的語言是Python3,我想這將是一個很好的選擇。現在,這裏是一個基本的構造上我的計劃是,在建工程:

class Cell(): 
    # - status open 
    # h hit 
    # m miss 
    neighboring = [] 
    status = None 
    cell_x = None 
    cell_y = None 

    def __init__(self, cell_x, cell_y): 
     self.cell_x = cell_x 
     self.cell_y = cell_y 
     status = '-' 

    def check_status(self): 
     return self.status 

    def check_ut(self): 
     if (self.status == "-"): 
      return True 

    def check_hit(self): 
     if (self.status == "h"): 
      return True 

    def check_miss(self): 
     if (self.status == "m"): 
      return True 

    def add_neighboring(self, c): 
     self.neighboring.append(c) 

    def check_neighboring(self): 
     for x in self.neighboring: 
      if (x.check_ut()): 
       return x 

    def check_neighboring_is_hit(self): 
     if self.check_hit(): 
      for x in self.neighboring: 
       if (x.check_ut()): 
        return x 


class Row(): 
    Cells = [] 
    y = None 

    def __init__(self, y): 
     for i in range(10): 
      self.Cells.append(Cell(i, y)) 


class Board(): 
    Rows = None 

    def populate_neighbors(self): 
     for l in self.Rows: 
      for c in l.Cells: 
       if (c.cell_x > 0): 
        prev_cell = l.Cells[c.cell_x - 1] 
        prev_cell.add_neighboring(c) 
        c.add_neighboring(prev_cell) 
       if (c.cell_y > 0): 
        above_cell = self.Rows[c.cell_y - 1].Cells[c.cell_x] 
        above_cell.add_neighboring(c) 
        c.add_neighboring(above_cell) 

     print("test") 

    def NewRow(self): 
     self.Rows.append(Row(len(self.Rows))) 

    def __init__(self, rows): 
     self.Rows = [] 
     for i in range(rows): 
      self.NewRow() 


list_ships = [1, 1, 2, 2, 3, 4, 5] 

z = Board(10) 
z.populate_neighbors() 

它試圖重建一個球員的一局,這是我10行基板(10)initalise且還應創建每行10個單元格。但是由於在後臺發生的事情,它似乎每行創建了100個字段,至少我的調試器是這樣說的。如果你能給我一個重複或娛樂或類似的事情後果,我將不勝感激。

在populate_neighbors中,我的目標是找到特定單元格的所有相鄰單元格,方法是遍歷第一個所有行,然後逐個單元格,以將前一個選中的元素添加到當前選定的元素中,遊戲場的高度。現在我希望你明白這是故意的。

回答

0

那麼,在您的代碼Row.Cells是一個類屬性,並在的所有實例之間共享。循環總是追加到同一個列表中,這就是爲什麼我們有100個單元格。修復你將需要:

class Row(): 
    Cells = [] # this is not a field declaration like Java 
    y = None 

    def __init__(self, y): 
     self.Cells = [] # need this 
     for i in range(10): 
      self.Cells.append(Cell(i, y)) 

我建議你重新閱讀Python的基礎知識。

+0

這是最好的提示,你可以給我! :) – marena