From abcde26ef403505efd745b6f5e16f2a76fa99c68 Mon Sep 17 00:00:00 2001 From: Robert Bendun Date: Tue, 27 Apr 2021 10:05:47 +0200 Subject: [PATCH] Forgot to add costMap to commit xD --- src/logic/costMap.js | 78 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 src/logic/costMap.js diff --git a/src/logic/costMap.js b/src/logic/costMap.js new file mode 100644 index 0000000..5419f3e --- /dev/null +++ b/src/logic/costMap.js @@ -0,0 +1,78 @@ +const MaxCostPoints = 3; +const MaxCostSpreadRadius = 5; + +class CostMap { + static instance + + constructor() { + CostMap.instance = this; + this.compute() + } + + getCostAt(x, y) { + return this.values[y * 20 + x] + } + + compute() { + this.values = [...Array(20 * 9)].map(_ => 0); + + const {floor, random, PI, sin, cos} = Math + for (let i = 0; i < MaxCostPoints; ++i) { + const x = floor(random() * 20); + const y = floor(random() * 9); + + this.values[y * 20 + x] = 1; + + for (let theta = 0; theta < PI * 2; theta += 0.1) { + for (let rbase = 1; rbase < MaxCostSpreadRadius; ++rbase) { + const r = Math.cbrt(Math.random()) * rbase; + const cx = floor(cos(theta) * r + (x + 0.5)); + const cy = floor(sin(theta) * r + (y + 0.5)); + + if (cx >= 0 && cx <= 20 && cy >= 0 && cy <= 9 && this.values[cy * 20 + cx] == 0) + this.values[cy * 20 + cx] = 1 - (rbase / MaxCostSpreadRadius); + } + } + } + } +} + +class CostMapVisualisation { + static instance + + constructor(canvas) { + this.canvas = canvas + this.ctx = canvas.getContext('2d'); + canvas.width = 2000 + canvas.height = 900 + + CostMapVisualisation.instance = this + + document.addEventListener('keydown', ({ key }) => { + if (key !== 'c') + return + + if (this.hasBeenUpdated) { + this.ctx.clearRect(0, 0, 2000, 900); + } else { + this.update(); + } + + this.hasBeenUpdated = !this.hasBeenUpdated + }) + } + + update() { + CostMap.instance.values.forEach((cost, i) => { + const y = Math.floor(i / 20) * 100; + const x = (i % 20) * 100; + + let color = Math.floor((cost * 255)).toString(16) + if (color.length == 1) + color = "0" + color + + this.ctx.fillStyle = '#' + color + color + color; + this.ctx.fillRect(x, y, 100, 100) + }) + } +}