Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div class="life_container">
  <div id="life_simulator"></div>
</div>
              
            
!

CSS

              
                .life_container{
  margin: 0 auto;
  width: 266px;
  padding: 8px;
  text-align: center;
  background: #222;
  color: white;
  box-sizing: border-box;
  border-radius: 4px;
}

#ls_input_groups_container {
    display: none;
    margin-bottom: 12px;
}

#ls_input_groups_container.show {
    display: block;
}

#ls_input_groups_container .ls_input_groups label {
    cursor: help;
}

#ls-controls-toggle {
    width: 100%;
    color: white;
    background: black;
    border-radius: 4px;
    margin-bottom: 8px;
    cursor: pointer;
}

.ls_input_groups{
    display: flex;
    justify-content: space-between;
    font-size: 9px;
    margin-top: 4px;
}

.ls_input_groups div {
    line-height: 16px;
    text-align: right;
    flex-grow: 1;
    padding-right: 6px;
}

.ls_input_groups label {
    line-height: 16px;
}

.ls_input_groups button {
    font-size: 12px;
    padding: 2px 4px;
    background: white;
    border: 1px solid silver;
    border-radius: 4px;
    outline: none;
}

.ls_input_groups button:hover {
    background: silver;
}

.ls_input_groups button:active {
    background: greenyellow;
}

#ls-data {
    border-bottom: 1px solid white;
    padding-bottom: 12px;
    margin-bottom: 12px;
}

#ls-data .ls_input_groups {
    font-size: 14px;
}

#ls-data .ls_input_groups div {
    padding-right: 0;
}

#ls-data #ls-legend {
    display: flex;
    justify-content: space-between;
    margin-top: 8px;
}

#ls-data #ls-legend span {
    padding: 0px 3px;
    border-radius: 2px;
    font-size: 9px;
    text-transform: uppercase;
    color:darkslateblue;
}
              
            
!

JS

              
                // html structure
const container = document.getElementById('life_simulator');
const canvas = document.createElement('canvas');
canvas.setAttribute("id", "ls-environment");
canvas.setAttribute("width", "250");
canvas.setAttribute("height", "250");

const data = document.createElement('div');
data.setAttribute("id", "ls-data");

const legend = document.createElement('div');
legend.setAttribute("id", "ls-legend");

const inputGroupsContainer = document.createElement('div');
inputGroupsContainer.setAttribute("id", "ls_input_groups_container");

const toggleControls = document.createElement('button');
toggleControls.setAttribute("id", "ls-controls-toggle");
toggleControls.textContent = 'TOGGLE CONTROLS';
toggleControls.addEventListener('click', () => {
    if(inputGroupsContainer.className.indexOf("show") === -1){
        inputGroupsContainer.className += ' show';
    } else {
        inputGroupsContainer.className = inputGroupsContainer.className.replace(' show', '');
    }
});

// appending
container.appendChild(canvas);
container.appendChild(data);
container.appendChild(toggleControls);
container.appendChild(inputGroupsContainer);

const ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = false;
ctx.mozImageSmoothingEnabled = false;

const colors = {
    blank:      [0,0,0],
    born:       [0,255,255],
    growing:    [255,0,255],
    mature:     [255,255,0],
    elder:      [127,127,255],
    disease:    [0,255,0],
};

const settings = {
    width: 250,
    height: 250,
    initialPopulationNumber: 12000,
    birthProbability: 0.25,
    maximumProgeny: 4,
    maturityAge: 480,
    deathAge: 760,
    agingSpeed: 1,
    diseaseRate: 0.25,
    diseaseMortality: 5,
};

