This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

81 righe
1.8 KiB

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