如何在python中同时运行多个克隆

2024-09-30 20:24:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着做一个代码,你可以按下空格键,一个物体会不断向前移动。我希望能够有多个这样的物体同时移动,而不必分别对数百个物体进行编码。你知道吗

这是我当前的代码:

项目符号:

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”已被重新定义为我按空格键时创建的新项目符号。有没有办法创建多个可以相互重叠的克隆?你知道吗


Tags: 项目代码false编码符号物体stopspeed
1条回答
网友
1楼 · 发布于 2024-09-30 20:24:59

您的while stop == False:循环和time.sleep(0.5)在像turtle这样的事件驱动环境中没有位置。相反,当我们发射每个项目符号时,下面的代码会附加一个计时器事件,它会一直移动直到它消失。这时子弹就被回收了。你知道吗

这个简化的例子只是从屏幕中心向随机方向发射子弹。你可以一直按空格键来同时生成子弹,所有子弹都朝着自己的方向移动,直到它们离得足够远:

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

enter image description here

相关问题 更多 >