game: extract getDistance

This commit is contained in:
He4eT 2025-06-11 04:55:31 +02:00
commit d96e0861c0

25
game.js
View file

@ -156,7 +156,7 @@ function gameover() {
/* Gameplay */ /* Gameplay */
function gameScreen() { function gameScreen() {
checkColisions() checkCollisions()
spawnEnemies() spawnEnemies()
handleMoves() handleMoves()
@ -395,7 +395,7 @@ function spawnEnemies() {
do { do {
x = rnd(arena.bounds.left + b, arena.bounds.right - b) x = rnd(arena.bounds.left + b, arena.bounds.right - b)
y = rnd(arena.bounds.top + b, arena.bounds.bottom - 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) } while (distance < minDistance)
return { x, y } return { x, y }
@ -451,18 +451,11 @@ function destroyEnemiesByLetter(letter) {
enemies = enemies.filter((enemy) => enemy.letter !== letter) enemies = enemies.filter((enemy) => enemy.letter !== letter)
} }
function checkColisions() { function checkCollisions() {
if ( const collide = (enemy) =>
enemies getDistance(player.position, enemy.positions[0]) < enemy.dangerZone
.map((enemy) => [
enemy, if (enemies.some(collide)) {
Math.hypot(
player.position.x - enemy.positions[0].x,
player.position.y - enemy.positions[0].y,
),
])
.some(([enemy, distance]) => distance < enemy.dangerZone)
) {
gameover() gameover()
} }
} }
@ -592,6 +585,10 @@ function rnd(from, to) {
return Math.floor(Math.random() * (to - from + 1)) + from 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) { function getDirection(from, to) {
const dx = to.x - from.x const dx = to.x - from.x
const dy = to.y - from.y const dy = to.y - from.y