about summary refs log tree commit diff stats
path: root/html/plains/enemies.js
blob: 77f5245078592b91a04f0123cbe8f95baa07befd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
// ============= Enemy System =============
const blueShades = [
    'rgb(0, 0, 255)',    // Bright blue
    'rgb(0, 0, 200)',    // Medium blue
    'rgb(0, 0, 150)',    // Darker blue
    'rgb(0, 0, 100)',    // Even darker blue
    'rgb(0, 0, 50)'      // Very dark blue
];

const generateEnemies = (villagers, collisionMap) => {
    const enemies = [];
    const gridSize = CONFIG.display.grid.size;
    const occupiedCells = new Set([...collisionMap.keys()]);
    
    villagers.forEach(villager => {
        if (villager.status === 'rescued') return;
        
        // Generate 2-5 enemies per villager
        const numEnemies = 2 + Math.floor(Math.random() * 4);
        
        for (let i = 0; i < numEnemies; i++) {
            // Place within 2-3 cells of villager
            const radius = 2 + Math.floor(Math.random());
            const angle = Math.random() * Math.PI * 2;
            
            const cellX = villager.cellX + Math.floor(Math.cos(angle) * radius);
            const cellY = villager.cellY + Math.floor(Math.sin(angle) * radius);
            const cellKey = `${cellX},${cellY}`;
            
            // Skip if cell is occupied
            if (occupiedCells.has(cellKey)) {
                continue;
            }
            
            // Generate random color between orange and dark red
            const red = 150 + Math.floor(Math.random() * 105);  // 150-255
            const green = Math.floor(Math.random() * 100);      // 0-100
            const blue = 0;
            
            enemies.push({
                x: (cellX * gridSize) + (gridSize / 2),
                y: (cellY * gridSize) + (gridSize / 2),
                color: `rgb(${red}, ${green}, ${blue})`,
                size: CONFIG.enemies.size.min + Math.random() * (CONFIG.enemies.size.max - CONFIG.enemies.size.min),
                targetVillager: villager,
                patrolAngle: Math.random() * Math.PI * 2,
                isChasing: false,
                hp: 2 + Math.floor(Math.random() * 9),
                stunned: false,
                stunEndTime: 0,
                attacking: false,
                attackCooldown: false,
                attackCooldownUntil: 0,
                knockback: {
                    active: false,
                    startX: 0,
                    startY: 0,
                    targetX: 0,
                    targetY: 0,
                    startTime: 0,
                    duration: 300
                }
            });
            
            occupiedCells.add(cellKey);
        }
    });
    
    return enemies;
};

const handleEnemyDamage = (enemy, damage, knockbackForce = 0, angle = 0) => {
    const gridSize = CONFIG.display.grid.size;
    enemy.hp -= damage;
    
    // Apply stun when hit
    enemy.stunned = true;
    enemy.stunEndTime = animationTime + 500; // 500ms stun duration
    
    // Apply knockback if there's a force
    if (knockbackForce > 0) {
        const knockbackDistance = gridSize * 0.5; // Half grid cell knockback
        enemy.knockback = {
            active: true,
            startX: enemy.x,
            startY: enemy.y,
            targetX: enemy.x + Math.cos(angle) * knockbackDistance,
            targetY: enemy.y + Math.sin(angle) * knockbackDistance,
            startTime: animationTime,
            duration: 300
        };
    }
    
    if (damage > 0 && enemy.hp <= 0) {
        // Create death particles
        const numParticles = 15 + Math.floor(Math.random() * 10);
        for (let i = 0; i < numParticles; i++) {
            const particleAngle = (i / numParticles) * Math.PI * 2;
            const speed = 2 + Math.random() * 3;
            state.particles.push({
                x: enemy.x,
                y: enemy.y,
                dx: Math.cos(particleAngle) * speed,
                dy: Math.sin(particleAngle) * speed,
                size: enemy.size * (0.1 + Math.random() * 0.2),
                color: enemy.color,
                lifetime: 1000,
                createdAt: animationTime
            });
        }

        // Generate diamonds when enemy is defeated
        const diamondCount = Math.floor(Math.random() * 5);
        for (let i = 0; i < diamondCount; i++) {
            state.diamonds.push({
                x: enemy.x + (Math.random() - 0.5) * 20,
                y: enemy.y + (Math.random() - 0.5) * 20,
                size: 6,
                collected: false
            });
        }
    }
    
    return damage > 0 && enemy.hp <= 0;
};

