Skip to content

Commit 3d306fc

Browse files
Merge pull request RustPython#655 from coolreader18/mandelbrot-snippet-generator
Use a generator for the mandelbrot demo snippet
2 parents caae69f + 4820250 commit 3d306fc

File tree

1 file changed

+40
-35
lines changed

1 file changed

+40
-35
lines changed

wasm/demo/snippets/mandelbrot.py

Lines changed: 40 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,43 @@
1-
from browser import request_animation_frame
2-
31
w = 50.0
42
h = 50.0
53

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)
4+
def mandel():
5+
"""Print a mandelbrot fractal to the console, yielding after each character
6+
is printed"""
7+
y = 0.0
8+
while y < h:
9+
x = 0.0
10+
while x < w:
11+
Zr, Zi, Tr, Ti = 0.0, 0.0, 0.0, 0.0
12+
Cr = 2 * x / w - 1.5
13+
Ci = 2 * y / h - 1.0
14+
15+
i = 0
16+
while i < 50 and Tr + Ti <= 4:
17+
Zi = 2 * Zr * Zi + Ci
18+
Zr = Tr - Ti + Cr
19+
Tr = Zr * Zr
20+
Ti = Zi * Zi
21+
i += 1
22+
23+
if Tr + Ti <= 4:
24+
print('*', end='')
25+
else:
26+
print('·', end='')
27+
28+
x += 1
29+
yield
30+
31+
print()
32+
y += 1
33+
yield
34+
35+
try: from browser import request_animation_frame
36+
except: request_animation_frame = None
37+
38+
gen = mandel()
39+
def gen_cb(_time=None):
40+
gen.__next__()
41+
request_animation_frame(gen_cb)
42+
if request_animation_frame: gen_cb()
43+
else: list(gen)

0 commit comments

Comments
 (0)