Generate random number outside of range in python

后端 未结 5 1244
盖世英雄少女心
盖世英雄少女心 2021-02-18 22:52

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

5条回答
  •  耶瑟儿~
    2021-02-18 23:17

    If it's the generation of random you want to avoid, rather than the loop, you can do the following:

    1. Generate a pair of random floating point coordinates in [0,1]
    2. Scale the coordinates to give a point in the outer rectangle.
    3. If your point is outside the inner rectangle, return it
    4. Rescale to map the inner rectangle to the outer rectangle
    5. Goto step 3

    This will work best if the inner rectangle is small as compared to the outer rectangle. And it should probably be limited to only going through the loop some maximum number of times before generating new random and trying again.

提交回复
热议问题