Python – Generate Random Number Outside of Range

pythonrandomrange

I'm currently working on a pygame game and I need to place objects randomly on the screen, except they cannot be within a designated rectangle. Is there an easy way to do this rather than continuously generating a random pair of coordinates until it's outside of the rectangle?

Here's a rough example of what the screen and the rectangle look like.

 ______________
|      __      |
|     |__|     |
|              |
|              |
|______________|

Where the screen size is 1000×800 and the rectangle is [x: 500, y: 250, width: 100, height: 75]

A more code oriented way of looking at it would be

x = random_int
0 <= x <= 1000
    and
500 > x or 600 < x

y = random_int
0 <= y <= 800
    and
250 > y or 325 < y

Best Answer

  1. Partition the box into a set of sub-boxes.
  2. Among the valid sub-boxes, choose which one to place your point in with probability proportional to their areas
  3. Pick a random point uniformly at random from within the chosen sub-box.

random sub-box

This will generate samples from the uniform probability distribution on the valid region, based on the chain rule of conditional probability.

Related Question