Forgot to add costMap to commit xD

This commit is contained in:
Robert Bendun 2021-04-27 10:05:47 +02:00
parent e824d238db
commit abcde26ef4

78
src/logic/costMap.js Normal file
View File

@ -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)
})
}
}