简体   繁体   中英

Make one Python turtle chase another turtle

I'm creating a game where the user uses the keyboard to move a turtle in order to avoid another turtle. This is my code:

import turtle
playGround = turtle.Screen()
playGround.screensize(500, 500)
playGround.title("Turtle Keys")

run = turtle.Turtle()
follow = turtle.Turtle()
run.shape("turtle")
follow.shape("turtle")
run.color("blue")
follow.color("red")
run.penup()
follow.penup()
run.st()

def k1():
    run.forward(45)
def k2():
    run.left(45)
def k3():
    run.right(45)
def k4():
    run.back(45)
def quitThis():
    playGround.bye()
playGround.onkey(k1, "Up")  # the up arrow key
playGround.onkey(k2, "Left") # the left arrow key
playGround.onkey(k3, "Right") # you get it!
playGround.onkey(k4, "Down")
playGround.onkey(quitThis,'q')
playGround.listen()

I want to make the red turtle chase the blue turtle but it is not working.

What you're missing is computer controlled motion of the blue/follow turtle. We can do that by adding an ontimer() event handler that invokes setheading() on towards() to keep blue/follow facing red/run. Plus a little bit of forward motion on blue/follow. Something like this:

from turtle import Turtle, Screen

playGround = Screen()
playGround.screensize(500, 500)
playGround.title("Turtle Keys")

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(45)

def k3():
    run.right(45)

def k4():
    run.backward(10)

def quitThis():
    playGround.bye()

def follow_runner():
    follow.setheading(follow.towards(run))
    follow.forward(1)
    playGround.ontimer(follow_runner, 10)

playGround.onkey(k1, "Up")  # the up arrow key
playGround.onkey(k2, "Left")  # the left arrow key
playGround.onkey(k3, "Right")  # you get it!
playGround.onkey(k4, "Down")
playGround.onkey(quitThis, 'q')

playGround.listen()

follow_runner()

playGround.mainloop()

You can tweak the performance of blue/follow by changing the amount it moves in its forward() statement. Once you get above 1, you'll be surprised how quickly it catches up with red/run.

You'll need to add the code to detect when the turtles collide and whatever follows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM