【问题标题】:How do you make a collision detection for turtle in python?如何在 python 中对海龟进行碰撞检测?
【发布时间】:2021-01-12 14:52:49
【问题描述】:

我遇到了问题,当我使用代码时:

from turtle import Turtle, Screen

playGround = Screen()
playGround.screensize(500, 500)
playGround.title("Race")
x=0

run = Turtle("turtle")
run.speed("fastest")
run.color("blue")
run.penup()
run.setposition(250, 250)

follow = Turtle("turtle")
follow.speed("fastest")
follow.color("red")
follow.penup()
follow.setposition(-250, -250)

def k1():
    run.forward(10)

def k2():
    run.left(20)

def k3():
    run.right(45)

def k4():
    run.backward(20)


def follow_runner():
    if x==0:
        follow.setheading(follow.towards(run))
        follow.forward(0.7)
        playGround.ontimer(follow_runner, 10)
        
while 1==1:
    playGround.onkey(k1, "Up")  # the up arrow key
    playGround.onkey(k2, "Left")  # the left arrow key
    playGround.onkey(k3, "Right") #It's obvious  
    playGround.onkey(k4, "Down")

    playGround.listen()

    follow_runner()
    runx= run.xcor()
    runy= run.ycor()
    followx = follow.xcor()
    followy= follow.ycor()

    playGround.mainloop()
    if  runx==followx and runy==followy:
        playGround.clear()
        x=1

当follow touch touch运行时,它只是继续,这意味着代码失败了。
我想让它工作并使箭头键能够按住。你能帮助我吗?请不要关闭它。

【问题讨论】:

    标签: python python-turtle


    【解决方案1】:

    如果您希望海龟在按键保持中移动,请使用onkeypress()。另外,请注意,不需要使用 while 循环。

    这里用这个:

    from turtle import Turtle, Screen
    import turtle
    playGround = Screen()
    playGround.screensize(500, 500)
    playGround.title("Race")
    x=0
    
    run = Turtle("turtle")
    run.speed("fastest")
    run.color("blue")
    run.penup()
    run.setposition(250, 250)
    
    
    follow = Turtle("turtle")
    follow.speed("fastest")
    follow.color("red")
    follow.penup()
    follow.setposition(-250, -250)
    
    
    def k1():
        run.forward(10)
    
    def k2():
        run.left(20)
    
    def k3():
        run.right(45)
    
    def k4():
        run.backward(20)
    
    
    def follow_runner():
        global x
        runx= run.xcor()
        runy= run.ycor()
        followx = follow.xcor()
        followy= follow.ycor()
    
        if x==0:
            follow.setheading(follow.towards(run))
            follow.forward(0.7)
            playGround.ontimer(follow_runner, 10)
        
        if int(runx) == int(followx) or int(runy) == int(followy):
           
            x=1
            playGround.clear()
    
    
    playGround.onkeypress(k1, "Up")  # the up arrow key
    playGround.onkeypress(k2, "Left")  # the left arrow key
    playGround.onkeypress(k3, "Right") #It's obvious  
    playGround.onkeypress(k4, "Down")
    
    
    follow_runner()
    
    playGround.listen()
    playGround.mainloop()
    
    

    【讨论】:

      猜你喜欢
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-26
      • 2014-04-13
      相关资源
      最近更新 更多