将多个值插入到列表Python / Battleship中

时间:2017-07-25 20:32:20

标签: python-3.x

这是我第一次发布问题,如果发布任何错误,请耐心等待。

我正在用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.

1 个答案:

答案 0 :(得分: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)