2017-07-25 22 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