简体   繁体   中英

Is there a way to move turtle slower in Python Turtle Graphics?

I have made a program to move turtle position by pressing the keyboard, but is there a way to make it move in smaller increments of pixels?

and also, is it possible to move turtle up and down instead of only left and right?

from turtle import Screen, Turtle
TURTLE_SIZE = 200

# functions
def go_left():
    t.direction = 'left'

def go_right():
    t.direction = 'right'

screen = Screen()
screen.setup(1152,648)
screen.tracer(0)

# player
t = Turtle()
t.shape("circle")
t.speed("slowest")
t.color("blue")
t.penup()
t.setx(338)
t.sety(0)
t.direction = 'stop'

# Keyboard
screen.onkeypress(go_left, 'Left')
screen.onkeypress(go_right, 'Right')
screen.listen()

while True:
    x = t.xcor()

    if t.direction == 'left':
        if x > TURTLE_SIZE - 576:
            x -= 3
            t.setx(x)
        else:
            t.direction = 'stop'
    elif t.direction == 'right':
        if x < 576 - TURTLE_SIZE:
            x += 3
            t.setx(x)
        else:
            t.direction = 'stop'

    screen.update()

screen.mainloop()

The reason your dot was moving so fast was because of your while True loop.

I moved most of that logic inside the the go_ functions and added an up and down for you as well.

from turtle import Screen, Turtle
TURTLE_SIZE = 200

def go_left():
    x = t.xcor()
    if x > TURTLE_SIZE - 576:
        x -= 3
        t.setx(x)
    screen.update()

def go_right():
    x = t.xcor()
    if x < 576 - TURTLE_SIZE:
        x += 3
        t.setx(x)
    screen.update()

def go_up():  # added this function
    y = t.ycor()
    if y < 576 - TURTLE_SIZE:
        y += 3
        t.sety(y)
    screen.update()

def go_down():  # added this function
    y = t.ycor()
    if y < 576 - TURTLE_SIZE:
        y -= 3
        t.sety(y)
    screen.update()

screen = Screen()
screen.setup(1152,648)
screen.tracer(0)

t = Turtle()
t.shape("circle")
t.speed("slowest")
t.color("blue")
t.penup()
t.setx(338)
t.sety(0)
screen.update()

# Keyboard
screen.onkeypress(go_left, 'Left')
screen.onkeypress(go_down, 'Down')   # added this listener
screen.onkeypress(go_up, 'Up')       # added this listner
screen.onkeypress(go_right, 'Right')
screen.listen()
screen.mainloop()

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