gpt4 book ai didi

python - 用python制作弹跳 turtle

转载 作者:行者123 更新时间:2023-11-28 22:33:32 25 4
gpt4 key购买 nike

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

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

最佳答案

尽管您解决问题的方法有效(我的返工):

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

在这里,我们已将控制权交还给主循环,并且 Action 在事件计时器上进行。可以执行其他 turtle 事件,因此 exitonclick() 可以正常工作。在您将自己和您的 turtle 逼到一个角落之前,请考虑继续前进。

关于python - 用python制作弹跳 turtle ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39808240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com