9.32: Finding a Place to Add New Squirrels and Grass

def getRandomOffCameraPos(camerax, cameray, objWidth, objHeight):
# create a Rect of the camera view
cameraRect = pygame.Rect(camerax, cameray, WINWIDTH, WINHEIGHT)
while True:
x = random.randint(camerax - WINWIDTH, camerax + (2 * WINWIDTH))
y = random.randint(cameray - WINHEIGHT, cameray + (2 * WINHEIGHT))
# create a Rect object with the random coordinates and use colliderect()
# to make sure the right edge isn't in the camera view.
objRect = pygame.Rect(x, y, objWidth, objHeight)
if not objRect.colliderect(cameraRect):
return x, y

When a new squirrel or grass object is created in the game world, we want it to be within the active area (so that it is near the player’s squirrel) but not within the view of the camera (so that it doesn’t just suddenly pop into existence on the screen). To do this, we create a Rect object that represents the area of the camera (using camerax, cameray, WINWIDTH, and WINHEIGHT constants).

Next, we randomly generate numbers for the XY coordinates that would be within the active area. The active area’s left and top edge are WINWIDTH and WINHEIGHT pixels to the left and up of camerax and cameray. So the active area’s left and top edge are at camerax - WINWIDTH and cameray - WINHEIGHT. The active area’s width and height are also three times the size of the WINWIDTH and WINHEIGHT, as you can see in this image (where WINWIDTH is set to 640 pixels and WINHEIGHT set to 480 pixels):

This means the right and bottom edges will be at camerax + (2 * WINWIDTH) and cameray + (2 * WINHEIGHT). Line 10 [352] will check if the random XY coordinates would collide with the camera view’s Rect object. If not, then those coordinates are returned. If so, then the while loop on line 4 [346] will keep generating new coordinates until it finds acceptable ones.