簡體   English   中英

如何使多個克隆在 python 龜中同時運行

[英]How to make multiple clones run at the same time in python turtle

我正在嘗試編寫一個可以按空格鍵的代碼,並且 object 將不斷向前移動。 我希望能夠一次移動多個這樣的對象,而不必單獨編寫數百個。

這是我當前的代碼:

子彈:

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: loop 和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()

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM