0

I would like to create a program in which a Turtle object responds to key presses. I can do this, but I can't seem to understand how to move a second Turtle object, which is controlled by the computer, while the first one is moving. Any help would be appreciated.

Here is my code:

from turtle import *
from Tkinter import Tk
root = Tk()
root.withdraw()
turtle = Turtle()
def h1():turtle.forward(10)
def h2():turtle.left(45)
def h3():turtle.right(45)
def h4():turtle.back(10)
def h5(root=root):root.quit()
onkey(h1,"Up")
onkey(h2,"Left")
onkey(h3,"Right")
onkey(h4,"Down")
onkey(h5,"q")
listen()
root.mainloop()

2 Answers 2

1

Insert a second turtle before listen() that moves with keys w,a,s,d:

turtle2 = Turtle()
def h11():turtle2.forward(10)
def h21():turtle2.left(45)
def h31():turtle2.right(45)
def h41():turtle2.back(10)
onkey(h11,"w")
onkey(h21,"a")
onkey(h31,"d")
onkey(h41,"s")
Sign up to request clarification or add additional context in comments.

Comments

0

I can't seem to understand how to move a second Turtle object, which is controlled by the computer, while the first one is moving.

Below is some minimal code that does as you describe. Green turtle Pokey is computer controlled while red turtle Hokey is user controlled (click on the window first so your keystrokes are heard):

from turtle import Turtle, Screen

def move_pokey():
    pokey.forward(10)
    x, y = pokey.position()

    if not (-width/2 < x < width/2 and -height/2 < y < height/2):
        pokey.undo()
        pokey.left(90)

    screen.ontimer(move_pokey, 100)

hokey = Turtle(shape="turtle")
hokey.color("red")
hokey.penup()

pokey = Turtle(shape="turtle")
pokey.setheading(30)
pokey.color("green")
pokey.penup()

screen = Screen()

width = screen.window_width()
height = screen.window_height()

screen.onkey(lambda: hokey.forward(10), "Up")
screen.onkey(lambda: hokey.left(45), "Left")
screen.onkey(lambda: hokey.right(45), "Right")
screen.onkey(lambda: hokey.back(10), "Down")
screen.onkey(screen.bye, "q")

screen.listen()

screen.ontimer(move_pokey, 100)

screen.mainloop()

This is not finished code (shutdown of the timer event should be cleaner, Hokey's handlers should lock out additional events while running, etc.) but should give you a basic idea of how to go about it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.