将球弹起一圈(Python Turtle) [英] Bouncing ball in a circle (Python Turtle)

查看:154
本文介绍了将球弹起一圈(Python Turtle)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用Turtle制作圆形台球程序.我的问题是,一旦球到达圆的侧面以使其反弹,我就无法弄清楚需要给Python哪个角度或位置.这是我程序中需要修复的部分:

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)

推荐答案

根据我对这个问题的了解,您应该能够使用turtle的heading()towards()方法计算出所需的内容:

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

这篇关于将球弹起一圈(Python Turtle)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