Bouncing ball in a circle (Python Turtle)

落爺英雄遲暮 提交于 2019-12-11 11:55:14

问题


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:


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()



来源:https://stackoverflow.com/questions/50591845/bouncing-ball-in-a-circle-python-turtle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!