Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random number outside of range in python

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 1000x800 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
like image 684
Spooky Avatar asked Nov 22 '15 17:11

Spooky


1 Answers

  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.

like image 162
Nick Alger Avatar answered Sep 20 '22 07:09

Nick Alger