Explanation
As others have pointed out, you are not dealing with the case that WALL <= pos <= WIDTH - WALL
.
Recommended change
Presumably the boid continues with current velocity if it does not hit a wall. Others have code that sets velocity to 0 if the boid is not hitting a wall. This solution is distinctive in using the existing velocity. I think that is important to your situation.
Code
def new_speedD(boid1):
def new_speed(pos, velocity):
return WALL_FORCE if pos < WALL \
else (-WALL_FORCE if pos > WIDTH - WALL \
else velocity)
xpos, ypos, xvelocity, yvelocity = boid1
new_speedDx = new_speed(posx, xvelocity)
new_speedDy = new_speed(posy, yvelocity)
return new_speedDx, new_speedDy
Some think this code is hard to understand. Here is a brief explanation:
- return WALL_FORCE if pos < WALL
- otherwise, return -WALL_FORCE if pos > WIDTH - WALL
- otherwise, return velocity
Here is a general question on the ternary operator. Remember, thought, that "It's frowned upon by some pythonistas."
If you don't use this code...
Return to your original and fix the typo in yvelocity
case: bposx > WIDTH - WALL
. The yvelocity
does not depend on the xpos
.