Skip to content

Commit b189d38

Browse files
committed
Sprig App - Mandelbrot Viewer
1 parent 62970b5 commit b189d38

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

Diff for: games/Mandelbrot-Viewer.js

+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
const maxIter = 64; // Iteration limit for Mandelbrot
2+
let centerX = -0.5;
3+
let centerY = 0.0;
4+
let zoom = 2.0;
5+
const gridWidth = 256;
6+
const gridHeight = 256;
7+
8+
const shades = ["0", "1"];
9+
10+
setLegend(
11+
["0", bitmap`
12+
2222222222222222
13+
2222222222222222
14+
2222222222222222
15+
2222222222222222
16+
2222222222222222
17+
2222222222222222
18+
2222222222222222
19+
2222222222222222
20+
2222222222222222
21+
2222222222222222
22+
2222222222222222
23+
2222222222222222
24+
2222222222222222
25+
2222222222222222
26+
2222222222222222
27+
2222222222222222`],
28+
["1", bitmap`
29+
0000000000000000
30+
0000000000000000
31+
0000000000000000
32+
0000000000000000
33+
0000000000000000
34+
0000000000000000
35+
0000000000000000
36+
0000000000000000
37+
0000000000000000
38+
0000000000000000
39+
0000000000000000
40+
0000000000000000
41+
0000000000000000
42+
0000000000000000
43+
0000000000000000
44+
0000000000000000`]
45+
);
46+
47+
function mandelbrot(x, y) {
48+
let real = x;
49+
let imag = y;
50+
let iter = 0;
51+
while (real * real + imag * imag <= 4 && iter < maxIter) {
52+
let temp = real * real - imag * imag + x;
53+
imag = 2 * real * imag + y;
54+
real = temp;
55+
iter++;
56+
}
57+
return iter;
58+
}
59+
60+
function drawMandelbrot() {
61+
let level = "";
62+
for (let j = 0; j < gridHeight; j++) {
63+
for (let i = 0; i < gridWidth; i++) {
64+
let x = centerX + (i - gridWidth / 2) * (zoom / gridWidth);
65+
let y = centerY + (j - gridHeight / 2) * (zoom / gridHeight);
66+
let iter = mandelbrot(x, y);
67+
let char = Math.floor(iter / (maxIter / shades.length));
68+
level += shades[Math.min(char, shades.length - 1)];
69+
}
70+
level += "\n";
71+
}
72+
setMap(map`${level}`);
73+
}
74+
75+
drawMandelbrot();
76+
77+
onInput("w", () => { centerY -= zoom * 0.1; drawMandelbrot(); });
78+
onInput("s", () => { centerY += zoom * 0.1; drawMandelbrot(); });
79+
onInput("a", () => { centerX -= zoom * 0.1; drawMandelbrot(); });
80+
onInput("d", () => { centerX += zoom * 0.1; drawMandelbrot(); });
81+
onInput("i", () => { zoom *= 0.8; drawMandelbrot(); });
82+
onInput("k", () => { zoom *= 1.25; drawMandelbrot(); });
83+

0 commit comments

Comments
 (0)