forked from tdamdouni/Pythonista
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathturtle.py
113 lines (89 loc) · 1.99 KB
/
turtle.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# https://gist.github.com/omz/4413863
# turtle.py
# Basic Turtle graphics module for Pythonista
#
# When run as a script, the classic Koch snowflake is drawn as a demo.
# The module can also be used interactively or from other scripts:
# >>> from turtle import *
# >>> right(30)
# >>> forward(100)
# ...
from canvas import set_size, draw_rect, draw_line, set_stroke_color
from math import sin, cos, pi
from time import sleep
heading = 0.0
pos = (0, 0)
pen_is_down = True
DELAY = 0.0
def to_rad(deg):
return deg * pi/180.0
def home():
global heading, pos
heading = 0
pos = (0, 0)
def reset():
set_size(512, 512)
home()
set_stroke_color(0, 0, 0)
draw_rect(0, 0, 512, 512)
set_stroke_color(0, 0, 1)
def forward(distance):
sleep(DELAY)
global pos
to = (pos[0] + sin(heading) * distance, pos[1] + cos(heading) * distance)
if pen_is_down:
draw_line(pos[0], pos[1], to[0], to[1])
pos = to
fd = forward
def backward(distance):
sleep(DELAY)
global pos
to = (pos[0] - sin(heading) * distance, pos[1] - cos(heading) * distance)
if pen_is_down:
draw_line(pos[0], pos[1], to[0], to[1])
pos = to
bk = backward
back = backward
def right(angle):
global heading
heading += to_rad(angle)
rt = right
def left(angle):
global heading
heading -= to_rad(angle)
lt = left
def goto(x, y):
global pos
pos = (x, y)
setpos = goto
setposition = goto
def setheading(angle):
global heading
heading = to_rad(angle)
seth = setheading
def pendown():
global pen_is_down
pen_is_down = True
pd = pendown
down = pendown
def penup():
global pen_is_down
pen_is_down = False
pu = penup
up = penup
reset()
if __name__ == '__main__':
# Draw the Koch snowflake
# (adapted from http://commons.wikimedia.org/wiki/Koch_snowflake)
setposition(100, 100)
koch_flake = 'FRFRF'
iterations = 5
for i in range(iterations):
koch_flake = koch_flake.replace('F', 'FLFRFLF')
for move in koch_flake:
if move == 'F':
forward(100.0 / (3 ** (iterations - 1)))
elif move == 'L':
left(60)
elif move == 'R':
right(120)