game: extract enemyBehaviors

This commit is contained in:
He4eT 2025-06-06 23:17:57 +02:00
commit bcc0e4b0b0

34
game.js
View file

@ -78,16 +78,12 @@ let player = {
}, },
} }
/**
* @typedef {'point' | 'fidget' | 'bounce' | 'zombie'} EnemyType
*/
/** @type EnemyType[] */
const enemyTypes = ['point', 'fidget', 'bounce', 'zombie'] const enemyTypes = ['point', 'fidget', 'bounce', 'zombie']
/** /**
* @typedef {{ * @typedef {{
* letter: string, * letter: string,
* type: EnemyType, * type: keyof typeof enemyBehaviors,
* dangerZone: number, * dangerZone: number,
* positions: Point[], * positions: Point[],
* }} Enemy * }} Enemy
@ -221,7 +217,9 @@ function spawn() {
const enemyCount = 1 + Math.floor(arena.wave / 2) const enemyCount = 1 + Math.floor(arena.wave / 2)
const getType = (wave) => { const getType = (wave) => {
if (wave < 2) return 'point' if (wave <= 2) return 'point'
const enemyTypes = Object.keys(enemyBehaviors)
return enemyTypes[rnd(0, enemyTypes.length - 1)] return enemyTypes[rnd(0, enemyTypes.length - 1)]
} }
@ -258,25 +256,23 @@ function spawn() {
effects.unshift({ effects.unshift({
type: 'detection', type: 'detection',
to: enemy.positions[0], to: enemy.positions[0],
frames: Array(5).fill(4), frames: Array(10).fill(4),
}) })
}) })
} }
function moveEnemies() { const enemyBehaviors = {
enemies.forEach((enemy) =>
({
point: () => {}, point: () => {},
fidget: () => {}, fidget: (enemy) => {},
bounce: () => { bounce: (enemy) => {
const speed = 1 const speed = 1
const current = enemy.positions[0] const current = enemy.positions[0]
const previous = enemy.positions[1] const previous = enemy.positions[1]
let d = getDirection(previous, current) const d = getDirection(previous, current)
dx = d.x * speed let dx = d.x * speed
dy = d.y * speed let dy = d.y * speed
let newX = current.x + dx let newX = current.x + dx
let newY = current.y + dy let newY = current.y + dy
@ -296,7 +292,7 @@ function moveEnemies() {
{ x: current.x, y: current.y }, { x: current.x, y: current.y },
] ]
}, },
zombie: () => { zombie: (enemy) => {
const speed = 0.5 const speed = 0.5
const current = enemy.positions[0] const current = enemy.positions[0]
const target = player.position const target = player.position
@ -310,8 +306,10 @@ function moveEnemies() {
}, },
] ]
}, },
})[enemy.type](), }
)
function moveEnemies() {
enemies.forEach((enemy) => enemyBehaviors[enemy.type](enemy))
} }
function checkColisions() { function checkColisions() {