Created
April 11, 2024 21:47
-
-
Save mzechmeister/c3ac92c09dc330f739d5575900b4f365 to your computer and use it in GitHub Desktop.
game_of_life
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
The game of life.<br> | |
<a href="https://www.youtube.com/watch?v=ouipbDkwHWA">youtube</a> | |
<br> | |
<input type="button" onclick="timer = false" value="||"/> | |
<input type="button" onclick="timer = false; count(cnt)" value=">"/> | |
<input type="button" onclick="timer = true" value=">>"/> | |
<br> | |
<canvas id="canvas" width="80px" height="40px" style="border: red solid 2px; transform-origin: top left; transform: scale(8); image-rendering: -moz-crisp-edges;" onclick="toggle()" onmousemove="if(event.buttons == 1) paint()" ontouchmove=" paint()"></iframe> | |
<script> | |
Nx = canvas.width | |
Ny = canvas.height | |
timer = false | |
var ctx = canvas.getContext("2d", {alpha: false}); | |
var imgData = ctx.getImageData(0, 0, Nx, Ny); | |
var data = imgData.data; | |
ctx.imageSmoothingEnabled = false | |
cnt = D = [...Array(Nx)].map(x => [...Array(Ny)].map(x => false)) | |
D[8][10] = true | |
D[9][11] = true | |
D[10][9] = true | |
D[10][10] = true | |
D[10][11] = true | |
function draw(M) { | |
k = 0 | |
for (j=0; j<Ny; ++j) | |
for (i=0; i<Nx; ++i) { | |
data[k] = data[k+1] = 0xFF * M[i][j] | |
k += 4 | |
} | |
ctx.putImageData(imgData, 0, 0); | |
} | |
function count(M) { | |
cnt = [...Array(Nx)].map(x => [...Array(Ny)].map(x => 0)) | |
for (i=1; i<Nx-1; ++i) | |
for (j=1; j<Ny-1; ++j) { | |
cnt[i][j] = M[i-1][j-1] + M[i][j-1] + M[i+1][j-1] + | |
M[i-1][j] + M[i+1][j] + | |
M[i-1][j+1] + M[i][j+1] + M[i+1][j+1] | |
cnt[i][j] = (M[i][j] && cnt[i][j] == 2) || (cnt[i][j] == 3) | |
} | |
draw(cnt) | |
} | |
function toggle(){ | |
i = parseInt((event.clientX-canvas.offsetLeft)/8-2) | |
j = parseInt((event.clientY-canvas.offsetTop)/8-2) | |
cnt[i][j] = !cnt[i][j] | |
draw(cnt) | |
} | |
function paint(){ | |
e = event.touches ? event.touches[0] : event | |
i = parseInt((e.clientX-canvas.offsetLeft)/8-2) | |
j = parseInt((e.clientY-canvas.offsetTop)/8-2) | |
cnt[i][j] = true | |
draw(cnt) | |
} | |
function runtimer() { | |
setInterval(function() { | |
if (timer) count(cnt) | |
}, 100) | |
} | |
draw(cnt) | |
runtimer() | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Preview: https://gistpreview.github.io/?c3ac92c09dc330f739d5575900b4f365