【问题标题】:How to create an (x,y) list in which only one of the variables change but the other one stays the same?如何创建一个 (x,y) 列表,其中只有一个变量发生变化,而另一个变量保持不变?
【发布时间】:2011-12-15 06:28:56
【问题描述】:
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。

【问题讨论】:

  • 你只改变y的值而不对x做任何事情,这不是你需要的吗?就像if pos == 'v': y = newy,没有提到x。
  • 不,但我仍然需要 x 的随机值,但这会随着值的变化保持不变。就像你要在图表上画一条垂直线一样,x 值将保持不变当 y 值改变时
  • @yosukesabai 的意思是xy 可以相互独立计算。选择你的随机x,然后(假设你的船长度为4),在1到6之间随机选择一个起始y。然后让你的船从y开始,所以它占据位置y,@987654330 @,y+2,y+3。按照设计,这不会超过 9,因为您在 1 和 6 之间选择了起始 y

标签: python list tuples


【解决方案1】:

您必须从检查可用位置的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    相关资源
    最近更新 更多