N = 49
board = ['o'] * N
ship_specs = [('two_space', 2), ('three_space1', 3), ('three_space2', 3),
('four_space', 4), ('five_space', 5)]
スタートを定義
occupied = set()
占有スペースを文書化するセットを使用 Ship = collections.namedtuple('Ship', ('name','indices', 'slice'))
def get_position(length):
'''Determine the unique position indices of a ship'''
start = random.randint(0, N-length)
indices = range(start, start + length)
if not occupied.intersection(indices):
occupied.update(indices)
return indices, slice(start, start + length)
else:
return get_position(length)
ships = []
for name, length in ship_specs:
indices, _slice = get_position(length)
ships.append(Ship(name, indices, _slice))
print(board)
for ship in ships:
board[ship.slice] = str(len(ship.indices))*len(ship.indices)
print(board)
print([(ship.name, ship.slice) for ship in ships])
>>>
['o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o']
['o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', '2', '2', '4', '4', '4', '4', '3', '3', '3', 'o', '5', '5', '5', '5', '5', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', '3', '3', '3', 'o', 'o', 'o']
[('two_space', slice(10, 12, None)), ('three_space1', slice(43, 46, None)), ('three_space2', slice(16, 19, None)), ('four_space', slice(12, 16, None)), ('five_space', slice(20, 25, None))]
>>>
あなたの質問は完全にはっきりしておらず、提供したコードは、あなたが試したことややろうとしていることを示していないので、全く役に立たない。 – Julien
スライスは常に0から始まりますか?ボードの寸法は? – wwii