-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathexercise_8.py
60 lines (52 loc) · 1.55 KB
/
exercise_8.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
from graphics import GraphWin, Point, Line
from math import pi, cos, sin
def Koch(Turtle, length, degree):
if degree == 0:
Turtle.draw(length)
else:
length1 = length/3
degree1 = degree - 1
Koch(Turtle, length1, degree1)
Turtle.turn(-60)
Koch(Turtle, length1, degree1)
Turtle.turn(120)
Koch(Turtle, length1, degree1)
Turtle.turn(-60)
Koch(Turtle, length1, degree1)
class Turtle:
def __init__(self, point, direction, window):
self.location = point
self.direction = direction * pi / 3
self.win = window
def moveTo(self, newpoint):
self.location = newpoint
def _moveTo(self, length):
dx = length * cos(self.direction)
dy = length * sin(self.direction)
x = self.location.getX()
y = self.location.getY()
x += dx
y += dy
newpoint = Point(x, y)
return self.moveTo(newpoint)
def draw(self, length):
oldLocation = self.location
self._moveTo(length)
path = Line(oldLocation, self.location)
path.draw(self.win)
def turn(self, direction):
if direction == -60:
self.direction -= (pi / 3)
elif direction == 120:
self.direction += (2 * pi / 3)
def main():
length = 500
degree = 5
win = GraphWin("Koch Snowflake", 800, 800)
dir = 0
turtle = Turtle(Point(150, 250), dir, win)
for i in range(3):
Koch(turtle, length, degree)
turtle.turn(120)
win.getMouse()
main()