const settingInputs = {
    width: [100, 250, 10, 'width', 'Canvas size: width.'],
    height: [100, 250, 10, 'height', 'Canvas size: height.'],
    initialPopulationNumber: [1000, 100000, 500, 'initial pop', 'Initial population.'],
    birthProbability: [0, 1, 0.05, 'birth', 'Birth: probability of procreation.', colors.born],
    maximumProgeny: [1, 32, 1, 'progeny', 'Birth: maximum amount of children.'],
    maturityAge: [10, 2000, 10, 'maturity', 'Birth: age of maturity for procreation. In Age cycles.', colors.mature],
    deathAge: [10, 2000, 10, 'death', 'Maximum lifespan. In Age cycles.', colors.elder],
    agingSpeed: [1, 100, 1, 'aging speed', 'Speed of Age cycles.', colors.growing],
    diseaseRate: [0, 1, 0.05, 'disease', 'Disease: probability of getting sick.', colors.disease],
    diseaseMortality: [5, 500, 5, 'mortality', 'Disease: life shortening power. In Age cycles.'],
};

const requireRestart = ['width', 'height', 'initialPopulationNumber'];

const dataMaker = (label) => {
    const cnt = document.createElement('div');
    cnt.setAttribute('class', 'ls_input_groups');

    const lbl = document.createElement('label');
    lbl.textContent = label;

    const val = document.createElement('div');

    cnt.appendChild(lbl);
    cnt.appendChild(val);

    data.appendChild(cnt);

    return val;
};

const dataSpans = {
    maxPopulation: dataMaker('Max Population'),
    population: dataMaker('Population'),
    age: dataMaker('Age'),
    totalBirths: dataMaker('Total births'),
    frameRate: dataMaker('Frame rate'),
};

Object.keys(colors).forEach((e) => {
    const col = document.createElement('span');
    col.setAttribute('style', `background: rgb(${colors[e].join(',')})`);
    col.textContent = e;

    legend.appendChild(col);
});

data.appendChild(legend);

let imgData = ctx.createImageData(settings.width, settings.height);
let initialPopulation = Array(settings.width * settings.height).fill(null);
let availableSpace = initialPopulation.length;
let totalBirths = 0;
let age = 0;

let started;
let paused;
let timeout;

const lookupTable = [];

/* inputs */
Object.keys(settings).forEach(el => {
    const input = document.createElement('input');
    input.setAttribute('id', el);
    input.setAttribute('type', 'range');
    input.setAttribute('min', settingInputs[el][0]);
    input.setAttribute('max', settingInputs[el][1]);
    input.setAttribute('step', settingInputs[el][2]);
    input.value = settings[el];

    const label = document.createElement('label');
    label.textContent = settingInputs[el][3];
    label.setAttribute('title', settingInputs[el][4]);
    if(settingInputs[el][5]){
        label.setAttribute('style', `color: rgb(${settingInputs[el][5].join(',')})`);
    }

    const span = document.createElement('div');
    span.setAttribute('id', `${el}Span`);
    span.textContent = settings[el];

    input.addEventListener('input', (e) => {
        settings[el] = e.srcElement.value;
        span.textContent = settings[el];

        if(requireRestart.includes(el)){
            restart();
        }
    });

    const inputContainer = document.createElement('div');
    inputContainer.setAttribute('class', 'ls_input_groups');

    inputContainer.appendChild(label);
    inputContainer.appendChild(span);
    inputContainer.appendChild(input);

    inputGroupsContainer.appendChild(inputContainer);
});

const startButton = document.createElement('button');
startButton.setAttribute('id', 'start');
startButton.textContent = 'START';

startButton.addEventListener('click', () => {
    clearTimeout(timeout);
    started = true;

    if( paused ) {
        paused = false;
        repeater();
    } else {
        restart();
    }
});

const pauseButton = document.createElement('button');
pauseButton.setAttribute('id', 'pause');
pauseButton.textContent = 'PAUSE';

pauseButton.addEventListener('click', () => {
    paused = true;
    started = false;
});

const stopButton = document.createElement('button');
stopButton.setAttribute('id', 'stop');
stopButton.textContent = 'STOP';

stopButton.addEventListener('click', () => {
    paused = false;
    started = false;
    clearTimeout(timeout);
});

