用 python 制作弹跳乌龟

make bouncing turtle with python

我是 python 的初学者,我写了这段代码来用 python 乌龟制作弹跳球 它可以工作但是有一些错误,比如球消失了

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

你需要 window_width()/2window_height()/2 才能留在 window。

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

你应该把 turtle.penup() 在 while 循环之前使您的代码更好更快一点。这几乎是一个错误!

虽然你解决问题的方法有效(我的返工):

import turtle

turtle.shape("circle")
turtle.penup()

x, y = 0, 0
xdir, ydir = 3, 3
xlimit, ylimit = turtle.window_width() / 2, turtle.window_height() / 2

while True:
    x = x + xdir
    y = y + ydir

    if not -xlimit < x < xlimit:
        xdir = -xdir
    if not -ylimit < y < ylimit:
        ydir = -ydir

    turtle.goto(x, y)

turtle.mainloop()

在长运行中,这是错误的做法。在这种情况下,由于无限循环 while True,永远不会调用 mainloop() 方法,因此没有其他 turtle 事件处理程序处于活动状态。例如,如果我们想使用 exitonclick() 而不是 mainloop(),这是行不通的。而是考虑:

import turtle

turtle.shape("circle")
turtle.penup()

x, y = 0, 0
xdir, ydir = 3, 3
xlimit, ylimit = turtle.window_width() / 2, turtle.window_height() / 2

def move():
    global x, y, xdir, ydir

    x = x + xdir
    y = y + ydir

    if not -xlimit < x < xlimit:
        xdir = -xdir
    if not -ylimit < y < ylimit:
        ydir = -ydir

    turtle.goto(x, y)

    turtle.ontimer(move, 5)

turtle.ontimer(move, 5)

turtle.exitonclick()

在这里,我们将控制权交还给了主循环,并且动作在事件计时器上。可以执行其他海龟事件,因此 exitonclick() 有效。在你将自己和你的乌龟逼到一个角落之前,先考虑一下前进的事情。

你的墙可以反弹,如果你想从上墙反弹,屏幕宽度为800,长度为600

from turtle import turtle
turtle=Turtle()
    def move(self)://This will move your ball in diagonal direction
        x_dir=self.xcor()+self.x
        y_dir=self.ycor()+self.y
        self.goto(x_dir,y_dir)
    def bounce(self)://This will bounce back
        self.y *=-1
turtle.bounce()

这段代码是运行,因为我是用继承来做的。您需要创建一个 class 然后继承所有属性,然后在那里创建两个方法,然后在主 class.

中调用这些函数