Bouncing ball in a circle (Python Turtle)

1.5k views Asked by At

I am currently working on a circular billiards program using Turtle. My problem is that I can't figure out what angle or position I need to give Python once the ball has reached the sides of the circle in order to make it bounce. Here is the part of my program that needs to be fixed:

while nbrebonds>=0:
        forward(1)
        if (distance(0,y)>rayon): #rayon means radius 
            print(distance(0,y))
            left(2*angleinitial)  #I put this angle as a test but it doesn't work
            forward(1)
            nbrebonds+=(-1)
1

There are 1 answers

1
cdlane On

From what I was able to understand about this issue, you should be able to calculate what you need using turtle's heading() and towards() methods:

from random import *
from turtle import *

radius = 100
nbrebonds = 10

# draw circle around (0, 0)
penup()
sety(-radius)
down()
circle(radius)

# move turtle to somewhat random position & heading inside circle
penup()
home()
setx(randrange(radius//4, radius//2))
sety(randrange(radius//4, radius//2))
setheading(randrange(0, 360))
pendown()

while nbrebonds >= 0:
    forward(1)

    if distance(0, 0) > radius:

        incoming = heading()
        normal = towards(0, 0)
        outgoing = 2 * normal - 180 - incoming

        setheading(outgoing)

        forward(1)

        nbrebonds -= 1

mainloop()

enter image description here