2017-03-05 46 views
0

我正在使用Python中的戰艦遊戲項目。我被困在顯示放置在網格上的船隻。這裏是我的功能,它根據用戶輸入的座標顯示更新的板子 - 以字母,數字形式顯示A10。用戶網格是一個10x10框。空板上印有「O」字樣,並且垂直船舶應該用|打印字符,而水平印有 - 。在設置完所有座標之後,我可以更新電路板。根據船舶的尺寸,所以用四個大小例如戰艦基於用戶輸入在Python中顯示不同值

def print_updated_board(coords, direction): 
    board = [] 
    for row in range(10): 
     board_row = [] 
     updated = [] 
     for c in range(ord('a'), ord('a') + BOARD_SIZE): 
      t = chr(c) + str(row) 
      board_row.append(t) 
     if direction == 'v': 
      for coord in coords: 
       for w in board_row: 
        if coord == w: 
         updated.append(VERTICAL_SHIP) 
        else: 
         updated.append(EMPTY) 
     board.append(updated) 
    print_board_heading() 
    row_num = 1 
    for row in board: 
     print(str(row_num).rjust(2) + " " + (" ".join(row))) 
     row_num += 1 

的COORDS被創建,放置在垂直A1,將具有座標(A1,A2,A3,A4)。我只是試圖在這個例子中打印一個|在這些座標上留下空的座標爲O.

我的代碼現在關閉 - 網格似乎錯誤地打印了50行(而不是10)。

任何指導如何採取此讚賞。謝謝

編輯****************實現我是雙循環,並將代碼更改爲此。尚未完美工作(它由一個位置關閉),但在其上工作。

def print_updated_board(coords, direction): 
    board = [] 
    for row in range(10): 
     board_row = [] 
     updated = [] 
     for c in range(ord('a'), ord('a') + BOARD_SIZE): 
      t = chr(c) + str(row) 
      board_row.append(t) 
     if direction == 'v': 
      for b in board_row: 
       if b in coords: 
        updated.append(VERTICAL_SHIP) 
       else: 
        updated.append(EMPTY) 
      board.append(updated) 
    print_board_heading() 
    row_num = 1 
    for row in board: 
     print(str(row_num).rjust(2) + " " + (" ".join(row))) 
     row_num += 1 
+0

OK我有點確定我problem--我是雙looping- - 在每個船的座標上面和船上。改變了上面的代碼以反映 - 我的一個問題是船舶正在打印一個變量。 –

回答

0

的問題是這些嵌套的循環:

for coord in coords: 
    for w in board_row: 
     updated.append(...) 

這些導致板變寬爲列表中的每個座標。


最好的解決辦法是扔掉所有這些代碼窗外,因爲有一個更容易的方式來做到這一點:

def print_updated_board(coords, direction): 
    # create an empty board 
    board = [['O']*BOARD_SIZE for _ in range(BOARD_SIZE)] 
    # at each coordinate, draw a ship 
    for coord in coords: 
     # convert string like "a1" to x,y coordinates 
     y= ord(coord[0])-ord('a') 
     x= int(coord[1:])-1 
     # update the board at this position 
     board[x][y]= '|' if direction=='v' else '--' 
+0

好心情吹。非常感謝! –

+0

快速快速問題 - 對我來說混淆的一部分是你轉換字符串的地方....只是不理解減法部分。就像我想的那樣,它似乎可能與Python的索引屬性有關 - 從0開始等等。是嗎? –

+0

@JohnRogerson確切地說,減法是在那裏讓我們的座標從0開始。 –