Amin Hijaz Amin Hijaz - 2 months ago 31
Python Question

make bouncing turtle with python

i am a beginner with python
I wrote this code to make bouncing ball with turtle it works but have some erors like ball dissapering

import turtle
turtle.shape("circle")
xdir = 1
x = 1
y = 1
ydir = 1
while True:
x = x + 3 * xdir
y = y + 3 * ydir
turtle.goto(x , y)
if x >= turtle.window_width():
xdir = -1
if x <= -turtle.window_width():
xdir = 1
if y >= turtle.window_height():
ydir = -1
if y <= -turtle.window_height():
ydir = 1
turtle.penup()
turtle.mainloop()

Answer

You need window_width()/2 and window_height()/2 to keep inside window.

ie.

if x >= turtle.window_width()/2:
    xdir = -1
if x <= -turtle.window_width()/2:
    xdir = 1
if y >= turtle.window_height()/2:
    ydir = -1
if y <= -turtle.window_height()/2:
    ydir = 1
Comments