From d96e0861c03130ee1952cb42e3ab3a346e0fd15e Mon Sep 17 00:00:00 2001 From: He4eT Date: Wed, 11 Jun 2025 04:55:31 +0200 Subject: [PATCH] game: extract getDistance --- game.js | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/game.js b/game.js index acfc615..0d6b930 100644 --- a/game.js +++ b/game.js @@ -156,7 +156,7 @@ function gameover() { /* Gameplay */ function gameScreen() { - checkColisions() + checkCollisions() spawnEnemies() handleMoves() @@ -395,7 +395,7 @@ function spawnEnemies() { do { x = rnd(arena.bounds.left + b, arena.bounds.right - b) y = rnd(arena.bounds.top + b, arena.bounds.bottom - b) - distance = Math.hypot(x - player.position.x, y - player.position.y) + distance = getDistance({ x, y }, player.position) } while (distance < minDistance) return { x, y } @@ -451,18 +451,11 @@ function destroyEnemiesByLetter(letter) { enemies = enemies.filter((enemy) => enemy.letter !== letter) } -function checkColisions() { - if ( - enemies - .map((enemy) => [ - enemy, - Math.hypot( - player.position.x - enemy.positions[0].x, - player.position.y - enemy.positions[0].y, - ), - ]) - .some(([enemy, distance]) => distance < enemy.dangerZone) - ) { +function checkCollisions() { + const collide = (enemy) => + getDistance(player.position, enemy.positions[0]) < enemy.dangerZone + + if (enemies.some(collide)) { gameover() } } @@ -592,6 +585,10 @@ function rnd(from, to) { return Math.floor(Math.random() * (to - from + 1)) + from } +function getDistance(from, to) { + return Math.hypot(from.x - to.x, from.y - to.y) +} + function getDirection(from, to) { const dx = to.x - from.x const dy = to.y - from.y