// Add this new function to find nearest lost villager
const findNearestLostVillager = (enemyX, enemyY, villagers) => {
    let nearestVillager = null;
    let shortestDistance = Infinity;
    
    villagers.forEach(villager => {
        if (villager.status === 'lost') {
            const dx = villager.x - enemyX;
            const dy = villager.y - enemyY;
            const distance = Math.sqrt(dx * dx + dy * dy);
            
            if (distance < shortestDistance) {
                shortestDistance = distance;
                nearestVillager = villager;
            }
        }
    });
    
    return nearestVillager;
};

const updateEnemies = (enemies, deltaTime) => {
    const gridSize = CONFIG.display.grid.size;
    const aggroRange = gridSize * CONFIG.enemies.chase.range;

    return enemies.filter(enemy => enemy.hp > 0).map(enemy => {
        const baseSpeed = CONFIG.enemies.patrol.speed.base * deltaTime / 1000;

        // Handle knockback animation
        if (enemy.knockback.active) {
            const progress = (animationTime - enemy.knockback.startTime) / enemy.knockback.duration;
            
            if (progress >= 1) {
                enemy.knockback.active = false;
                enemy.x = enemy.knockback.targetX;
                enemy.y = enemy.knockback.targetY;
                
                // Calculate distance from villager after knockback
                const dvx = enemy.x - enemy.targetVillager.x;
                const dvy = enemy.y - enemy.targetVillager.y;
                const distanceToVillager = Math.sqrt(dvx * dvx + dvy * dvy);
                
                // If too far from villager, set returning state
                if (distanceToVillager > gridSize * 3) {
                    return {
                        ...enemy,
                        x: enemy.x,
                        y: enemy.y,
                        isChasing: false,
                        isReturning: true
                    };
                }
            } else {
                // Smooth easing function (ease-out)
                const t = 1 - Math.pow(1 - progress, 3);
                enemy.x = enemy.knockback.startX + (enemy.knockback.targetX - enemy.knockback.startX) * t;
                enemy.y = enemy.knockback.startY + (enemy.knockback.targetY - enemy.knockback.startY) * t;
            }
            
            return {
                ...enemy,
                x: enemy.x,
                y: enemy.y,
                isChasing: false
            };
        }
        
        // If enemy is returning to villager
        if (enemy.isReturning) {
            const dvx = enemy.targetVillager.x - enemy.x;
            const dvy = enemy.targetVillager.y - enemy.y;
            const distanceToVillager = Math.sqrt(dvx * dvx + dvy * dvy);
            
            // If back within range, resume normal behavior
            if (distanceToVillager <= gridSize * 2) {
                enemy.isReturning = false;
            } else {
                // Move towards villager
                const angle = Math.atan2(dvy, dvx);
                const returnSpeed = baseSpeed * CONFIG.enemies.return.speedMultiplier;
                
                return {
                    ...enemy,
                    x: enemy.x + Math.cos(angle) * returnSpeed,
                    y: enemy.y + Math.sin(angle) * returnSpeed,
                    isChasing: false,
                    isReturning: true
                };
            }
        }
        
        // Check if stun has worn off
        if (enemy.stunned && animationTime >= enemy.stunEndTime) {
            enemy.stunned = false;
        }
        
        // Check if current target villager was rescued
        if (enemy.targetVillager.status === 'rescued') {
            // Find new target villager
            const newTarget = findNearestLostVillager(enemy.x, enemy.y, state.villagers);
            
            if (newTarget) {
                // Update enemy with new target
                enemy.targetVillager = newTarget;
                enemy.isReturning = true;  // Make enemy return to new villager
                enemy.isChasing = false;
            } else {
                // No more villagers to guard, enemy becomes defeated
                return {
                    ...enemy,
                    color: CONFIG.enemies.colors.defeated
                };
            }
        }
        
        // Calculate distance to player
        const dx = state.player.x - enemy.x;
        const dy = state.player.y - enemy.y;
        const distanceToPlayer = Math.sqrt(dx * dx + dy * dy);
        
        if (distanceToPlayer <= aggroRange) {
            // Check if in attack range (half grid cell)
            const attackRange = gridSize * 0.5;
            
            // If on attack cooldown, keep distance
            if (enemy.attackCooldown) {
                if (animationTime >= enemy.attackCooldownUntil) {
                    enemy.attackCooldown = false;
                } else if (distanceToPlayer < gridSize) {
                    // Retreat if too close during cooldown
                    const retreatAngle = Math.atan2(dy, dx) + Math.PI; // Opposite direction
                    const retreatSpeed = baseSpeed * CONFIG.enemies.chase.speedMultiplier;
                    return {
                        ...enemy,
                        x: enemy.x + Math.cos(retreatAngle) * retreatSpeed,
                        y: enemy.y + Math.sin(retreatAngle) * retreatSpeed,
                        isChasing: true
                    };
                }
            }
            
            // If in attack range and not on cooldown, initiate attack
            if (distanceToPlayer <= attackRange && !enemy.attacking && !enemy.attackCooldown) {
                enemy.attacking = true;
                enemy.attackStartPosition = { x: enemy.x, y: enemy.y };
                enemy.attackTargetPosition = {
                    x: state.player.x,
                    y: state.player.y
                };
                enemy.attackStartTime = animationTime;

                // Change enemy color to a random blue shade
                enemy.color = blueShades[Math.floor(Math.random() * blueShades.length)];
            }
            
            // Handle attack animation and damage
            if (enemy.attacking) {
                const attackDuration = 200; // 200ms attack
                const progress = (animationTime - enemy.attackStartTime) / attackDuration;
                
                if (progress >= 1) {
                    enemy.attacking = false;
                    enemy.attackCooldown = true;
                    enemy.attackCooldownUntil = animationTime + 1000; // 1 second cooldown
                    
                    // Check if attack hit the player
                    const finalDx = state.player.x - enemy.x;
                    const finalDy = state.player.y - enemy.y;
                    const finalDistance = Math.sqrt(finalDx * finalDx + finalDy * finalDy);
                    
                    if (finalDistance < enemy.size + CONFIG.player.size && 
                        !state.player.isInvulnerable && 
                        !state.player.isDefending && 
                        !state.player.isSwinging && 
                        state.player.bubbles.length === 0) {
                        state.player.hp -= 1;
                        state.player.isInvulnerable = true;
                        state.player.invulnerableUntil = animationTime + 1000;
                    }
                    
                    return {
                        ...enemy,
                        isChasing: true
                    };
                }
                
                // Fast lunge animation with ease-in
                const t = progress * progress; // Quadratic ease-in
                return {
                    ...enemy,
                    x: enemy.attackStartPosition.x + (enemy.attackTargetPosition.x - enemy.attackStartPosition.x) * t,
                    y: enemy.attackStartPosition.y + (enemy.attackTargetPosition.y - enemy.attackStartPosition.y) * t,
                    isChasing: true,
                    attacking: true
                };
            }
            
            // Normal chase behavior if not attacking
            const angle = Math.atan2(dy, dx);
            const chaseSpeed = baseSpeed * CONFIG.enemies.chase.speedMultiplier;
            
            return {
                ...enemy,
                x: enemy.x + Math.cos(angle) * chaseSpeed,
                y: enemy.y + Math.sin(angle) * chaseSpeed,
                isChasing: true
            };
        } else {
            // Get current distance from villager
            const dvx = enemy.x - enemy.targetVillager.x;
            const dvy = enemy.y - enemy.targetVillager.y;
            const distanceToVillager = Math.sqrt(dvx * dvx + dvy * dvy);
            
            // If too far from villager, start returning
            if (distanceToVillager > gridSize * 3) {
                return {
                    ...enemy,
                    isReturning: true,
                    isChasing: false
                };
            }
            
            // Patrol behavior - move in small circles around current position
            if (!enemy.patrolAngle) {
                enemy.patrolAngle = Math.random() * Math.PI * 2;
            }
            
            enemy.patrolAngle += baseSpeed * 0.02; // Small angle change for circular movement
            
            return {
                ...enemy,
                x: enemy.x + Math.cos(enemy.patrolAngle) * baseSpeed,
                y: enemy.y + Math.sin(enemy.patrolAngle) * baseSpeed,
                patrolAngle: enemy.patrolAngle,
                isChasing: false
            };
        }
    });
};

