This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
1.9 KiB

  1. # This example implements a LOGO-like toy language for Python's turtle, with interpreter.
  2. try:
  3. input = raw_input # For Python2 compatibility
  4. except NameError:
  5. pass
  6. import turtle
  7. from lark import Lark
  8. turtle_grammar = """
  9. start: instruction+
  10. instruction: MOVEMENT NUMBER -> movement
  11. | "c" COLOR [COLOR] -> change_color
  12. | "fill" code_block -> fill
  13. | "repeat" NUMBER code_block -> repeat
  14. code_block: "{" instruction+ "}"
  15. MOVEMENT: "f"|"b"|"l"|"r"
  16. COLOR: LETTER+
  17. %import common.LETTER
  18. %import common.INT -> NUMBER
  19. %import common.WS
  20. %ignore WS
  21. """
  22. parser = Lark(turtle_grammar)
  23. def run_instruction(t):
  24. if t.data == 'change_color':
  25. turtle.color(*t.children) # We just pass the color names as-is
  26. elif t.data == 'movement':
  27. name, number = t.children
  28. { 'f': turtle.fd,
  29. 'b': turtle.bk,
  30. 'l': turtle.lt,
  31. 'r': turtle.rt, }[name](int(number))
  32. elif t.data == 'repeat':
  33. count, block = t.children
  34. for i in range(int(count)):
  35. run_instruction(block)
  36. elif t.data == 'fill':
  37. turtle.begin_fill()
  38. run_instruction(t.children[0])
  39. turtle.end_fill()
  40. elif t.data == 'code_block':
  41. for cmd in t.children:
  42. run_instruction(cmd)
  43. else:
  44. raise SyntaxError('Unknown instruction: %s' % t.data)
  45. def run_turtle(program):
  46. parse_tree = parser.parse(program)
  47. for inst in parse_tree.children:
  48. run_instruction(inst)
  49. def main():
  50. while True:
  51. code = input('> ')
  52. try:
  53. run_turtle(code)
  54. except Exception as e:
  55. print(e)
  56. def test():
  57. text = """
  58. c red yellow
  59. fill { repeat 36 {
  60. f200 l170
  61. }}
  62. """
  63. run_turtle(text)
  64. if __name__ == '__main__':
  65. # test()
  66. main()