【问题标题】:How do I make my game reset when my turtle hits an sprite?当我的乌龟撞到精灵时,如何让我的游戏重置?
【发布时间】:2020-12-05 15:47:21
【问题描述】:

标题解释了我想用这个程序做什么,当我的乌龟撞到一个圆圈时,游戏重置/结束

这是宇宙飞船(你的角色)的代码:

move = turtle.Turtle()

showturtle()
turtle.hideturtle()
move.setposition(-500,0)
move.pencolor('cyan')
move.fillcolor("blue")
move.penup()
move.speed()
move.shapesize(3,3,3)



turtle.fillcolor("blue")
turtle.shapesize(3,3,3)
outline = ['white', 'green', 'red', 'blue', 'purple', 'yellow', 'orange']
colors = ['red', 'blue', 'green', 'purple', 'yellow', 'orange', 'black']


def up():
   move.forward(25)

def down():
   move.backward(15)

def left():
    move.left(30)


def right():
    move.right(30)
 


def clickleft(x,y):
    move.fillcolor(random.choice(colors))

def clickright(x,y):
    move.pencolor(random.choice(outline))


    
turtle.listen()

turtle.onscreenclick(clickleft, 1)
turtle.onscreenclick(clickright, 3)

turtle.onkey(up, 'Up')
turtle.onkey(down, 'Down')
turtle.onkey(left, 'Left')
turtle.onkey(right, 'Right')

这是小行星(移动命中时游戏重置的精灵):

asteroid_prototype = Turtle()
asteroid_prototype.hideturtle()
asteroid_prototype.color('grey')
asteroid_prototype.shape('circle')
asteroid_prototype.shapesize(ASTEROID_RADIUS / CURSOR_SIZE)
asteroid_prototype.speed('fastest')  # because 15 isn't a valid argument
asteroid_prototype.penup()

asteroids = []

for _ in range(NUMBER_ASTEROIDS):
    asteroid = asteroid_prototype.clone()
    asteroid.setposition( \
        randint(ASTEROID_RADIUS - WIDTH, WIDTH - ASTEROID_RADIUS), \
        randint(ASTEROID_RADIUS - HEIGHT, HEIGHT - ASTEROID_RADIUS) \
    )

    while any(map((lambda a: lambda b: a.distance(b) < ASTEROID_RADIUS)(asteroid), asteroids)):
        asteroid.setposition( \
            randint(ASTEROID_RADIUS - WIDTH, WIDTH - ASTEROID_RADIUS), \
            randint(ASTEROID_RADIUS - HEIGHT, HEIGHT - ASTEROID_RADIUS) \
        )

    asteroid.showturtle()
    asteroids.append(asteroid)

我需要它,所以如果移动命中 asteroid_prototype,游戏会重置或至少结束。 提前谢谢你

【问题讨论】:

标签: python turtle-graphics python-turtle


【解决方案1】:

您可以尝试创建一个函数来将所有内容移动到其起始位置(我已将其命名为 startPos)。我将放置海龟的所有位置,将所有分数重置为 0,并在此函数中清空所有敌人列表等。然后,当 asteroid_prototype 和你的海龟在同一位置时调用它。例如,在你的主循环中

for i in range(asteroids):
    if i.xcor == turtle.xcor and i.ycor == turtle.ycor:
        startPos()

您始终可以稍微更改参数,以便它们不必处于完全相同的位置if i.xcor &gt; turtle.xcor - 5 and i.xcor &lt; turtle.xcor + 5 and i.ycor &gt; turtle.ycor - 5 and i.ycor &lt; turtle.ycor + 5 或类似的位置。您可能希望将参数设置为海龟/小行星半径的大小(我选择了 5 作为任意数字)。

我希望这会有所帮助,并且写得足够清楚。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 2022-11-19
    • 1970-01-01
    • 2019-06-04
    相关资源
    最近更新 更多