简体   繁体   中英

Turtle Graphics path using a string

Edit: I managed to fix it.

...

I don't know too much about Python but I'm trying to write a function that uses Python's Turtle Graphics to draw a simple path based on the characters in the string.

So, for example, if string = "FRRL" then the turtle should move forward, right, right, left.

When I run this code:

import turtle

step = 100
angle = 90

t = turtle.Turtle()

t.forward(step)
t.left(angle)
t.right(angle)

turtle.done()

It gives a different output to the one I am trying to make below:

import turtle

t = turtle.Turtle()   
S = "FLR"
step = 100
angle = 90

for i in S:

    if i == 'F' or 'E':
        t.forward(step)

    if i == 'L':
        t.left(angle)

    if i == 'R':
        t.right(angle)

turtle.done()

The code runs but it seems that in this one it moves the turtle the direction it's facing (so forward I guess) on top of what the if i == '...': t....(angle/step) is telling it to do. So, for example if i == 'R', it will move it forward first and then turn it by 90 degrees to the right, instead of just turning it - same for i == 'F' and i == 'L'. It moves all of them forward first before carrying out the turtle move I want it to.

How do I fix this? Thanks.

From your comments, I guess (and this is bad, as you should have given more details about that) you expect that when the letter is "L" the turtle would turn left based on "angle" AND walk the "step".

So, in this case, you missed the forward walk, and this would be the right addition to do so:

if i == 'L':
    t.left(angle)
    t.forward(step)

if i == 'R':
    t.right(angle)
    t.forward(step)

PS: In any case, both versions you posted work the same for me!

I fixed the problem by changing

if i == 'F' or 'E':

to

if i in ['F', 'E']:

and now it works as it should.

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