ASCII animated snow scene
Example program for codegolf.stackexchange.com
by plstand
HTML
<textarea id="output" cols="80" rows="24" disabled>
</textarea>
<textarea id="input" cols="80" rows="24" disabled>
****
****
**** ****
**** ****
**** ****
*** **** ****
******* **** ****
******** *** ***
********* ***
******* ******
************* **
***********
*** **** ***
*** **************** ***
*** **************** ***
*** ***
*** **************** ***
*** ***
****************************
****************************
</textarea>
CSS
body {
margin: 1em;
}
textarea {
background: black;
color: white;
}
#input {
display: none;
}
JavaScript
var snow = [], art = [];
function $(id) {
return document.getElementById(id);
}
function initArrays() {
var i, x, y;
// Initialize snow array
for (i = 0; i < 1920; ++i) {
snow[i] = ' ';
}
// Initialize art array
var artLines = $('input').value.split('\n');
if (!artLines[artLines.length - 1]) {
artLines.pop();
}
var artStart = 24 - artLines.length;
for (i = 0; i < artLines.length; ++i) {
y = artStart + i;
for (x = 0; x < artLines[i].length; ++x) {
art[80 * y + x] = artLines[i][x];
}
}
}
function dropSnow() {
for (var y = 24; y--;) for (var x = 0; x < 80; ++x) if (snow[80 * y + x] === '*') {
var drop = true;
// Check if this space is supposed to be filled in.
if (art[80 * y + x] === '*') {
// No drop unless there is a space to be filled
drop = false;
// Look for a remaining empty space.
for (var z = y + 1; z < 24; ++z) {
if (art[80 * z + x] === '*' && snow[80 * z + x] !== '*') {
drop = true;
break;
}
}
}
if (drop) {
snow[80 * y + x] = ' ';
snow[80 * (y + 1) + x] = '*';
}
}
}
function addSnow() {
for (var x = 0; x < 80; ++x) {
if (Math.random() < 0.1) {
snow[x] = '*';
}
}
}
function displaySnow() {
var text = '';
for (var x = 0; x < 24; ++x) {
text += snow.slice(80 * x, 80 * (x + 1)).join('') + '\n';
}
$('output').value = text;
}
function animate() {
dropSnow();
addSnow();
displaySnow();
}
initArrays();
for(var x = 0; x < 24; ++x) {
animate();
}
setInterval(animate, 67);