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