How do I make an object disappear after some time?

耗尽温柔 提交于 2019-12-01 11:43:23

Your progam appears to be a collection of misconceptions glued together with bad code management. Your bullet not only has lag, but it locks out all other action while it's in motion! Let's toss the time module idea and instead take advantage of turtle's own timer events to really let the bullets fly:

from turtle import Screen, Turtle

# Arrow Keys as turtle movement
def forward_1():
    player_1.forward(player_speed)

def back_1():
    player_1.back(player_speed)

def left_1():
    player_1.left(player_speed)

def right_1():
    player_1.right(player_speed)

def shoot_1():
    screen.onkey(None, "space")  # disable handler inside handler!
    shoot(player_1)
    screen.onkey(shoot_1, "space")

def forward_2():
    player_2.forward(player_speed)

def left_2():
    player_2.left(player_speed)

def right_2():
    player_2.right(player_speed)

def back_2():
    player_2.back(player_speed)

def shoot_2():
    screen.onkey(None, "z")
    shoot(player_2)
    screen.onkey(shoot_2, "z")

def travel(bullet, milliseconds):
    bullet.forward(bullet_speed)

    if milliseconds:
        screen.ontimer(lambda b=bullet, s=milliseconds - 100: travel(b, s), 100)
    else:
        bullet.hideturtle()
        bullets.append(bullet)

# Shoot a bullet from a player
def shoot(player):
    # sets position of bullet at x and y of player
    # spawn turtle at x and y
    if bullets:
        bullet = bullets.pop(0)
    else:
        bullet = Turtle(visible=False)
        # bullet.shape("uparrow.png")
        bullet.shape('arrow')
        bullet.speed('fastest')
        bullet.penup()

    # Launch him
    bullet.color(player.fillcolor())
    bullet.setheading(player.heading())
    bullet.setposition(player.position())
    bullet.showturtle()

    travel(bullet, 2000)

bullets = []

# Set speed, GUI, creates new turtle
player_speed = 10
bullet_speed = 15

screen = Screen()
screen.setup(700, 400)
# screen.addshape("uparrow.png")

player_1 = Turtle('triangle')
player_1.speed('fastest')
player_1.color('red', 'pink')
player_1.penup()
player_1.setheading(90)

player_2 = Turtle('triangle')
player_2.speed('fastest')
player_2.color('blue', 'cyan')
player_2.penup()
player_2.setheading(270)

# Movement
screen.onkey(forward_1, "Up")
screen.onkey(back_1, "Down")
screen.onkey(left_1, "Left")
screen.onkey(right_1, "Right")
screen.onkey(shoot_1, "space")

screen.onkey(forward_2, "w")
screen.onkey(back_2, "s")
screen.onkey(left_2, "a")
screen.onkey(right_2, "d")
screen.onkey(shoot_2, "z")

# Game Engine
screen.listen()
screen.mainloop()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!