【发布时间】:2016-07-02 15:31:56
【问题描述】:
假设我的窗口尺寸是 400 宽 x 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
【问题讨论】:
-
recrangle 的左上角 (0, 0) 在哪里?
-
@ayhan 是的,这是正确的。
-
感谢您的链接,尽管解决方案似乎很复杂!我找到了一个解决方案,并将用它更新我的帖子。也许有人可以看看它是否可以更优雅地完成。
-
原帖已更新!