JSFiddle - React, Tailwind, and code Playground
by jcubed111
HTML
<canvas id="main" width=500 height=500></canvas>
<div id="count">0</div>
CSS
body{
background: #222;
}
#count{
color: #ddd;
}
JavaScript
class Cell{
constructor(x, y, type='G') {
this.x = x;
this.y = y;
this.type = type;
this.typeString = '';
}
}
class Terrain{
constructor(width, height) {
this.width = width;
this.height = height;
this.cells = Array(width).fill(0).map((_, x) => Array(height).fill(0).map((_, y) => new Cell(x, y)));
}
forEach(cb) {
this.cells.forEach(col => col.forEach(c => cb(c, [c.x, c.y])));
}
getTypeAt(x, y) {
if(x >= 0 && x < this.width && y >= 0 && y < this.height) {
return this.cells[x][y].type;
}else{
return 'G';
}
}
}
const t = new Terrain(100, 100);
// CGMR
const typeTransitions = {
// G_GGGG: { M: 0.00001, R: 0.00001, },
G_GGGG: { R: 0.00001, },
G_GGGM: { M: 0.5, },
G_GGMM: { M: 0.2, },
G_GMMM: { M: 0.2, },
G_MMMM: { M: 1.0, },
M_GGGM: { G: 0.75, },
M_MMMM: { G: 0.001, },
G_GGGR: {R: 0.1},
R_GGGR: {G: 0.3},
//R_GRRR: {G: 1.0},
};
function step() {
t.forEach((c, [x, y]) => {
c.typeString = c.type + '_' + [
t.getTypeAt(x + 1, y),
t.getTypeAt(x - 1, y),
t.getTypeAt(x, y + 1),
t.getTypeAt(x, y - 1),
].sort().join('');
});
t.forEach((c, [x, y]) => {
const transition = typeTransitions[c.typeString] || {};
let p = Math.random();
for(const [key, value] of Object.entries(transition)) {
if(value > p) {
c.type = key;
return;
}else{
p -= value;
}
}
});
}
function render() {
const s = 5;
const ctx = document.getElementById('main').getContext('2d');
ctx.clearRect(0, 0, t.width*s, t.height*s);
t.forEach((c, [x, y]) => {
ctx.fillStyle = ({
G: '#3b3',
R: '#36f',
M: '#868',
C: '#c96',
})[c.type];
ctx.fillRect(s * x, s * y, s, s);
});
}
async function...