You could avoid sameness relation comparison ==
for boundary. I use <=
or >=
for compare boundary.
I do not know about your code and context, but I suppose circleX
, circleY
has been changed on other method.
If it change variables as like circleX += 20
, it can be passed all if-condition. or if it was called too fast by some events on thread environment, we can not trust the value of circleX
.
I recommend to compare as following:
if circleX - 16 <= 0: # Left border
circleX = 16
elif circleY - 16 <= 0: # Top
circleY = 16
elif circleY + 16 >= 500: # Bottom
circleY = 484
elif circleX + 16 >= 500: # Right
circleX = 484
elif circleY - 16 <= 0 and circleX - 16 <= 0: # Top Left corner
circleY = 16
circleX = 16
elif circleY + 16 >= 500 and circleX + 16 >= 500: # Bottom right
circleX = 484
circleY = 484
elif circleY + 16 >= 500 and circleX - 16 <= 0: # Bottom left
circleY = 484
circleX = 16
elif circleY - 16 <= 0 and circleX + 16 >= 500: # Top right
circleX = 484
circleY = 16
and it can be shorten by using less if condition:
if circleX - 16 <= 0: # Left border
circleX = 16
if circleY - 16 <= 0: # Top Left corner
circleY = 16
elif circleY - 16 <= 0: # Top
circleY = 16
if circleX + 16 >= 500: # Top right
circleX = 484
elif circleY + 16 >= 500: # Bottom
circleY = 484
if circleX - 16 <= 0: # Bottom left
circleX = 16
elif circleX + 16 >= 500: # Right
circleX = 484
if circleY + 16 >= 500: # Bottom right
circleY = 484
BUT, more short code in my personal favorite is:
circleX = min(max(16, circleX), 484)
circleY = min(max(16, circleY), 484)