Advertisement
mikhail_dvorkin

Dragon Curve lesson code

May 27th, 2020
1,465
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.91 KB | None | 0 0
  1. import math
  2. import random
  3.  
  4. lr2rl = str.maketrans({'L': 'R', 'R': 'L'})
  5.  
  6. def dragon_curve(n):
  7.     if n == 0:
  8.         return ""
  9.     return dragon_curve(n - 1) + "L" + dragon_curve(n - 1)[::-1].translate(lr2rl)
  10.  
  11. def turtle_graphics(f, x, y, step, turns):
  12.     dx, dy = step, 0
  13.     for turn in turns + "F":
  14.         svg_line = f'<line x1="{x}" y1="{y}" x2="{x + dx}" y2="{y + dy}" stroke="black" stroke-width="3"/>'
  15.         print(svg_line, file=f)
  16.         x += dx; y += dy
  17.         matrix = moves[turn]
  18.         dx, dy = matrix[0] * dx + matrix[1] * dy, matrix[2] * dx + matrix[3] * dy
  19.  
  20. def random_turn(dx, dy):
  21.     alpha = random.random() * 2 * math.pi
  22.     return dx * math.cos(alpha) + dy * math.sin(alpha), -dx * math.sin(alpha) + dy * math.cos(alpha)
  23.  
  24. moves = {
  25.     'F': (1, 0, 0, 1),
  26.     'L': (0, 1, -1, 0),
  27.     'R': (0, -1, 1, 0),
  28.     'M': (math.cos(math.pi / 16), math.sin(math.pi / 16), -math.sin(math.pi / 16), math.cos(math.pi / 16))
  29. }
  30. f = open("generated.svg", "w")
  31. print("<!-- Generated -->", file=f)
  32. # os.system("generated.svg")
  33. hei = 800
  34. wid = 800
  35. print('<svg xmlns="http://www.w3.org/2000/svg" height="' + str(hei) + 'px" width="' + str(wid) + 'px">', file=f)
  36. turns = dragon_curve(13) # "FFFFLRFFFFMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
  37. print(turns)
  38. turtle_graphics(f, wid // 2, hei // 2, 3, turns)
  39. print('</svg>', file=f)
  40. f.close()
  41.  
  42. /*
  43. 1   L   1   v←
  44. 2   L   10  ←
  45. 3   R   11  v
  46. 4   L   100
  47. 5   L   101 v
  48. 6   R   110
  49. 7   R   111 v
  50. 8   L   1000    ←
  51. 9   L   1001    v
  52. 10  L   1010
  53. 11  R   1011    v
  54. 12  R   1100
  55. 13  L   1101    v
  56. 14  R   1110
  57. 15  R   1111    v
  58. 16  L   10000   ←
  59. 17  L   10001   v
  60. 18  L   10010
  61. 19  R   10011   v
  62. 20  L   10100
  63. 21  L   10101   v
  64. LLRLLRRLLL
  65. 10010110101110000   x
  66. 10010110101101111   x - 1
  67. 00000000000011111   x xor (x - 1)
  68. 00000000000100000   x xor (x - 1) + 1
  69. 00000000000100000   x and (x xor (x - 1) + 1) является ли 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement