JSFiddle - React, Tailwind, and code Playground
by cincodenada
HTML
<html>
<head>
<title>GrassGrower</title>
</head>
<body>
<div id="field"></div>
Height: <input type="text" id="width" value="5"/><br/>
Width: <input type="text" id="height" value="5"/><br/>
Number of runs: <input type="text" id="numtimes" value="10"/><br/>
Chance of growth: 1/<input type="text" id="grasschance" value="8"/><br/>
<input type="button" id="btngenerate" value="Generate!"/>
<input type="button" id="btnrun" value="Run!"/>
</body>
</html>
CSS
td {
width: 10px;
height: 10px;
border: 1px solid #000000;
}
.type_0 { background-color: #CCCCCC; }
.type_1 { background-color: #996633; }
.type_2 { background-color: #006600; }
JavaScript
$(document).ready(function() {
generateField();
$('#btngenerate').click(generateField);
$('#btnrun').click(runSim);
});
function rotateCell() {
curtype = $(this).data('type');
newtype = (curtype + 1) % 3;
$(this).removeClass();
$(this).data('type', newtype);
$(this).addClass('type_' + newtype);
}
function generateField() {
$('#field').html('<table id="grid"></table>');
tblGrid = $('#field #grid').eq(0);
for(y=0;y < $('#height').val();y++) {
currow = $('<tr></tr>');
for(x=0;x < $('#width').val(); x++) {
td = $('<td class="type_0" id="cell_' + x + '_' + y + '"></td>').data("type",0);
currow.append(td);
}
tblGrid.append(currow);
}
$('#grid td').click(rotateCell);
}
function runSim() {
var initialVal = [];
var curFrame = [];
var nextFrame = [];
var initialDirt = 0;
var width = $('#width').val();
var height = $('#height').val();
for(y = 0; y < height; y++) {
initialVal[y] = [];
curFrame[y] = [];
nextFrame[y] = [];
for(x = 0; x < width; x++) {
initialVal[y][x] = $('#cell_' + x + '_' + y).data('type');
curFrame[y][x] = initialVal[y][x];
nextFrame[y][x] = null;
if(initialVal[y][x] == 1) {
initialDirt++;
}
}
}
grassChance = 1/($('#grasschance').val());
for(i=0;i<$('#numtimes').val();i++) {
numdirt = initialDirt;
while(numdirt > 0) {
for(y = 0; y < height; y++) {
for(x = 0; x < width; x++) {
if(curFrame[x][y] == 2) {
for (xadd = -1; xadd <=1; xadd++) {
for(yadd = -1; yadd <=1; yadd++) {
newx = x + xadd;
newy = y + yadd;
if(!(
(newx == x && newy ==...