osyamanbo
osyamanbo

Reputation: 43

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

Upvotes: 2

Views: 133

Answers (1)

Alexander
Alexander

Reputation: 17335

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

Upvotes: 1

Related Questions