const inputContainer = document.createElement('div');
inputContainer.setAttribute('class', 'ls_input_groups');

inputContainer.appendChild(startButton);
inputContainer.appendChild(pauseButton);
inputContainer.appendChild(stopButton);

container.appendChild(inputContainer);
/* inputs */

/* LOGIC */
const imageMaker = (pop) => {
    const t0 = performance.now();

    age += parseInt(settings.agingSpeed);

    const emptyIndexes = [];
    for(let f=0; f<availableSpace; f++){
        if(!pop[f]){ emptyIndexes.push(f); }
    }

    emptyIndexes.sort(() => (0.5 - lookup()));

    for(let x=0; x<availableSpace; x++){
        let element = colors.blank;

        if(pop[x] !== null){
            pop[x].age += parseInt(settings.agingSpeed);

            if(pop[x].age >= pop[x].death){
                emptyIndexes.push(x);
                pop[x] = null;
            } else if (pop[x].age >= pop[x].elder){
                pop[x].color = colors.elder;
            } else {
                if(pop[x].age >= pop[x].born){
                    pop[x].color = colors.growing;
                }

                if (pop[x].age >= pop[x].maturity){
                    pop[x].color = colors.mature;

                    if(lookup() > 1 - settings.birthProbability && emptyIndexes.length > 0){
                        pop[x].children++;
                        if(pop[x].children < pop[x].maxChildren){
                            pop[emptyIndexes.pop()] = newBorn(pop[x].diseased);
                        }
                    }
                }
            }

            if(pop[x] && pop[x].diseased){
                pop[x].color = colors.disease;
                pop[x].death -= settings.diseaseMortality;
            }

            element = pop[x] ? pop[x].color : colors.blank;
        }

        let i = x * 4;
        imgData.data[i] = element[0];
        imgData.data[i+1] = element[1];
        imgData.data[i+2] = element[2];
        imgData.data[i+3] = 255;
    }

    const t1 = performance.now();

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.putImageData(imgData, 0, 0);

    dataSpans.population.textContent = pop.filter(e => e !== null).length;
    dataSpans.frameRate.textContent = (t1 - t0).toFixed(2) + 'ms';
    dataSpans.age.textContent = age;
    dataSpans.totalBirths.textContent = totalBirths;

    if(pop.filter(e => e !== null).length === 0){
        started = false;
        data.setAttribute('class', 'red');
    }
};

const newBorn = (hasDisease = false) => {
    totalBirths++;
    const maturity = parseInt(lookup() * settings.maturityAge);
    const death = parseInt(lookup() * settings.deathAge);
    const maxChildren = parseInt(lookup() * settings.maximumProgeny);
    const elder = maturity + (death - maturity) * lookup();

    return {
        age: 0,
        born: maturity * 0.25,
        maturity,
        elder,
        death,
        children: 0,
        maxChildren,
        color: colors.born,
        diseased: hasDisease ? hasDisease : lookup() > (1 - settings.diseaseRate),
    }
};

let random = 0;

const lookup = () => {
    random++;
    if(random >= lookupTable.length){
        random = 0;
    }

    return lookupTable[random];
};

const repeater = () => {
    imageMaker(initialPopulation);

    if(started){
        timeout = requestAnimationFrame(repeater);
    }
};

const restart = () => {
    data.setAttribute('class', '');
    totalBirths = 0;
    age = 0;

    imgData = ctx.createImageData(settings.width, settings.height);

    initialPopulation = Array(settings.width * settings.height).fill(null);

    availableSpace = initialPopulation.length;

    dataSpans.maxPopulation.textContent = availableSpace;

    for(let e = 0; e < availableSpace; e++){
        lookupTable.push(Math.random());

        if(e < settings.initialPopulationNumber){
            initialPopulation[e] = newBorn();
        }
    }

    initialPopulation.sort(() => (0.5 - lookup()));

    repeater();
};

restart();
/* LOGIC */
              
            
!
999px

Console