{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "bab99d0a", "metadata": {}, "outputs": [], "source": [ "from turtle import * \n", "import time\n", "\n", "def initturtle():\n", " \n", " pencolor('blue')\n", " \n", " speed('slowest')\n", " \n", " tracer(1)\n", " \n", " goto(0,0)\n", " \n", " pendown()\n", "\n", "\n", "def graphword(str):\n", "\n", " for char in str:\n", "\n", " if char == 'F':\n", " \n", " forward(100)\n", "\n", "\n", " if char == '-':\n", " \n", " left(90)\n", "\n", "\n", " if char == '[': # when you see a '[', save the current 'state' of the turtle\n", " \n", " (xpos, ypos) = position() # get current turtle position\n", " \n", " angle = heading() # get current turtle heading angle\n", " \n", " TurtleState = (xpos, ypos, angle) # form a tuple containing the state of the turtle\n", " \n", " stack.append(TurtleState) # store turtle state in a stack\n", "\n", "\n", " if char == ']': # when you see a ']', restore last stored turtle state\n", " \n", " stackpointer = len(stack) - 1\n", " \n", " (xpos, ypos, angle) = stack[stackpointer] # retrieve turtle state from stack\n", " \n", " del stack[stackpointer] # once retrieved, delete from stack\n", " \n", " goto(xpos, ypos) # use retrieved info to set the coordinates of the turtle\n", " \n", " setheading(angle) # also set heading angle\n", "\n", "\n", "initturtle() \n", "\n", "stack = list()\n", "\n", "graphword('F[-F]F')\n", "\n", "done()\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "abe6390a", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.7" } }, "nbformat": 4, "nbformat_minor": 5 }