這似乎是一件很有趣的事情,但我通常只是試着將你推向正確的方向,今天我決定給你一些東西,讓它們能夠放置船隻。
這不是最佳的,但對此應用程序很好。
處理安打,沉船被留作練習:
import collections
import random
DIRECTIONS = ['up', 'down', 'left', 'right']
Ship = collections.namedtuple("Ship", ("name", "size", "count"))
Board = collections.namedtuple("Board", ("w", "h", "map"))
ships = [Ship("battle", 4, 1), Ship('submarine', 3, 1), Ship('destroyer', 3, 1), Ship("patrol", 2, 1), Ship("carrier", 5, 1)]
def create_board(w, h):
return Board(w, h, [['_'] * w for _ in range(h)])
def place_ships(board, ships):
for ship in ships:
for _ in range (ship.count):
place_ship(board, ship)
def place_ship(board, ship):
while True:
_x = random.randint(0, board.w - 1)
_y = random.randint(0, board.h - 1)
random.shuffle(DIRECTIONS)
for direction in DIRECTIONS:
if maybe_place(board, _x, _y, direction, ship):
return
def maybe_place(board, x, y, direction, ship):
if direction == "right":
right = min(board.w - 1, x + ship.size)
left = right - ship.size
slots = [(x, i) for i in range(left, right)]
elif direction == "left":
left = max(0, x - ship.size)
right = left + ship.size
slots = [(x, i) for i in range(left, right)]
elif direction == "down":
bottom = min(board.h - 1, y + ship.size)
top = bottom - ship.size
slots = [(i, y) for i in range(top, bottom)]
elif direction == "up":
top = max(0, y - ship.size)
bottom = top + ship.size
slots = [(i, y) for i in range(top, bottom)]
if all([board.map[x][y] == '_' for x, y in slots]):
for x, y in slots:
board.map[x][y] = ship.name[0]
return True
return False
def print_board(board):
for row in board.map:
for x in row:
print x,
print
if __name__ == "__main__":
board = create_board(10, 10)
place_ships(board, ships)
print_board(board)
輸出的例子
_ _ c _ _ _ _ _ _ _
_ _ c _ _ _ _ _ _ _
_ _ c _ _ _ _ _ _ _
_ _ c _ _ _ _ _ _ _
_ _ c _ p p _ _ _ _
_ _ _ _ _ b _ _ _ _
_ _ _ _ _ b _ _ _ _
_ _ _ _ _ b s s s _
_ _ _ _ _ b _ _ _ _
_ _ _ _ _ _ d d d _
_ _ _ c b _ _ _ _ _
_ _ _ c b _ _ _ _ _
_ _ _ c b _ _ _ _ _
_ _ _ c b _ _ _ _ _
_ _ _ c _ _ _ _ _ _
_ _ _ _ _ _ _ _ d _
_ _ _ _ _ _ p p d _
_ _ _ _ _ _ _ _ d _
_ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ s s s _
_ _ _ _ _ c _ _ _ _
_ _ _ _ _ c _ _ _ _
_ _ d d d c _ _ _ _
_ _ _ _ _ c _ _ _ _
_ _ _ _ _ c _ _ _ _
_ _ _ _ _ b b b b _
_ _ _ _ _ _ p s _ _
_ _ _ _ _ _ p s _ _
_ _ _ _ _ _ _ s _ _
_ _ _ _ _ _ _ _ _ _
戰列艦上圖 –