如何创建一个(x,y)列表,其中只有一个变量发生变化而另一个变量保持不变?

时间:2011-12-15 06:28:57

标签: python list tuples

SHIPS = (('AirCraftCarrier', 5), ('Battleship', 4),
         ('Submarine', 3), ('Destroyer', 3), ('PatrolBoat', 2))
position = ('v', 'h')

def setShip(self, board, graphics):
        maxval = board.getSize() - 1
        coords = []
        sizes = [(v) for k, v in SHIPS]
        for i in sizes:
            legal = False
            while not legal:
                pos = choice(position)
                if pos == 'v':
                    x = randint(0, maxval-1)
                    y = some kind of code to change y while keeping x same
                if pos == 'h':
                    x = some kind of code to change x while keeping y same 
                    y = randint(0, maxval-1)

                if not board.isOccupied(x, y):
                    legal = True
                    coords.append((pos, x, y))
            #return grid.displayShip(x, y)
            return coords

现在,如果选择v=vertical选项, y 值必须更改,而 x 值保持不变。这将导致我的船垂直放置。我不知道如何使这项工作。我需要随机选择第一个值,然后选择之后的值才能获得船的长度,但是最后一个值不能大于9,因为我的网格只能达到9。

1 个答案:

答案 0 :(得分:0)

您必须从检查可用位置的while循环中取出您不想更改的变量。您可以通过多种方式完成此操作。一种选择是:

def setShip(self, board, graphics):
        maxval = board.getSize() - 1
        coords = []
        sizes = [v for k, v in SHIPS]
        for i in sizes:
            legal = False
            x = randint(0, maxval-1)
            y = randint(0, maxval-1)
            pos = choice(position)
            while not legal:
                if pos == 'v':
                    y = y+1 if y < 9 else 0
                if pos == 'h':
                    x = x+1 if x < 9 else 0
                if not board.isOccupied(x, y):
                    legal = True
                    coords.append((pos, x, y))

            return coords

请注意,我也限制了头寸可以采取的价值。如果船在一侧消失,它将从另一侧出现。该代码的问题在于船始终朝向一个方向(从0 - > 9)。您可以更改此选项以选择所需的方向。例如:

sense = choice([1, -1])

然后在内循环中,例如:

y = y + sense if y < 9 else 0