Cannot shoot anymore enemies after that, the unfinished word is still registered after the enemy's death with an EMP:
// Get the canvas and context
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Set canvas dimensions to match the window
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Create an offscreen canvas for the bloom effect
const offscreenCanvas = document.createElement('canvas');
offscreenCanvas.width = canvas.width;
offscreenCanvas.height = canvas.height;
const offscreenCtx = offscreenCanvas.getContext('2d');
// Player class
class Player {
constructor() {
this.width = 40;
this.height = 60;
this.x = canvas.width / 2 - this.width / 2;
this.y = canvas.height - this.height - 20;
this.isHighlighted = false; // To indicate incorrect input
}
draw(ctx) {
// Change color based on isHighlighted
ctx.fillStyle = this.isHighlighted ? '#ff8800' : '#00ff00'; // Orange if highlighted, else green
// Draw the ship (triangle pointing upwards)
ctx.beginPath();
ctx.moveTo(this.x + this.width / 2, this.y); // Tip of the ship
ctx.lineTo(this.x, this.y + this.height); // Bottom left
ctx.lineTo(this.x + this.width, this.y + this.height); // Bottom right
ctx.closePath();
ctx.fill();
}
}
const player = new Player();
// Projectile class
class Projectile {
constructor(x, y, targetEnemy) {
this.x = x + player.width / 2; // Start from the center of the player
this.y = y;
this.targetEnemy = targetEnemy;
this.speed = 8; // Increased speed to catch up with enemies
this.radius = 5;
this.updateVelocity();
}
// Enemy class
class Enemy {
constructor(word, speed) {
this.word = word;
this.speed = speed;
this.x = this.getSpawnX();
this.y = -50;
this.destroyed = false;
this.currentTypingIndex = 0; // Number of letters typed by the player
this.isTypingComplete = false; // Indicates if the player has finished typing the word
this.isTargeted = false; // To indicate if this enemy is being targeted
this.vx = 0;
this.vy = 0;
this.knockbackVx = 0; // Knockback velocity in x-direction
this.knockbackVy = 0; // Knockback velocity in y-direction
this.knockbackTime = 0; // Duration of knockback effect
this.hitPoints = this.word.length; // Number of hits required to destroy the enemy
}
getSpawnX() {
let x;
let attempts = 0;
do {
x = Math.random() * (canvas.width - 100) + 50;
attempts++;
} while (this.isOverlapping(x) && attempts < 50);
return x;
}
isOverlapping(x) {
return enemies.some(enemy => {
return Math.abs(enemy.x - x) < 50; // Adjust based on enemy size
});
}
update() {
if (this.knockbackTime > 0) {
// Apply knockback movement
this.x += this.knockbackVx;
this.y += this.knockbackVy;
// Reduce knockback over time (simulate friction)
const friction = 0.9;
this.knockbackVx *= friction;
this.knockbackVy *= friction;
this.knockbackTime--;
} else {
// Calculate direction towards player
const dx = (player.x + player.width / 2) - this.x;
const dy = (player.y + player.height / 2) - this.y;
const distance = Math.hypot(dx, dy);
this.vx = (dx / distance) * this.speed;
this.vy = (dy / distance) * this.speed;
// Move towards player
this.x += this.vx;
this.y += this.vy;
}
}
draw(ctx) {
ctx.fillStyle = this.isTargeted ? '#ff8800' : '#ff0000'; // Highlight if targeted
ctx.fillRect(this.x - 20, this.y - 20, 40, 40);
// Enemy word
ctx.font = '20px Arial';
ctx.textAlign = 'left';
// Split the word into typed and remaining parts
const typed = this.word.substring(0, this.currentTypingIndex);
const remaining = this.word.substring(this.currentTypingIndex);
// Measure the total width of the word
const wordWidth = ctx.measureText(this.word).width;
// Set the starting x position so that the word is centered above the enemy
const wordX = this.x - wordWidth / 2;
const wordY = this.y - 30;
// Draw typed letters in green
ctx.fillStyle = '#00ff00';
ctx.fillText(typed, wordX, wordY);
// Measure the width of the typed text to offset the remaining text
const typedWidth = ctx.measureText(typed).width;
// Draw remaining letters in white
ctx.fillStyle = '#ffffff';
ctx.fillText(remaining, wordX + typedWidth, wordY);
}
let enemies = [];
let enemySpawnQueue = [];
let wave = 1;
let enemySpeed = 1;
let enemiesPerWave = 5;
let spawnIntervalTime = 2000; // Initial spawn interval in milliseconds
let enemySpawnInterval = null; // Initialize to null
let isWaveTransitioning = false; // Flag to prevent multiple wave transitions
let waveClearMessage = null; // Object to handle wave clear message
// Function to prepare enemies for the wave
async function prepareEnemies() {
const usedLetters = new Set();
// Collect first letters of active enemies
enemies.forEach(enemy => {
if (!enemy.destroyed && !enemy.isTypingComplete) {
usedLetters.add(enemy.word.charAt(0).toLowerCase());
}
});
enemySpawnQueue.forEach(enemy => {
usedLetters.add(enemy.word.charAt(0).toLowerCase());
});
let wordsNeeded = enemiesPerWave;
let words = [];
let attempts = 0;
while (words.length < wordsNeeded && attempts < 10) {
// Get more words than needed, to increase chance of getting words with unique starting letters
const wordsToFetch = (wordsNeeded - words.length) * 2;
const newWords = await getRandomWords(wordsToFetch);
for (let word of newWords) {
// Ignore words that do not start with a letter
if (!/^[a-zA-Z]/.test(word)) continue;
const firstLetter = word.charAt(0).toLowerCase();
if (!usedLetters.has(firstLetter)) {
words.push(word);
usedLetters.add(firstLetter);
if (words.length >= wordsNeeded) break;
}
}
attempts++;
// Break if cannot find enough unique words after several attempts
if (attempts >= 10) {
console.log('Not enough unique words could be fetched.');
break;
}
}
// If still not enough words, accept words even if they have repeated starting letters
if (words.length < wordsNeeded) {
const additionalWords = await getRandomWords(wordsNeeded - words.length);
words.push(...additionalWords);
}
words.forEach(word => {
enemySpawnQueue.push(new Enemy(word.toLowerCase(), enemySpeed));
});
}
// Function to spawn an enemy from the queue
function spawnEnemyFromQueue() {
if (enemySpawnQueue.length > 0) {
const enemy = enemySpawnQueue.shift();
enemies.push(enemy);
if (isWaveTransitioning) {
isWaveTransitioning = false; // Wave has started
}
}
}
// Start enemy spawning with intervals
function startEnemySpawning() {
spawnEnemyFromQueue(); // Spawn one enemy immediately
enemySpawnInterval = setInterval(() => {
spawnEnemyFromQueue();
if (enemySpawnQueue.length === 0) {
clearInterval(enemySpawnInterval);
enemySpawnInterval = null; // Set to null after clearing the interval
}
}, spawnIntervalTime);
let currentInput = '';
let score = 0;
let isGameOver = false;
let keystrokes = 0; // Total number of keystrokes (both correct and incorrect)
let correctKeystrokes = 0; // Total number of correct keystrokes
let streak = 0;
let longestStreak = 0;
let projectiles = [];
let targetEnemy = null;
let explosions = []; // Array to hold active explosions
// EMP system variables
let empCount = 3; // Player starts with 3 EMPs
let emps = []; // Array to hold active EMPs
// EMP class
class EMP {
constructor(x, y) {
this.x = x;
this.y = y;
this.lifetime = 60; // Duration of the EMP effect in frames
this.currentRadius = 0; // Current radius
this.maxRadius = canvas.width * 0.5; // Maximum radius the EMP reaches
this.expansionRate = this.maxRadius / this.lifetime; // Rate at which the EMP expands
this.active = true;
}
// Function to activate an EMP
function activateEMP() {
const emp = new EMP(player.x + player.width / 2, player.y + player.height / 2);
emps.push(emp);
// Optional: Add sound effect or screen shake here
}
// Handle user input
document.addEventListener('keydown', function (event) {
if (isGameOver) return;
const key = event.key.toLowerCase();
// Check if the key is 'Enter' and activate EMP
if (event.key === 'Enter') {
if (empCount > 0) {
activateEMP();
empCount--;
} else {
// Optional: Provide feedback that no EMPs are left
console.log('No EMPs left!');
}
return; // Early exit to prevent further processing
}
// Accept only alphabetic keys
if (/^[a-z]$/.test(key)) {
keystrokes++; // Increment total keystrokes for every alphabetic key pressed
const potentialInput = currentInput + key;
// Find matching enemies among those not yet typing complete
let matchingEnemies = enemies.filter(enemy => !enemy.isTypingComplete && enemy.word.startsWith(potentialInput));
if (matchingEnemies.length > 0) {
correctKeystrokes++; // Increment correct keystrokes only when the key press is correct
currentInput += key;
targetEnemy = matchingEnemies[0]; // Prioritize the first matching enemy
enemies.forEach(enemy => {
enemy.isTargeted = (enemy === targetEnemy);
});
// Update enemy's typing index
targetEnemy.currentTypingIndex = currentInput.length;
// Create a new projectile towards the target enemy
projectiles.push(new Projectile(player.x, player.y, targetEnemy));
checkInput();
} else {
// Incorrect input
// Highlight the player's ship
player.isHighlighted = true;
setTimeout(() => {
player.isHighlighted = false;
}, 300); // Highlight for 300ms
// Do not increment correctKeystrokes or currentInput
// Keep currentInput as it is
// Do not reset streak
}
}
});
// Check input against enemy words
function checkInput() {
enemies.forEach(enemy => {
if (!enemy.isTypingComplete && enemy.word.startsWith(currentInput)) {
enemy.currentTypingIndex = currentInput.length;
// If the full word matches
if (enemy.word === currentInput) {
// Mark enemy as typing complete
enemy.isTypingComplete = true;
// Clear current input to prevent further typing
currentInput = '';
// Reset target enemy
targetEnemy = null;
}
} else {
enemy.currentTypingIndex = 0;
}
});
// Variables for fixed timestep game loop
let delta = 0;
let lastFrameTimeMs = 0;
const timestep = 1000 / 60; // 60 FPS
// Start the game loop
function gameLoop(timestamp) {
if (isGameOver) {
displayStats();
return;
}
// Throttle the frame rate
if (timestamp < lastFrameTimeMs + (1000 / 60)) {
requestAnimationFrame(gameLoop);
return;
}
delta += timestamp - lastFrameTimeMs;
lastFrameTimeMs = timestamp;
while (delta >= timestep) {
updateGame();
delta -= timestep;
}
renderGame();
// Continue the game loop
requestAnimationFrame(gameLoop);
}
// Function to update game logic
function updateGame() {
// Update enemies
if (!isWaveTransitioning || waveClearMessage) {
enemies.forEach(enemy => {
enemy.update();
// Check collision with player
const dx = enemy.x - (player.x + player.width / 2);
const dy = enemy.y - (player.y + player.height / 2);
const distance = Math.hypot(dx, dy);
if (distance < 30 && !enemy.destroyed) { // Adjust collision distance as needed
isGameOver = true;
}
});
// Update projectiles
projectiles = projectiles.filter((projectile) => {
projectile.update();
// Check for collision with target enemy
if (projectile.targetEnemy && !projectile.targetEnemy.destroyed) {
const dx = projectile.x - projectile.targetEnemy.x;
const dy = projectile.y - projectile.targetEnemy.y;
const distance = Math.hypot(dx, dy);
if (distance < projectile.radius + 20) { // Adjust collision radius as needed
score += 10;
// Apply slight knockback to the enemy
const knockbackMagnitude = 2; // Adjust as needed
const dxPlayer = (player.x + player.width / 2) - projectile.targetEnemy.x;
const dyPlayer = (player.y + player.height / 2) - projectile.targetEnemy.y;
const angleTowardsPlayer = Math.atan2(dyPlayer, dxPlayer);
const angleAwayFromPlayer = angleTowardsPlayer + Math.PI; // Reverse direction
projectile.targetEnemy.knockbackVx = Math.cos(angleAwayFromPlayer) * knockbackMagnitude;
projectile.targetEnemy.knockbackVy = Math.sin(angleAwayFromPlayer) * knockbackMagnitude;
projectile.targetEnemy.knockbackTime = 5; // Number of frames to apply knockback
// Decrement enemy hit points
projectile.targetEnemy.hitPoints--;
if (projectile.targetEnemy.hitPoints <= 0) {
projectile.targetEnemy.destroyed = true;
streak++;
if (streak > longestStreak) {
longestStreak = streak;
}
// Create explosion when enemy is destroyed
createExplosion(projectile.targetEnemy.x, projectile.targetEnemy.y);
// No need to reset currentInput here as it's handled when typing is complete
}
// Remove projectile after hit
return false; // Remove projectile from array
}
}
// Remove projectile if offscreen
if (projectile.offscreen()) {
return false; // Remove projectile
}
return true; // Keep projectile
});
// Update explosions
explosions = explosions.filter(explosion => {
explosion.update();
return explosion.particles.length > 0;
});
// Remove destroyed enemies
enemies = enemies.filter(enemy => !enemy.destroyed);
}
// Update EMPs
emps = emps.filter(emp => {
emp.update();
return emp.active;
});
// Check if wave is over
if (!isWaveTransitioning && enemies.length === 0 && enemySpawnQueue.length === 0 && !enemySpawnInterval) {
isWaveTransitioning = true; // Prevent multiple wave increments
streak = 0; // Reset streak at the end of the wave
// Set up wave clear message
waveClearMessage = {
text: `WAVE ${wave} CLEAR`,
elapsedTime: 0,
duration: 4000, // Total duration in milliseconds
fadeInDuration: 1000, // Fade in over 1 second
holdDuration: 2000, // Hold for 2 seconds
fadeOutDuration: 1000,// Fade out over 1 second
yStart: canvas.height / 2 - 50, // Start a bit above center
yEnd: canvas.height / 2 + 50, // End a bit below center
x: 20, // Horizontally on the left
opacity: 0,
y: canvas.height / 2 - 50,
};
}
// Update wave clear message
if (waveClearMessage) {
waveClearMessage.elapsedTime += timestep;
const t = waveClearMessage.elapsedTime;
const { fadeInDuration, holdDuration, fadeOutDuration, yStart, yEnd } = waveClearMessage;
const totalDuration = fadeInDuration + holdDuration + fadeOutDuration;
if (t >= totalDuration) {
// Message is done
waveClearMessage = null;
// Proceed to next wave
wave++; // Increment wave number for the next wave
enemySpeed += 0.2;
enemiesPerWave += 1;
spawnIntervalTime = Math.max(1000, spawnIntervalTime - 100); // Decrease spawn interval, minimum 1000ms
prepareEnemies().then(() => {
startEnemySpawning();
// isWaveTransitioning will be set to false in spawnEnemyFromQueue()
});
} else {
// Update message properties: opacity and position
let opacity = 0;
let y = 0;
if (t <= fadeInDuration) {
// Fade in
opacity = t / fadeInDuration;
y = waveClearMessage.yStart + ((t / fadeInDuration) * (canvas.height / 2 - waveClearMessage.yStart));
} else if (t <= fadeInDuration + holdDuration) {
// Hold
opacity = 1;
y = canvas.height / 2;
} else {
// Fade out
const tFadeOut = t - fadeInDuration - holdDuration;
opacity = 1 - (tFadeOut / fadeOutDuration);
y = canvas.height / 2 + ((tFadeOut / fadeOutDuration) * (waveClearMessage.yEnd - canvas.height / 2));
}
waveClearMessage.opacity = opacity;
waveClearMessage.y = y;
}
}
}
// Function to create an explosion at a given position
function createExplosion(x, y) {
explosions.push(new Explosion(x, y));
}
// Explosion class to manage particles
class Explosion {
constructor(x, y) {
this.particles = [];
const particleCount = 20; // Number of particles in explosion
for (let i = 0; i < particleCount; i++) {
this.particles.push(new Particle(x, y, '#ff8800')); // Use orange color for explosion particles
}
}
update() {
this.particles.forEach((particle, index) => {
particle.update();
// Remove particle if it is faded out
if (particle.alpha <= 0) {
this.particles.splice(index, 1);
}
});
}
draw(ctx) {
this.particles.forEach(particle => {
particle.draw(ctx);
});
}
}
// Function to render the game
function renderGame() {
// Clear both canvases
ctx.clearRect(0, 0, canvas.width, canvas.height);
offscreenCtx.clearRect(0, 0, offscreenCanvas.width, offscreenCanvas.height);
// Draw scene onto the offscreen canvas
drawScene(offscreenCtx);
// Apply bloom effect
applyBloom();
// Draw HUD elements (e.g., input text) onto the main canvas
// Display current input
ctx.fillStyle = '#ffffff';
ctx.font = '20px Arial';
ctx.textAlign = 'left';
ctx.fillText(`Input: ${currentInput}`, 20, canvas.height - 20);
// Display EMP count as a circle with the number inside
const circleRadius = 20;
const circleX = canvas.width - circleRadius - 20; // 20 pixels from the right edge
const circleY = canvas.height - circleRadius - 20; // 20 pixels from the bottom edge
// Draw the circle
ctx.fillStyle = '#00ffff'; // Cyan color fits the game's theme
ctx.beginPath();
ctx.arc(circleX, circleY, circleRadius, 0, Math.PI * 2);
ctx.fill();
// Draw the EMP count number
ctx.fillStyle = '#000000'; // Black color for the number
ctx.font = '20px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(empCount, circleX, circleY);
// Update stats display
// Ensure you have an element with id 'stats' in your HTML
document.getElementById('stats').innerHTML = `Score: ${score} | Wave: ${wave} | Streak: ${streak}`;
// Draw wave clear message
if (waveClearMessage) {
ctx.save();
ctx.globalAlpha = waveClearMessage.opacity;
ctx.fillStyle = '#00ffff'; // Cyan color
ctx.font = '48px Arial';
ctx.textAlign = 'left';
ctx.textBaseline = 'middle';
ctx.fillText(waveClearMessage.text, waveClearMessage.x, waveClearMessage.y);
ctx.restore();
}
}
// Function to draw the entire scene onto a given context
function drawScene(context) {
// Draw background
drawStars(context);
drawNebulas(context);
// Function to apply the bloom effect
function applyBloom() {
// Save the current canvas state
ctx.save();
// Draw the offscreen canvas onto the main canvas
ctx.drawImage(offscreenCanvas, 0, 0);
// Apply blur filter
ctx.filter = 'blur(8px)';
// Set the global composite operation to lighter to create the bloom effect
ctx.globalCompositeOperation = 'lighter';
// Draw the offscreen canvas again with the blur and blending mode
ctx.drawImage(offscreenCanvas, 0, 0);
// Restore the canvas state
ctx.restore();
// Reset filters and composite operation
ctx.filter = 'none';
ctx.globalCompositeOperation = 'source-over';
}
// Start the game
prepareEnemies().then(() => {
startEnemySpawning();
requestAnimationFrame(gameLoop);
});
The issue you're experiencing occurs because the game doesn't properly handle the scenario where an enemy is destroyed (e.g., by an EMP) while the player is in the middle of typing that enemy's word. In such cases, the currentInput still holds the partly typed word, and since the enemy is gone, it doesn't match any existing enemies. As a result, the game doesn't reset currentInput or targetEnemy, preventing you from targeting new enemies.
Solution:
To fix this, we need to ensure that whenever enemies are destroyed—either by EMP or any other means—we check if the currentInput still matches any of the remaining enemies. If it doesn't, we should reset currentInput and targetEnemy. Here's how you can implement this:
Step 1: After destroying enemies (whether by EMP or projectiles), and after removing them from the enemies array, add a check to see if currentInput still matches any of the remaining enemies.
Step 2: If currentInput doesn't match any enemy's word, reset currentInput and targetEnemy, and ensure no enemies are marked as targeted.
Implementation Details:
Locate the updateGame function in your code and add the following code after the line where you filter out the destroyed enemies:
// Remove destroyed enemies
enemies = enemies.filter(enemy => !enemy.destroyed);
// After removing destroyed enemies, check if currentInput still matches any enemy
let inputStillValid = enemies.some(enemy => enemy.word.startsWith(currentInput));
if (!inputStillValid) {
currentInput = '';
targetEnemy = null;
enemies.forEach(enemy => enemy.isTargeted = false);
}
Explanation:
Line 1: We remove all destroyed enemies from the enemies array.
Line 3: We check if the currentInput still matches the beginning of any enemy's word using the some method.
Line 5: If no enemies match the currentInput, we reset currentInput and targetEnemy to allow the player to start typing a new word.
Line 7: We also ensure that no enemies are marked as targeted since the previous target may have been destroyed.
By adding this code, you ensure that the game state remains consistent even when enemies are destroyed while being targeted. It allows the player to continue targeting and destroying new enemies without being stuck due to an invalid currentInput.
Updated Code Snippet:
Here's the relevant part of the updateGame function with the added code:
function updateGame() {
// ... [existing code] ...
// Update EMPs
emps = emps.filter(emp => {
emp.update();
return emp.active;
});
// Remove destroyed enemies
enemies = enemies.filter(enemy => !enemy.destroyed);
// After removing destroyed enemies, check if currentInput still matches any enemy
let inputStillValid = enemies.some(enemy => enemy.word.startsWith(currentInput));
if (!inputStillValid) {
currentInput = '';
targetEnemy = null;
enemies.forEach(enemy => enemy.isTargeted = false);
}
// ... [remaining code] ...
}
Conclusion:
This fix ensures that the game properly resets the player's input and targeting status when the current target is destroyed by an EMP or any other means, preventing the reported bug from occurring.