Created
December 28, 2018 20:28
-
-
Save md2perpe/8b6d4b5f2dc5f8e5e9c953b1a2f3e5cf to your computer and use it in GitHub Desktop.
Game of life
This file contains 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> | |
<body> | |
<style> | |
td.selected { | |
background: red; | |
} | |
</style> | |
<script> | |
const N = 100; | |
const ROWS = N; | |
const COLS = N; | |
function cell_id(r, c) { | |
return `cell-${r}-${c}`; | |
} | |
// Create board | |
document.writeln('<table width="500" height="500" cellspacing="0" cellpadding="0" id="board">'); | |
for (let r=0; r<ROWS; r++) { | |
document.writeln('<tr>'); | |
for (let c=0; c<COLS; c++) { | |
document.writeln(`<td id="${cell_id(r, c)}" width="1" height="1"></td>`); | |
} | |
document.writeln('</tr>'); | |
} | |
document.writeln('</table>'); | |
// Initialize board | |
for (let r=0; r<ROWS; r++) { | |
for (let c=0; c<COLS; c++) { | |
if (Math.random() < 0.3) { | |
document.getElementById(cell_id(r, c)).className = "selected"; | |
} | |
} | |
} | |
document.writeln('</table>'); | |
setInterval(function () { | |
// Calculate new board | |
for (let r=0; r<ROWS; r++) { | |
for (let c=0; c<COLS; c++) { | |
// Count neighbors | |
let neighbor_count = 0; | |
for (let dr=-1; dr<=1; dr++) { | |
for (let dc=-1; dc<=1; dc++) { | |
if (dr==0 && dc==0) { | |
continue; | |
} | |
if (document.getElementById(cell_id((r+dr+ROWS)%ROWS, (c+dc+COLS)%COLS)).className == "selected") { | |
neighbor_count++; | |
} | |
} | |
} | |
// What should next state be? | |
let td = document.getElementById(cell_id(r,c)); | |
td.newClassName = td.className; | |
if (neighbor_count == 3) { | |
td.newClassName = "selected"; | |
} | |
if (neighbor_count < 2 || neighbor_count > 3) { | |
td.newClassName = ""; | |
} | |
} | |
} | |
// Update board | |
for (let r=0; r<ROWS; r++) { | |
for (let c=0; c<COLS; c++) { | |
let td = document.getElementById(cell_id(r, c)); | |
td.className = td.newClassName; | |
} | |
} | |
}, 100); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment