如何在python中同时运行多个克隆
我试着做一个代码,你可以按下空格键,一个物体会不断向前移动。我希望能够让多个这样的对象同时移动,而不必分别对数百个对象进行编码 这是我当前的代码: 要点:如何在python中同时运行多个克隆,python,turtle-graphics,Python,Turtle Graphics,我试着做一个代码,你可以按下空格键,一个物体会不断向前移动。我希望能够让多个这样的对象同时移动,而不必分别对数百个对象进行编码 这是我当前的代码: 要点: bullet = turtle.Turtle() bullet.speed(0) bullet.shape("circle") bullet.color("red") bullet.shapesize(stretch_wid=0.5, stretch_len=0.5) bullet.penup() bullet.goto(-200, -200
bullet = turtle.Turtle()
bullet.speed(0)
bullet.shape("circle")
bullet.color("red")
bullet.shapesize(stretch_wid=0.5, stretch_len=0.5)
bullet.penup()
bullet.goto(-200, -200)
bullet.hideturtle()
运动:
def shoot_bullet():
stop = False
bullet2 = bullet.clone()
bullet2.showturtle()
while stop == False:
y = bullet2.ycor()
bullet2.sety(y + 20)
wn.update()
time.sleep(0.5)
...
onkeypress(shoot_bullet, "space")
直到我再次按空格键,子弹停止,因为“bullet2”已被重新定义为我按空格键时创建的新子弹。有没有一种方法可以创建多个可以相互重叠运行的克隆?你的
while stop==False:
循环和时间。睡眠(0.5)
在海龟这样的事件驱动环境中没有位置。相反,当我们发射每个子弹时,下面的代码会附加一个计时器事件,该事件会一直移动到子弹消失为止。在这一点上子弹被回收
这个简化的示例只是从屏幕中心向随机方向发射子弹。您可以继续敲击空格键,以生成同时的子弹,所有子弹都朝着自己的方向移动,直到它们离得足够远:
from turtle import Screen, Turtle
from random import randrange
def move_bullet(bullet):
bullet.forward(15)
if bullet.distance((0, 0)) > 400:
bullet.hideturtle()
bullets.append(bullet)
else:
screen.ontimer(lambda b=bullet: move_bullet(b), 50)
screen.update()
def shoot_bullet():
screen.onkey(None, 'space') # disable handler inside hander
bullet = bullets.pop() if bullets else bullet_prototype.clone()
bullet.home()
bullet.setheading(randrange(0, 360))
bullet.showturtle()
move_bullet(bullet)
screen.onkey(shoot_bullet, 'space') # reenable handler on exit
bullet_prototype = Turtle('circle')
bullet_prototype.hideturtle()
bullet_prototype.dot(10) # just for this example, not for actual code
bullet_prototype.shapesize(0.5)
bullet_prototype.color('red')
bullet_prototype.penup()
bullets = []
screen = Screen()
screen.tracer(False)
screen.onkey(shoot_bullet, 'space')
screen.listen()
screen.mainloop()