1
Fork 0

javascript(clever-dots): Make rendering loop async

Signed-off-by: prescientmoon <git@moonythm.dev>
This commit is contained in:
prescientmoon 2024-03-04 16:49:39 +01:00
parent 9bdc46e524
commit 43beb60e21
Signed by: prescientmoon
SSH key fingerprint: SHA256:UUF9JT2s8Xfyv76b8ZuVL7XrmimH4o49p4b+iexbVH4

View file

@ -2,39 +2,60 @@ function game(){
this.size = [500, 500]; this.size = [500, 500];
this.clear = function () { this.clear = function () {
setTimeout(function(){
var c = document.getElementById("can"); var c = document.getElementById("can");
var ctx = c.getContext("2d"); var ctx = c.getContext("2d");
ctx.fillStyle = "#000000"; ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, 1000, 1000); ctx.fillRect(0, 0, 1000, 1000);
//console.log("clearing"); //console.log("clearing");
},1); };
}
this.draw = function (x, y) { this.draw = function (x, y) {
setTimeout(function(){
var c = document.getElementById("can"); var c = document.getElementById("can");
var ctx = c.getContext("2d"); var ctx = c.getContext("2d");
ctx.fillStyle = "#FFFFFF"; ctx.fillStyle = "#FFFFFF";
ctx.fillRect(x, y, 1, 1); ctx.fillRect(x, y, 1, 1);
//console.log(y+"drawing"+x); //console.log(y+"drawing"+x);
},1);
//console.log("finished drawing"); //console.log("finished drawing");
} };
} }
var a = new game(); var a = new game();
a.clear(); a.clear();
var b = new population(a); var b = new population(a);
b.reset(); b.reset();
b.create_population(); b.create_population();
for (var k = 0;k < 20;k++){
function redraw() {
let done = false;
let callback = null;
requestAnimationFrame(() => {
done = true;
if (callback !== null) callback();
});
return new Promise((res) => {
if (done) res();
else callback = () => res();
});
}
const iterationsPerFrame = 10;
async function main() {
for (let k = 0; k < 1000; k++) {
await redraw();
a.clear(); a.clear();
console.log("thinking"); console.log(`thinking: ${k}`);
for (var i = 0;i < 500;i++){ for (let i = 0; i < 500; i++) {
for (var j = 0;j < b.Population.length;j++){ if (i % iterationsPerFrame === 0) await redraw();
for (let j = 0; j < b.Population.length; j++) {
b.think(b.Population[j]); b.think(b.Population[j]);
a.draw(b.Population[j].x, b.Population[j].y); a.draw(b.Population[j].x, b.Population[j].y);
} }
} }
b.evolve(); b.evolve();
} }
}
main();