简体   繁体   中英

Why doesn't the range() function work when i use turtle module?

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM