2016-12-03 155 views
0

我正在試圖製作戰列艦,並且我正在將這些艦船列入「單板」列表中,並且船隻的長度將由切片決定。我試圖隨機移動船隻,但我很快意識到random.choice一次只能移動一個元素,但船隻有2-5個元素。我正在嘗試查看是否可以將列表中的切片隨機分配到切片上分配的單位。 random.shuffle似乎不起作用。如何隨機化切片?

import random 

board = "o" 

board = [board] * 49 

ship_two_space = board[0:2] 

ship_three_space = board[0:3] 

ship_three_space_second = board[0:3] 

ship_four_space = board[0:4] 

ship_five_space = board[0:5] 
+0

您的問題完全不清楚,您提供的代碼根本沒有幫助,因爲它沒有顯示您嘗試或嘗試執行的操作。 – Julien

+0

切片始終從0開始?什麼是電路板尺寸? – wwii

回答

0

船舶位置不能重疊 - 使用一組給

occupied = set() 

文件所佔用的空間定義規格

N = 49 
board = ['o'] * N 
ship_specs = [('two_space', 2), ('three_space1', 3), ('three_space2', 3), 
       ('four_space', 4), ('five_space', 5)] 

開始製作船 - 利用collections.namedtuple到定義

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))] 
>>>