python turtle : how to make a turtle object that can shoot bullets automatically?

how to make a turtle object that can shoot bullets automatically and under control? please help me. i have tried this code and the game is crashing(Enemy aircraft fired bullets continuously without pause since they first appeared)
This is my code :

bg.addshape("F 22 Raptor.gif")
enemy2 = turtle.Turtle()
enemy2.shape("F 22 Raptor.gif")
enemy2.setheading(-90)
enemy2.turtlesize(3)
enemy2.penup()
enemy2.goto(0,360)

PlayerBullets = [] # Menyimpan peluru
EnemyBullets = [] # Menyimpan peluru musuh

def EnemyBullet():
    Ebullet = turtle.Turtle()
    Ebullet.shape("triangle")
    Ebullet.color("yellow")
    Ebullet.shapesize(stretch_wid=0.3, stretch_len=0.1)
    Ebullet.penup()
    Ebullet.goto(enemy2.xcor(), enemy2.ycor())  # Posisi awal peluru sama dengan posisi Spaceshuttle
    Ebullet.speed(0.01)
    return Ebullet

def EFireBullet():
    Ebullet = EnemyBullet()
    EnemyBullets.append(Ebullet)
    bulletsSound.play()

def MoveEnemyBullets():
    global EnemyBullets
    newbullets = []
    for Ebullet in EnemyBullets:
        y = Ebullet.ycor()
        y += -2  # Mengubah posisi Y agar peluru turun
        Ebullet.sety(y)

        if y > 300:# Hapus peluru yang mencapai batas atas layar
            Ebullet.hideturtle()
        else:
            newbullets.append(Ebullet)
    EnemyBullets = newbullets

def CheckEnemyCollision():
    global score, HighScore
    for Ebullet in EnemyBullets:
        if Ebullet.distance(SpaceShuttle) < 20: 
            Ebullet.hideturtle()  # menyembunyikan peluru jika mencapai batas atas layar
            EnemyBullets.remove(Ebullet)
            HitMarker.play()
            if score > HighScore:
                HighScore = score
                with open("highscore.txt", "w") as file:
                    file.write(str(HighScore))

  • You forgot to include the code you are referring to.

    – 

  • Even if you get this working, it’ll leak memory and eventually crash since turtles are basically impossible to garbage collect. Refer to this answer. I don’t suggest allocating a new list just to move turtles–better to simply call .forward() or .sety() on each one in a loop.

    – 




Leave a Comment