Python turtle moving using keyboard (code noob)

72 Views Asked by At

So, I need to make a code where turtle move when you press w,a,s,d, without importing keyboard in python.

from turtle import *
x=100
z=90
v=input()
while True:
    if v == 'w':
        forward(x)    
    if v == 's':
        backward(x)
    if v == 'd':
        right(z)
    if v == 'a':
        left(z)

there is the code.

The problem is, when i press any of these buttons turtle moves infinitely, without stopping. I have no idea how to fix this, and im kinda sure its easy to fix. It has to be infinite, so "while" is required. Also dont mind my grammar,I think I did some grammar mistakes here. Code shouldn't be fully rewritten.

2

There are 2 best solutions below

0
AudioBubble On BEST ANSWER

To fix the issue of the turtle moving infinitely without stopping, you need to continuously update the value of v inside the while loop to capture the user input repeatedly.

Here's the modified code:

from turtle import *

x = 100
z = 90

while True:
    v = input("Enter a command (w, a, s, d): ")
    if v == 'w':
        forward(x)
    elif v == 's':
        backward(x)
    elif v == 'd':
        right(z)
    elif v == 'a':
        left(z)
    else:
        print("Invalid command. Please enter w, a, s, or d.")
1
Aadiraj Anil On

while True:
    screen.onkey(forward, "w")
    screen.onkey(backward, "s")
    screen.onkey(right, "d")   
    screen.onkey(left, "a")    
    screen.listen()

do this. put the input part in the loop.