From 16bc58065d609a457016edce545eded2bd27682a Mon Sep 17 00:00:00 2001 From: Paolo Brasolin <paolo.brasolin@eurac.edu> Date: Tue, 5 Apr 2022 18:03:02 +0200 Subject: [PATCH] feat: #fe smarter box positioning --- frontend/src/js/clue.ts | 48 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 44 insertions(+), 4 deletions(-) diff --git a/frontend/src/js/clue.ts b/frontend/src/js/clue.ts index d855393..21509a3 100644 --- a/frontend/src/js/clue.ts +++ b/frontend/src/js/clue.ts @@ -70,14 +70,54 @@ class Clue extends Phaser.GameObjects.Sprite { setPositionForDrop() { const bounds = this.body.customBoundsRectangle; - const x = - bounds.left + - this.displayWidth * 0.5 + - Math.random() * (bounds.width - this.displayWidth); + const x = this.findBestDropPosition(bounds, this.scene.cluesGroup.children); + // const x = this.findRandDropPosition(bounds); const y = bounds.top + this.displayHeight * 0.5; this.setPosition(x, y); } + findRandDropPosition(bounds: Phaser.Geom.Rectangle) { + return ( + bounds.left + + this.displayWidth * 0.5 + + Math.random() * (bounds.width - this.displayWidth) + ); + } + + findBestDropPosition( + bounds: Phaser.Geom.Rectangle, + siblings: Phaser.Structs.Set<Phaser.GameObjects.GameObject>, + pad = 10, + ) { + const minX = Math.ceil(bounds.left); + const maxX = Math.floor(bounds.right); + const xCount = maxX - minX + 1; + const xScores = Array(xCount).fill(0); + + xScores.forEach((_, i, xs) => { + (siblings as Phaser.Structs.Set<Clue>).each((clue) => { + if (clue == this) return; + const clueBounds = clue.getBounds(); + const x = i + minX; + let intersect = true; + intersect &&= clueBounds.left - pad < x; + intersect &&= x < clueBounds.right + pad; + xs[i] += intersect; + }); + }); + + const boxWidth = Math.ceil(this.displayWidth); + const boxPosScores = Array(xCount - boxWidth).fill(0); + + boxPosScores.forEach((_, i, ps) => { + ps[i] = xScores.slice(i, i + boxWidth).reduce((a, b) => a + b, 0); + }); + + const bestBoxPos = boxPosScores.indexOf(Math.min(...boxPosScores)); + + return bounds.left + 0.5 * this.displayWidth + bestBoxPos; + } + delete() { this.fadeOut(() => { this.texture.destroy(); -- GitLab