def random_row(board):
return randrange(0, len(board)-1)
def random_col(board):
return randrange(0, len(board[0])-1)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
这是来自codeacademy的战舰游戏的代码。如何为ship_row和ship_col获取随机索引范围而不仅仅是1个数字?我希望我的船只有一个以上的索引,因为猜测一个数字很难,战舰有多个瓦片吗?谢谢,我希望我的问题很清楚。
答案 0 :(得分:1)
算法会是这样的......
如果它是5x5板,你需要连续获得4个点,你可以有两种可能性。您可以在棋盘上选择一个位置,然后倒数4以获得战舰的空间或选择现场然后倒计时。我会做这个问题的方法是随机选择,看看你是否想要上下。然后你可以做两个随机选择来得到x和y。你只需要根据电路板的大小确保一切都在范围内。
答案 1 :(得分:0)
这似乎是一个有趣的事情,试图写,虽然我通常只是试图推动你朝着正确的方向,今天我决定给你一些东西,将产生一个放置船的板。
这不是最佳选择,但适用于此应用程序。
处理命中和沉船是一项练习:
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 _ _
_ _ _ _ _ _ _ _ _ _