const renderEnemies = (ctx, enemies) => {
    // Pre-create the health circle gradient once
    const healthGradient = ctx.createRadialGradient(0, 0, 0, 0, 0, 2);
    healthGradient.addColorStop(0, 'rgba(255, 0, 0, 0.8)');
    healthGradient.addColorStop(0.7, 'rgba(200, 0, 0, 0.6)');
    healthGradient.addColorStop(1, 'rgba(150, 0, 0, 0.4)');

    enemies.forEach(enemy => {
        // Draw enemy body
        ctx.beginPath();
        ctx.arc(enemy.x, enemy.y, enemy.size, 0, Math.PI * 2);
        ctx.fillStyle = enemy.stunned ? 'rgb(150, 150, 150)' : enemy.color;
        ctx.fill();
        
        // Add a glowing effect
        const glowSize = enemy.stunned ? 1.1 : (enemy.attacking ? 1.6 : enemy.isChasing ? 1.4 : 1.2);
        const glowIntensity = enemy.stunned ? 0.1 : (enemy.attacking ? 0.5 : enemy.isChasing ? 0.3 : 0.2);
        
        // Create glow gradient only once per enemy
        const glowGradient = ctx.createRadialGradient(
            enemy.x, enemy.y, enemy.size * 0.5,
            enemy.x, enemy.y, enemy.size * glowSize
        );
        glowGradient.addColorStop(0, `rgba(255, 0, 0, ${glowIntensity})`);
        glowGradient.addColorStop(1, 'rgba(255, 0, 0, 0)');
        
        ctx.beginPath();
        ctx.arc(enemy.x, enemy.y, enemy.size * glowSize, 0, Math.PI * 2);
        ctx.fillStyle = glowGradient;
        ctx.fill();
        
        // Draw HP circles
        if (enemy.hp > 0) {
            const circleRadius = 3;
            const circleSpacing = 8;
            const totalCircles = enemy.hp;
            const startX = enemy.x - ((totalCircles - 1) * circleSpacing) / 2;
            const circleY = enemy.y - enemy.size - 15;
            
            // Batch draw the circle borders
            ctx.beginPath();
            for (let i = 0; i < totalCircles; i++) {
                const circleX = startX + (i * circleSpacing);
                ctx.moveTo(circleX + circleRadius, circleY);
                ctx.arc(circleX, circleY, circleRadius, 0, Math.PI * 2);
            }
            ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)';
            ctx.lineWidth = 1;
            ctx.stroke();
            
            // Batch draw the filled circles
            ctx.beginPath();
            for (let i = 0; i < totalCircles; i++) {
                const circleX = startX + (i * circleSpacing);
                ctx.moveTo(circleX + circleRadius - 1, circleY);
                ctx.arc(circleX, circleY, circleRadius - 1, 0, Math.PI * 2);
            }
            ctx.fillStyle = 'rgba(255, 0, 0, 0.6)';
            ctx.fill();
        }
    });
};

const generateDiamonds = () => {
    const diamondCount = Math.floor(Math.random() * 5); // 0 to 4 diamonds
    const diamonds = [];
    
    for (let i = 0; i < diamondCount; i++) {
        diamonds.push({
            x: enemy.x + (Math.random() - 0.5) * 20, // Random position around the enemy
            y: enemy.y + (Math.random() - 0.5) * 20,
            size: 10, // Size of the diamond
            collected: false // Track if collected
        });
    }
    
    return diamonds;
};

// Export the functions
window.enemySystem = {
    generateEnemies,
    updateEnemies,
    renderEnemies,
    findNearestLostVillager,
    handleEnemyDamage
};