mirror of
https://github.com/RustPython/RustPython.git
synced 2026-10-28 18:59:04 +08:00
Use a generator for the mandelbrot demo snippet
This commit is contained in:
1 file changed
+31
-28
@@ -3,36 +3,39 @@ from browser import request_animation_frame
|
||||
w = 50.0
|
||||
h = 50.0
|
||||
|
||||
# to make up for the lack of `global`
|
||||
_y = {'y': 0.0}
|
||||
def mandel():
|
||||
"""Print a mandelbrot fractal to the console, yielding after each character
|
||||
is printed"""
|
||||
y = 0.0
|
||||
while y < h:
|
||||
x = 0.0
|
||||
while x < w:
|
||||
Zr, Zi, Tr, Ti = 0.0, 0.0, 0.0, 0.0
|
||||
Cr = 2 * x / w - 1.5
|
||||
Ci = 2 * y / h - 1.0
|
||||
|
||||
def mandel(_time_elapsed=None):
|
||||
y = _y['y']
|
||||
if y >= h:
|
||||
return
|
||||
x = 0.0
|
||||
while x < w:
|
||||
Zr, Zi, Tr, Ti = 0.0, 0.0, 0.0, 0.0
|
||||
Cr = 2 * x / w - 1.5
|
||||
Ci = 2 * y / h - 1.0
|
||||
i = 0
|
||||
while i < 50 and Tr + Ti <= 4:
|
||||
Zi = 2 * Zr * Zi + Ci
|
||||
Zr = Tr - Ti + Cr
|
||||
Tr = Zr * Zr
|
||||
Ti = Zi * Zi
|
||||
i += 1
|
||||
|
||||
i = 0
|
||||
while i < 50 and Tr + Ti <= 4:
|
||||
Zi = 2 * Zr * Zi + Ci
|
||||
Zr = Tr - Ti + Cr
|
||||
Tr = Zr * Zr
|
||||
Ti = Zi * Zi
|
||||
i += 1
|
||||
if Tr + Ti <= 4:
|
||||
print('*', end='')
|
||||
else:
|
||||
print('·', end='')
|
||||
|
||||
if Tr + Ti <= 4:
|
||||
print('*', end='')
|
||||
else:
|
||||
print('·', end='')
|
||||
x += 1
|
||||
yield
|
||||
|
||||
x += 1
|
||||
print()
|
||||
y += 1
|
||||
yield
|
||||
|
||||
print()
|
||||
_y['y'] += 1
|
||||
request_animation_frame(mandel)
|
||||
|
||||
request_animation_frame(mandel)
|
||||
gen = mandel()
|
||||
def gen_cb(_time=None):
|
||||
gen.__next__()
|
||||
request_animation_frame(gen_cb)
|
||||
gen_cb()
|
||||
Reference in new issue
Block a user