首页 > 解决方案 > 如何乘以python流星对象

问题描述

好的,所以我正在尝试制作一个你必须躲避流星的流星游戏。但我不只想要一颗流星,我想要多颗。那么如何将我的第一颗流星复制到更多流星中呢?

我试过用一个函数来做更多。但这给了我一个错误。我尝试使用 while 循环,所以它运行流星代码 10 次,但没有奏效

    import turtle
    import random
    # meteorgame by Daniel99oslo

    wn = turtle.Screen()
    wn.title("Meteor")
    wn.bgcolor("black")
    wn.setup(width=500, height=600)
    wn.tracer(0)

    #Player    
    Player = turtle.Turtle()
    Player.speed(0)
    Player.shape("square")
    Player.color("Blue")
    Player.shapesize(stretch_wid=1, stretch_len=1)
    Player.penup()
    Player.goto(0, -100)

    #Meteor    
    Meteor = turtle.Turtle()
    Meteor.speed(0)
    Meteor.shape("square")
    Meteor.color("red")
    Meteor.shapesize(stretch_wid=1, stretch_len=1)
    Meteor.penup()
    Meteor.goto(0, 290)

    y1 = (random.randint(500,600))
    y2 = Meteor.ycor()
    Meteor.sety(y1)


    # left/right
    def Player_Left():
        x = Player.xcor()
        x -= 5
        Player.setx(x)
    def Player_Right():
        x = Player.xcor()
        x += 5
        Player.setx(x)

    # Keyboard binds a/d
    wn.listen()
    wn.onkeypress(Player_Left, "a")
    wn.onkeypress(Player_Right, "d")

    # Main game loop
    while True:
        wn.update()

        #Meteor respawn/location
        x1 = (random.randint(-230,230))
        y = Meteor.ycor()
        y -= 0.1
        Meteor.sety(y)
        if Meteor.ycor() <-300:
            Meteor.sety(290)


            x = Meteor.xcor()
            Meteor.setx(x1)
        #Meteor hit player detection

        if Player.distance(Meteor) < 25:
            #Code that will kill player add here
            pass

标签: pythonturtle-graphics

解决方案


如果你只是循环遍历流星代码,你有 10 次仍然只能得到一个结果,因为每次循环遍历它时变量都会被覆盖。处理此问题的一种简单方法是创建一个列表并将流星存储在其中。

meteors = []
for i in range(10):
     Meteor = turtle.Turtle()
     ...
     meteors.append(Meteor)

推荐阅读