Skip to content

Commit 40ef62d

Browse files
committed
Use a generator for the mandelbrot demo snippet
1 parent 8143adc commit 40ef62d

File tree

1 file changed

+36
-33
lines changed

1 file changed

+36
-33
lines changed

wasm/demo/snippets/mandelbrot.py

Lines changed: 36 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -3,36 +3,39 @@
33
w = 50.0
44
h = 50.0
55

6-
# to make up for the lack of `global`
7-
_y = {'y': 0.0}
8-
9-
def mandel(_time_elapsed=None):
10-
y = _y['y']
11-
if y >= h:
12-
return
13-
x = 0.0
14-
while x < w:
15-
Zr, Zi, Tr, Ti = 0.0, 0.0, 0.0, 0.0
16-
Cr = 2 * x / w - 1.5
17-
Ci = 2 * y / h - 1.0
18-
19-
i = 0
20-
while i < 50 and Tr + Ti <= 4:
21-
Zi = 2 * Zr * Zi + Ci
22-
Zr = Tr - Ti + Cr
23-
Tr = Zr * Zr
24-
Ti = Zi * Zi
25-
i += 1
26-
27-
if Tr + Ti <= 4:
28-
print('*', end='')
29-
else:
30-
print('·', end='')
31-
32-
x += 1
33-
34-
print()
35-
_y['y'] += 1
36-
request_animation_frame(mandel)
37-
38-
request_animation_frame(mandel)
6+
def mandel():
7+
"""Print a mandelbrot fractal to the console, yielding after each character
8+
is printed"""
9+
y = 0.0
10+
while y < h:
11+
x = 0.0
12+
while x < w:
13+
Zr, Zi, Tr, Ti = 0.0, 0.0, 0.0, 0.0
14+
Cr = 2 * x / w - 1.5
15+
Ci = 2 * y / h - 1.0
16+
17+
i = 0
18+
while i < 50 and Tr + Ti <= 4:
19+
Zi = 2 * Zr * Zi + Ci
20+
Zr = Tr - Ti + Cr
21+
Tr = Zr * Zr
22+
Ti = Zi * Zi
23+
i += 1
24+
25+
if Tr + Ti <= 4:
26+
print('*', end='')
27+
else:
28+
print('·', end='')
29+
30+
x += 1
31+
yield
32+
33+
print()
34+
y += 1
35+
yield
36+
37+
gen = mandel()
38+
def gen_cb(_time=None):
39+
gen.__next__()
40+
request_animation_frame(gen_cb)
41+
gen_cb()

0 commit comments

Comments
 (0)