dimanche 22 novembre 2015

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




Aucun commentaire:

Enregistrer un commentaire