JSFiddle - React, Tailwind, and code Playground

by jcubed111

HTML

<canvas id="main"></canvas>
<div id="sum">0</div>

CSS

body{
    margin: 0;
    overflow: hidden;
    background: #000;
}

#sum{
    position: absolute;
    top: 0;
    left: 0;
    background: #000;
    color: #bbb;
}

JavaScript

function randInt(min, max) {
	return Math.floor(Math.random() * (max - min) + min);
}
function randChoice(arr) {
	return arr[randInt(0, arr.length)];
}
Array.prototype.sum = function() { return this.reduce((a, b) => a + b, 0); };
Array.prototype.average = function() { return this.sum() / this.length; };


const TYPES = {
	STONE: 'STONE',
    DIRT: 'DIRT',
};

const PLANT_MAX = 40;
const PLANT_STRONG = 20;
const PLANT_FLOWER_GROW = 35;
const PLANT_MIN = 10;
const SCALE = 16;

const flowerColors = ['#f00', '#d11fa2', '#ee9522'];

class Cell{
	constructor(x, y, type, water, plant, flowerPower, flowerType) {
    	this.x = x;
        this.y = y;
        this.type = type;
        this.water = water;
        this.plant = plant;
        this.flowerPower = flowerPower;
        this.flowerType = flowerType;
    }
    
    canGrow() {
    	return this.plant > 0
        	&& this.plant < PLANT_MAX
        	&& this.water < 4
            && this.type == TYPES.DIRT;
    }
    
    canFeed() {
    	if(this.water >= 8) return 2;
        if(this.water >= 4 || this.plant >= PLANT_MIN) return 1;
        return 0;
    }
    
    nextState(adjacents) {
    	let nextWater = this.water;
        let nextPlant = this.plant;
        
        // plant grows from water, or strong plant
        if(this.canGrow()) {
        	nextPlant += adjacents.map(a => a.canFeed()).sum();
        }
        
        // plant shrink from feeding other plants
        if(this.canFeed()) {
        	if(this.water >= 8) {
            	nextWater -= 2 * adjacents.filter(a => a.canGrow()).length;
            }else if(this.water >= 4) {
            	nextWater -= adjacents.filter(a => a.canGrow()).length;
            }else{
            	nextPlant -= adjacents.filter(a => a.canGrow()).length;
            }
        }
        
        // plant spawns from adjacent strong plant
        if(nextPlant == 0 && this.water <= 4 && this.type == TYPES.DIRT && adjacents.some(a => a.plant >= PLANT_STRONG)) {
        	nextPlant = 1;
...