Search code examples
pythonfunctionturtle-graphicspython-turtle

Is there a way to mirror a python function?


I am a student taking my first python class and we are using Turtle to draw an image. In an effort to save time I am trying to create a mirror function that can flip one functions results over the y-axis by a given number of pixels. For the sake of simplicity I created some functions to speed up my coding. Here is how my code works:

units, north, east, south, west = desiredPixelsPerUnit, 90, 0, 270, 180

def main():
    eye(30, 15)
    eye(40, 15)

def left():
    myTurtle.left(90)
def draw(count):
    distance = units * count
    myturtle.forward(distance)
def singleStep(xDirection, yDirection, stepCount):
    down()
    for step in range(stepCount):
        if yDirection == north:
            point(north)
            draw(1)
            if xDirection == east:
                point(east)
                draw(1)
         etc..
def eye(xPosition, yPosition):
    ....
    draw(3)
    left()
    draw(2)
    left()
    ....
    singleStep(east, north, 1)
    singleStep(west, north, 2)
    etc....

All of this gives me the following

Result of running eye() in main twice:

enter image description here

What I am trying to create is a function that is passed another function then will look at what is being executed. if it is left() or right() run the opposite. If it is point (x, y) add 180 to x. If it has a function call that inside the function then it checks that as well for lefts or rights. Something like this.

def mirror(function):
    for action in function:
        if action == left():
            execute right()
        ...
        elif action == singleStep():
            newFunction = singleStep()
            for action in newFunction:
                if:
                    statement above
                else:
                    statement below
       else:
           execute initial action

I am still very new to coding and programming. I have tried using arrays, associative arrays and lists, using eval and more. The time spent trying to figure it out has been far longer than writing a separate instruction list for the left and the right hahah but I really want to figure out how to do something like this.


Solution

  • You could step back from calling left() and right() directly. Just create your own functions your_left() and your_right() and use them everytime. Then use a global variable called mirror. This variable will work as a flag for you. So you just set mirror to True when you want to mirror the output.

    Your functions your_right() and your_left() will be looking something like this:

    def your_right():
        left() if mirror else right()
    
    def your_left():
        right() if mirror else left()
    

    And then you are free to mirror all your outputs, if you want to. I hope i could help!