This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

91 linhas
1.9 KiB

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