如何在矩形外生成随机点?

时间:2016-07-02 15:31:57

标签: python random position

我们说我的窗户的尺寸是400宽×600高。

在单方面生成随机点相对容易,让我们说它的顶部:

random.randint(0, width)

但是什么是让这个方法适用于所有4个方面的最明智的方法,以便在矩形外生成随机点?

如果我这样做

pos_x = [random.randint(0, width)]
pos_y = [random.randint(0, height)]

它们只会出现在角落,这是有道理的。我能想到的唯一方法是在矩形内随机创建一个点,比较最接近边界的轴,然后将其夹住。事情是我不知道如何优雅地做到这一点,而不需要对每一方进行4次检查(感觉多余)。我觉得有一个更简单的解决方案吗?

这是一个几乎可行的解决方案,但它已经啰嗦了。刚刚意识到这会在角落里获得更少的分数。

# Create a random point inside the rectangle
pos_x = random.randint(0, width)
pos_y = random.randint(0, height)

# Get a distance for each side
left_border = pos_x
right_border = width-pos_x
top_border = pos_y
bottom_border = height-pos_y

borders = [left_border, right_border, top_border, bottom_border]

index_1 = 0
index_2 = 2
closest_side = 0

# Get closest from left/right borders
if right_border < left_border:
    index_1 = 1

# Get closest from top/bottom borders
if bottom_border < top_border:
    index_2 = 3

# Get closest border
if borders[index_1] < borders[index_2]:
    closest_side = index_1
else:
    closest_side = index_2

if closest_side == 0:
    obj.pos.x = 0 # Clamp to left wall
elif closest_side == 1:
    obj.pos.x = width # Clamp to right wall
elif closest_side == 2:
    obj.pos.y = 0 # Clamp to top wall
else:
    obj.pos.y = height # Clamp to bottom wall

1 个答案:

答案 0 :(得分:1)

抱歉;第一次完全误解了这个问题。

如果您只想在矩形的边缘上随机选取一个点,请尝试以下方法:

p = random.randint(0, width + width + height + height)
if p < (width + height):
  if p < width:
    obj.pos.x = p
    obj.pos.y = 0
  else:
    obj.pos.x = width
    obj.pos.y = p - width
else:
  p = p - (width + height)
  if p < width:
    obj.pos.x = width - p
    obj.pos.y = height
  else:
    obj.pos.x = 0
    obj.pos.y = height - (p - width)

简单地说,它在与矩形周长相同的直线上选取一个随机点,然后在矩形周围分段包围该线以给出x和y坐标。

为了确保分布在角落处保持均匀,四个片段中的每一个都被视为包含 - 独占间隔(可以是0,不能是宽度或高度)并且它们被放置成使得它们中的每一个开始于一个不同的角落。

相关问题