2017-07-25 20 views
2

這是我第一次發佈一個問題,所以如果我發佈任何錯誤,請耐心等待。在列表中插入多個值Python/Battleship

我在Python中創建戰艦遊戲,並卡在我的代碼的特定部分。我設法增加大小爲1的船隻,但不添加大於1的船隻。我已經使用了10x10格子板和字典來保存船隻和船隻的大小。有沒有一種善良的靈魂可以幫助我理解如何解決這個問題?這是我到目前爲止的代碼:

def comp_place_ship(comp_board): 
    ships = {"A": 4, "B": 3, "C": 2, "S": 2, "D": 1} 
    for i, j in ships.items(): 
     x = random.randint(0,9) 
     y = random.randint(0,9) 
     place = x,y 
     if place != 0: 
      print(place) 
      comp_board[x][y] = i 
      comp_board[x+j][y] = i #THIS IS WHERE I'M STUCK 
      print('The computer has placed ship: ', i) 

comp_place_ship(comp_board) 
print("--------------------------------------------") 
print("--------------------------------------------") 
print_comp_board(comp_board) 

編輯:可能有助於你顯示輸出,所以你知道我的意思:This is the output

我想標記的區域也爲「A」,而不是0 。

+0

是它拋出一個錯誤?它看起來像只要'x + j> 9'就會拋出索引超出範圍。你需要確保這不會發生。它也似乎是所有的船舶將被放置在相同的方向,這可能會或可能不是你想要的。 – dashiell

+0

就像旁註一樣,'place!= 0'永遠不會是'False'(換句話說,'place'永遠不會是'0') – DeepSpace

+0

感謝您的評論。它沒有拋出一個錯誤,但列表/板不是我想要的。它不插入前例。 4「A」連續排列,但A,0,0,A。(如果有任何意義)編輯問題以顯示輸出。我還沒有添加定位代碼。 – Tinadark

回答

0

這是我有:

from pprint import pprint 
import random 

comp_board = []*10 
for i in xrange(10): 
    comp_board.append(['0']*10) 

def comp_place_ship(comp_board): 
    ships = {"A": 4, "B": 3, "C": 2, "S": 2, "D": 1} 
    for i, j in ships.items(): 
     x = random.randint(0,9-j) # fix the index error 
     y = random.randint(0,9) 
     place = x,y 
     print(place) 
     for k in range(j): # you alter a variable number of cells based on the length of the ship 
      comp_board[x][y] = i 
      comp_board[x+k][y] = i 
      print('The computer has placed ship: ', i) 

comp_place_ship(comp_board) 
pprint(comp_board) 
+0

謝謝sooo @dashiell!這正是我需要了解如何完成剩下的工作。通過這種方式印刷什麼樣的模塊?是否需要或足夠打印?這是一個學校項目,我需要證明使用不同的模塊,你看:) – Tinadark

+0

pprint是一個非常好的功能,使打印列表和字典更好。我只是使用它,因爲我沒有你的'print_comp_board'功能 – dashiell

+0

謝謝你清理那個:)忘了添加print_comp_board功能。順便說一句,你有沒有想法如何避免重疊的船隻?我試過了一個if語句,如下所示:if comp_board [x + k] [y] =='0'(空單元格的標準輸出)。但那並不奏效。有時它們重疊,有時不重合。 – Tinadark