0

I am writing a program that needs input in the console to control where a turtle goes on the screen. For example, if the user of the program types w in the console, and presses enter, the turtle should move forward 30 units. If the user types a, the turtle should turn left 45 degrees, etc.

I wrote some functions and used an infinite while loop for the program. It looks like this:

def movemattfd():
    matt.fd(30)

def movemattlt():
    matt.lt(45)

def movemattrt():
    matt.rt(45)

def movemattbk():
    matt.back(30)

def movematt():
    while True:
        input()
        if input() == 'w':
            movemattfd()

        if input() == 'a':
            movemattlt()

        if input() == 'd':
            movemattrt()

        if input() == 's':
            movemattbk()

def main():
    windowHeight = 500
    windowWidth = 500
    turtle.screensize(windowWidth, windowHeight, None)
    movematt()

main()

The program works, except when I enter w in the console, it takes at least 2 entries to get my turtle to move forward. It takes even more when I try to turn my turtle right.

Any ideas? Thanks in advance.

2
  • you should learn about extracting result into separate objects and elif keyword Commented Oct 18, 2017 at 0:37
  • why do you need first input() right after while True: line? Commented Oct 18, 2017 at 0:38

1 Answer 1

1

Each input() prompts for a new entry from the user.

What your code does is, for every set of 5 entries:

  • discard the first entry
  • check if the second entry is 'w' then move forward
  • check if the third entry is 'a' then move left
  • check if the fourth entry is 's' then move right
  • check if the fifth entry is 'd' then move back

You should assign the first input() to a variable, then check with that.
Use elif to avoid checking other characters if it already satisfies one.

while True:
    entry = input()
    if entry == 'w':
        movemattfd()

    elif entry == 'a':
        movemattlt()

    elif entry == 'd':
        movemattrt()

    elif entry == 's':
        movemattbk()

Not the answer you're looking for? Browse other questions tagged or ask your own question.