From 43beb60e21b1d52cc708a0caa72b7e9c412d433f Mon Sep 17 00:00:00 2001 From: prescientmoon Date: Mon, 4 Mar 2024 16:49:39 +0100 Subject: [PATCH] javascript(clever-dots): Make rendering loop async Signed-off-by: prescientmoon --- javascript/clever-dots/game.js | 89 +++++++++++++++++++++------------- 1 file changed, 55 insertions(+), 34 deletions(-) diff --git a/javascript/clever-dots/game.js b/javascript/clever-dots/game.js index 8e8c2af..a5241cf 100644 --- a/javascript/clever-dots/game.js +++ b/javascript/clever-dots/game.js @@ -1,40 +1,61 @@ -function game(){ - this.size = [500,500]; - - this.clear = function(){ - setTimeout(function(){ - var c = document.getElementById("can"); - var ctx = c.getContext("2d"); - ctx.fillStyle="#000000"; - ctx.fillRect(0,0,1000,1000); - //console.log("clearing"); - },1); - } - - this.draw = function(x,y){ - setTimeout(function(){ - var c = document.getElementById("can"); - var ctx = c.getContext("2d"); - ctx.fillStyle="#FFFFFF"; - ctx.fillRect(x,y,1,1); - //console.log(y+"drawing"+x); - },1); - //console.log("finished drawing"); - } +function game() { + this.size = [500, 500]; + + this.clear = function () { + var c = document.getElementById("can"); + var ctx = c.getContext("2d"); + ctx.fillStyle = "#000000"; + ctx.fillRect(0, 0, 1000, 1000); + //console.log("clearing"); + }; + + this.draw = function (x, y) { + var c = document.getElementById("can"); + var ctx = c.getContext("2d"); + ctx.fillStyle = "#FFFFFF"; + ctx.fillRect(x, y, 1, 1); + //console.log(y+"drawing"+x); + //console.log("finished drawing"); + }; } var a = new game(); a.clear(); var b = new population(a); b.reset(); b.create_population(); -for (var k = 0;k < 20;k++){ - a.clear(); - console.log("thinking"); - for (var i = 0;i < 500;i++){ - for (var j = 0;j < b.Population.length;j++){ - b.think(b.Population[j]); - a.draw(b.Population[j].x,b.Population[j].y); - } - } - b.evolve(); -} \ No newline at end of file + +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(); + console.log(`thinking: ${k}`); + for (let i = 0; i < 500; i++) { + if (i % iterationsPerFrame === 0) await redraw(); + for (let j = 0; j < b.Population.length; j++) { + b.think(b.Population[j]); + a.draw(b.Population[j].x, b.Population[j].y); + } + } + + b.evolve(); + } +} + +main(); +