-1

I am following a paddles game tutorial and I am trying to get the ball to hit the paddles and change its trajectory.

I thought that it would be better if I used range() instead of the code shown in the tutorial but mine ends up not executed (the ball just goes through the paddles).

The code in the tutorial works perfectly. The code used in the tutorial:

#Hit Paddles
if ball.xcor() > 340 and ball.xcor() < 350 and\
   ball.ycor() > paddle_b.ycor() - 40 and ball.ycor() < paddle_b.ycor() + 40:
    ball.setx(340)
    ball.dx *= -1

My code:

#Hit Paddles
if ball.xcor() in range(340, 350) and\
   ball.ycor() in range((paddle_b.ycor() - 40), (paddle_b.ycor() + 40)):
    ball.setx(340)
    ball.dx *= -1

The game was created using the turtle module, window wd = 800, window height = 600, paddles are 20 * 100, and I placed them at x = -350/350 and ball diameter is 20.

Red
  • 26,798
  • 7
  • 36
  • 58
mathnoob
  • 7
  • 1
  • 1
    FWIW, it's cleaner to do a chained [comparison](https://docs.python.org/3/reference/expressions.html#comparisons) for x: `340 < ball.xcor() < 350`, and [check the difference](https://stackoverflow.com/q/13602170/4518341) for y: `abs(ball.ycor() - paddle_b.ycor()) < 40` – wjandrea Jul 26 '20 at 21:06
  • It is worse to use range(), because itonly works for integers and even then you have to compare 10 times instead of just 2 times – jjj Jul 30 '20 at 16:59

1 Answers1

4

The range() generates a serie of integers, not floats.

So range(340, 350) will give us [340, 341, 342, 343, 344, 345, 346, 347, 348, 349].

The turtle's coordinates will almost never be an exact integer, unless you program it to be that way.

If your turtle's xcor() coordinate is at, for example, 345.456, the program will treat it as not in range(340, 350) (because it is not in the range).

So the float coordinates will likely not be in the range() you used.

Red
  • 26,798
  • 7
  • 36
  • 58