// game.js
// 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;
// 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() {
// Change color based on isHighlighted
ctx.fillStyle = this.isHighlighted ? '#ff8800' : '#00ff00'; // Orange if highlighted, else green
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();
// Stars for the background
const stars = [];
for (let i = 0; i < 200; i++) {
stars.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
size: Math.random() * 2,
opacity: Math.random()
});
}
function drawStars() {
ctx.fillStyle = 'white';
stars.forEach(star => {
ctx.globalAlpha = star.opacity;
ctx.fillRect(star.x, star.y, star.size, star.size);
});
ctx.globalAlpha = 1;
}
// Nebulas for the background
const nebulas = [];
for (let i = 0; i < 3; i++) {
nebulas.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
radius: Math.random() * 200 + 100,
color: `hsla(${Math.random() * 360}, 60%, 50%, 0.1)`
});
}
function drawNebulas() {
nebulas.forEach(nebula => {
const gradient = ctx.createRadialGradient(
nebula.x, nebula.y, 0,
nebula.x, nebula.y, nebula.radius
);
gradient.addColorStop(0, nebula.color);
gradient.addColorStop(1, 'transparent');
ctx.fillStyle = gradient;
ctx.beginPath();
ctx.arc(nebula.x, nebula.y, nebula.radius, 0, Math.PI * 2);
ctx.fill();
});
}
// 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;
}
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() {
this.y += this.speed;
}
draw() {
// Enemy ship
ctx.fillStyle = '#ff0000'; // Red color
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;
// Function to prepare enemies for the wave
async function prepareEnemies() {
const usedLetters = new Set();
// Collect first letters of pre-spawned enemies (both in enemies and in enemySpawnQueue)
enemies.forEach(enemy => {
usedLetters.add(enemy.word.charAt(0).toLowerCase());
});
enemySpawnQueue.forEach(enemy => {
usedLetters.add(enemy.word.charAt(0).toLowerCase());
});
let wordsNeeded = enemiesPerWave;
let words = [];
while (words.length < wordsNeeded) {
// 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;
}
}
}
// If we cannot find enough words, break to avoid infinite loop.
// This can happen if we have used all possible letters.
if (newWords.length === 0) {
console.log('Not enough unique words could be fetched.');
break;
}
}
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);
}
}
// Start enemy spawning with intervals
function startEnemySpawning() {
spawnEnemyFromQueue(); // Spawn one enemy immediately
enemySpawnInterval = setInterval(() => {
spawnEnemyFromQueue();
if (enemySpawnQueue.length === 0) {
clearInterval(enemySpawnInterval);
}
}, spawnIntervalTime);
}
// Fetch random words from external API
async function getRandomWords(count) {
try {
const response = await fetch(`https://random-word-api.herokuapp.com/word?number=${count}`);
const words = await response.json();
// Filter out words that are empty or do not start with a letter
return words.filter(word => /^[a-zA-Z]/.test(word));
} catch (error) {
console.error('Error fetching words:', error);
// Fallback words in case the API fails
return [
'fallback', 'words', 'typing', 'game', 'space', 'enemy', 'ship',
'laser', 'attack', 'defend', 'asteroid', 'galaxy', 'meteor',
'planet', 'comet', 'star', 'universe', 'rocket', 'alien'
];
}
}
let currentInput = '';
let score = 0;
let isGameOver = false;
let keystrokes = 0; // Total number of correct keystrokes
let correctKeystrokes = 0; // Total number of correct keystrokes used to eliminate enemies
let streak = 0;
let longestStreak = 0;
// Handle user input
document.addEventListener('keydown', function(event) {
if (isGameOver) return;
const key = event.key.toLowerCase();
// Accept only alphabetic keys
if (/^[a-z]$/.test(key)) {
const potentialInput = currentInput + key;
let matchesAny = enemies.some(enemy => enemy.word.startsWith(potentialInput));
if (matchesAny) {
// Correct input
keystrokes++;
currentInput += key;
checkInput();
} else {
// Incorrect input
// Highlight the player's ship
player.isHighlighted = true;
setTimeout(() => {
player.isHighlighted = false;
}, 300); // Highlight for 300ms
// Do not increment keystrokes or currentInput
// Keep currentInput as it is
// Do not reset streak
}
}
});
// Check input against enemy words
function checkInput() {
enemies.forEach(enemy => {
if (enemy.word.startsWith(currentInput)) {
enemy.currentTypingIndex = currentInput.length;
// If the full word matches
if (enemy.word === currentInput) {
enemy.destroyed = true;
currentInput = '';
score += enemy.word.length * 10;
streak++;
if (streak > longestStreak) {
longestStreak = streak;
}
correctKeystrokes += enemy.word.length;
// Reset typing indices of other enemies
enemies.forEach(otherEnemy => {
otherEnemy.currentTypingIndex = 0;
});
}
} else {
enemy.currentTypingIndex = 0;
}
});
}
// Display end-of-game stats
function displayStats() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#ffffff';
ctx.font = '30px Arial';
ctx.textAlign = 'center';
ctx.fillText('Game Over', canvas.width / 2, canvas.height / 2 - 80);
ctx.font = '24px Arial';
ctx.fillText(`Score: ${score}`, canvas.width / 2, canvas.height / 2 - 40);
ctx.fillText(`Waves Survived: ${wave - 1}`, canvas.width / 2, canvas.height / 2);
const accuracy = ((keystrokes > 0) ? (correctKeystrokes / keystrokes) * 100 : 0).toFixed(2);
ctx.fillText(`Typing Accuracy: ${accuracy}%`, canvas.width / 2, canvas.height / 2 + 40);
ctx.fillText(`Longest Streak: ${longestStreak}`, canvas.width / 2, canvas.height / 2 + 80);
ctx.font = '20px Arial';
ctx.fillText('Press F5 to Restart', canvas.width / 2, canvas.height / 2 + 120);
}
// Main game loop
async function gameLoop() {
if (isGameOver) {
displayStats();
return;
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw background
drawStars();
drawNebulas();
// Update and draw enemies
enemies.forEach(enemy => {
enemy.update();
enemy.draw();
// Check collision with player
if (enemy.y + 20 >= player.y && !enemy.destroyed) {
isGameOver = true;
}
});
// Remove destroyed enemies or those off-screen
enemies = enemies.filter(enemy => !enemy.destroyed && enemy.y < canvas.height + 50);
// Check if wave is over
if (enemies.length === 0 && enemySpawnQueue.length === 0) {
// Proceed to next wave
wave++;
enemySpeed += 0.2; // Adjusted for smoother difficulty progression
enemiesPerWave += 1; // Increase number of enemies per wave
spawnIntervalTime = Math.max(500, spawnIntervalTime - 100); // Decrease spawn interval, not going below 500ms
await prepareEnemies();
startEnemySpawning();
}
// Draw the player
player.draw();
// Display current input
ctx.fillStyle = '#ffffff';
ctx.font = '20px Arial';
ctx.textAlign = 'left';
ctx.fillText(`Input: ${currentInput}`, 20, canvas.height - 20);
// Update stats display
document.getElementById('stats').innerHTML = `Score: ${score} | Wave: ${wave} | Streak: ${streak}`;
// Continue the game loop
requestAnimationFrame(gameLoop);
}
// Start the game
prepareEnemies().then(() => {
startEnemySpawning();
gameLoop();
});
// Adjust canvas size on window resize
window.addEventListener('resize', function() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
player.x = canvas.width / 2 - player.width / 2;
player.y = canvas.height - player.height - 20;
});
Explanation of the Modification:
In the updated prepareEnemies function, the game now ensures that newly generated words don't start with the same letter as any pre-spawned enemy. Here's how it works:
-
Collect Used Letters:
- We create a
Set called usedLetters to track the first letters of all pre-spawned enemies.
- We iterate over both the
enemies array and the enemySpawnQueue to collect the starting letters of all existing enemy words.
-
Fetch and Filter Words:
- We attempt to fetch more words than needed to increase the chance of getting words with unique starting letters.
- We loop until we have enough words that satisfy the condition or until it's impractical to continue.
- For each fetched word, we check:
- If it starts with a letter (ignoring any words that start with non-alphabetic characters).
- If its first letter is not already in the
usedLetters set.
- If both conditions are satisfied, we add the word to our list and update the
usedLetters set.
-
Avoid Infinite Loops:
- The loop includes a safeguard to break if no new words are fetched, which can happen if the word source is exhausted or if all letters are already used.
By implementing this change, the game prevents multiple enemies from having words that start with the same letter, reducing confusion and making the gameplay more engaging.
Note: Ensure that the HTML file includes an element with the ID gameCanvas for the canvas and an element with the ID stats to display the score and other game stats.