<script>
const gameContainer = document.getElementById('game-container');
const gameWorld = document.getElementById('game-world');
const player = document.getElementById('player');
const scoreDisplay = document.getElementById('score');
const livesDisplay = document.getElementById('lives');
const levelDisplay = document.getElementById('level');
const timerDisplay = document.getElementById('timer');
const instructions = document.getElementById('instructions');
const cutscene = document.getElementById('cutscene');
const levelIntro = document.getElementById('level-intro');
const levelText = document.getElementById('level-text');
const bossFightScreen = document.getElementById('boss-fight');
const gameOverScreen = document.getElementById('game-over');
const intro = document.getElementById('intro');
const dialoguePara = document.querySelector('#dialogue p');
const bossHallway = document.getElementById('boss-hallway');
const bossHealthBar = document.getElementById('boss-health-bar');
const bossHealthDisplay = document.getElementById('boss-health');
const powerUpMessage = document.getElementById('power-up-message');
const interactMessage = document.getElementById('interact-message');
const friend = document.getElementById('friend');
let playerPositionX = 50;
let playerPositionY = 0;
let playerVelocityX = 0;
let playerVelocityY = 0;
let playerMaxSpeed = 5;
const playerJumpStrength = 12;
let jumpCount = 0;
const maxJumps = 2;
let isDoubleJumpEnabled = false;
let isJumping = false;
let isPaused = false;
let canShoot = true;
let bossAttacking = false;
let bossAttackPhase = 0;
let gameInterval;
let obstacles = [];
let enemies = [];
let bullets = [];
let powerUps = [];
let platforms = [];
let bossDoors = [];
let coins = [];
let score = 0;
let lives = 3;
let level = localStorage.getItem('playerLevel') ? parseInt(localStorage.getItem('playerLevel')) : 1;
const gravity = 0.5;
const maxLevels = 5;
let movingLeft = false, movingRight = false;
let currentDirection = 1;
let currentPowerUp = null;
let powerUpTimer = 0;
let gameScrollPosition = 0;
const bossScoreThreshold = 1500;
const dialogues = [
"Player: Hey friend! What a nice day for an adventure!",
"Friend: Indeed! Maybe we should explore the caves.",
"Player: What's that over there? Is it the King?",
"King: Haha, I've found you! You're coming with me!",
"Friend: Player, help me!"
];
let dialogueIndex = 0;
let boss = null;
let bossHealth = 100;
let bossShielded = true;
let bossPowerObtained = false;
let bossFightActive = false;
const allPowerUpTypes = [
"super-speed", "invincibility", "teleportation", "time-freeze",
"gravity-reversal", "reflective-shield", "double-shot", "extra-life",
"score-boost", "mega-jump", "ice", "fire", "levitate", "hypno", "shield",
"regeneration", "ghost", "magnet", "invisibility", "freeze", "clone",
"shockwave", "energy", "shrink", "grow", "heal", "boss-power-up",
"speed-bullet", "rapid-fire", "spike", "anti-gravity", "energy-blast",
"light-speed", "blazing-trail", "sonic-wave", "armor", "telekinetic",
"camouflage", "dimension-shift", "energy-drain", "mind-control",
"hologram"
];
window.addEventListener('keydown', handleKeydown);
window.addEventListener('keyup', handleKeyup);
function handleKeydown(e) {
switch (e.key) {
case 'ArrowLeft':
movingLeft = true;
currentDirection = -1;
break;
case 'ArrowRight':
movingRight = true;
currentDirection = 1;
break;
case 'ArrowUp':
handleJump();
break;
case ' ': // Space bar for shooting
if (canShoot) {
shootBullet(currentDirection);
canShoot = false;
setTimeout(() => canShoot = true, 300);
}
break;
case 'z':
case 'Z': // Power-Up activation
if (currentPowerUp) { // Check if there is a power-up to use
usePowerUp();
} else if (bossPowerObtained) { // Charge if the boss power is obtained and no power-up is active
isCharging = true;
chargeTime = 0;
}
break;
case 'e':
case 'E':
interact(); // Trigger the interact function when 'E' is pressed
break;
}
}
function handleKeyup(e) {
switch (e.key) {
case 'ArrowLeft':
movingLeft = false;
break;
case 'ArrowRight':
movingRight = false;
break;
case 'z':
case 'Z':
if (bossPowerObtained && isCharging) {
isCharging = false;
shootLaserBlast(chargeTime);
}
break;
}
}
code
function handleJump() {
if (playerPositionY <= 0 || (isDoubleJumpEnabled && jumpCount < maxJumps)) {
playerVelocityY = playerJumpStrength;
jumpCount++;
isJumping = true;
}
}
function nextDialogue() {
if (dialogueIndex < dialogues.length - 1) {
dialogueIndex++;
dialoguePara.textContent = dialogues[dialogueIndex];
} else {
intro.style.display = 'none';
startGame();
}
}
function shootBullet(direction) {
const bullet = createBullet(direction);
bullets.push({ element: bullet, direction });
gameWorld.appendChild(bullet);
if (currentPowerUp === 'double-shot') {
const altBullet = createBullet(direction + 1);
bullets.push({ element: altBullet, direction });
gameWorld.appendChild(altBullet);
}
if (currentPowerUp === 'speed-bullet') {
const sideBullet1 = createBullet(direction + 6);
const sideBullet2 = createBullet(direction - 6);
bullets.push({ element: sideBullet1, direction });
bullets.push({ element: sideBullet2, direction });
gameWorld.appendChild(sideBullet1);
gameWorld.appendChild(sideBullet2);
}
}
function createBurst(x, y) {
const burst = document.createElement('div');
burst.classList.add('burst');
burst.style.left = x + 'px';
burst.style.bottom = y + 'px';
gameWorld.appendChild(burst);
setTimeout(() => burst.remove(), 500);
}
function summonAllies() {
for (let i = 0; i < 3; i++) {
let ally = createElement('ally', [], parseInt(player.style.left) + (i * 30));
ally.style.bottom = player.style.bottom;
gameWorld.appendChild(ally);
function removeElement(el, array, index, scoreValue) {
el.remove();
array.splice(index, 1);
if (scoreValue) {
score += scoreValue;
updateDisplay();
}
}
function handleCollision(el, array, index, scoreValue, isPowerUp = false) {
if (el.classList.contains('coin')) {
score += 5;
updateDisplay();
} else if (isPowerUp) {
applyPowerUp(el);
} else if (el.classList.contains('boss-door') && score >= level * bossScoreThreshold) {
interactMessage.textContent = "Press 'E' to enter boss door.";
interactMessage.style.display = checkCollision(player, el) ? 'block' : 'none';
if (checkCollision(player, el) && playerPositionX >= parseInt(el.style.left)) {
openBossHallway();
}
} else if (el.classList.contains('enemy') || el.classList.contains('obstacle')) {
reduceLives();
}
removeElement(el, array, index, scoreValue);
}
function applyPowerUp(el) {
if (currentPowerUp || currentPowerUp === 'boss-power-up') return;
const type = el.getAttribute('data-type');
if (type === 'boss-power-up') {
grantBossPowerUp();
} else {
currentPowerUp = type;
let duration = 10;
activatePowerUp(type);
powerUpTimer = duration;
const powerUpInterval = setInterval(() => {
powerUpTimer--;
if (powerUpTimer <= 0) {
clearInterval(powerUpInterval);
resetPowerUp();
}
updateDisplay();
}, 1000);
}
displayPowerUpMessage(type);
}
function activatePowerUp(type) {
switch (type) {
case 'super-speed':
player.style.backgroundColor = 'lime';
playerMaxSpeed = 8;
break;
case 'invincibility':
player.style.backgroundColor = 'gold';
PlayerInvincibility();
break;
case 'teleportation':
teleportPlayer();
break;
case 'time-freeze':
activateRegenerativeTime();
break;
case 'gravity-reversal':
toggleGravity();
break;
case 'reflective-shield':
activateReflectiveShield();
break;
case 'double-shot':
enableDoubleShot();
break;
case 'extra-life':
gainExtraLife();
break;
case 'score-boost':
boostScore();
break;
case 'mega-jump':
activateMegaJump();
break;
case 'energy-blast':
activateEnergyBlast();
break;
case 'light-speed':
activateLightSpeed();
break;
case 'blazing-trail':
activateBlazingTrail();
break;
case 'sonic-wave':
activateSonicWave();
break;
case 'armor':
activateArmor();
break;
case 'telekinetic':
activateTelekinetic();
break;
case 'camouflage':
activateCamouflage();
break;
case 'dimension-shift':
activateDimensionShift();
break;
case 'energy-drain':
activateEnergyDrain();
break;
case 'mind-control':
activateMindControl();
break;
case 'hologram':
activateHologram();
break;
default:
player.style.backgroundColor = getPowerUpColor(type);
break;
}
}
let timeFrozen = false; // Track if time is frozen
function activateRegenerativeTime() {
if (timeFrozen) return; // Prevent multiple activations
code
timeFrozen = true; // Freeze time
// Stop movement of all enemies and blocks
enemies.forEach(enemy => enemy.style.left = enemy.style.left); // No movement
obstacles.forEach(obstacle => obstacle.style.left = obstacle.style.left); // No movement
const initialPlayerPositionX = playerPositionX; // Remember the player's initial position
const initialPlayerPositionY = playerPositionY; // Remember the player's initial position
// Allow the player to move freely during this time
window.addEventListener('keydown', allowPlayerMovement);
// Reset after 10 seconds
setTimeout(() => {
timeFrozen = false; // Unfreeze time
window.removeEventListener('keydown', allowPlayerMovement); // Stop allowing free movement of player
// Reset any positions or states if necessary
playerPositionX = initialPlayerPositionX; // Reset player position if needed
playerPositionY = initialPlayerPositionY; // Reset player position if needed
}, 10000); // 10 seconds
}
function allowPlayerMovement(e) {
switch (e.key) {
case 'ArrowLeft':
playerPositionX -= playerMaxSpeed;
player.style.left = playerPositionX + 'px';
break;
case 'ArrowRight':
playerPositionX += playerMaxSpeed;
player.style.left = playerPositionX + 'px';
break;
// Add other player movement keys as necessary
}
}
function PlayerInvincibility() {
// Check if the player collides with a block
const blocks = document.querySelectorAll('enemy'); // Assuming blocks have the class 'block'
blocks.forEach(block => {
if (checkCollision(player, block)) {
block.remove(); // Break and remove the block
// Player does not take damage from the block
}
});
code
// Check for collision with enemies
enemies.forEach((enemy, index) => {
if (checkCollision(player, enemy)) {
if (!isInvincible) { // Only reduce lives if not invincible
if (extraLives < 3) {
extraLives++; // Grant an extra life
updateDisplay(); // Update the display with new life count
displayMessage(`Extra life granted! Total extra lives: ${extraLives}`);
} else {
lives--; // Deduct a life if max extra lives are reached
if (lives <= 0) {
endGame(false); // End the game if no lives remain
}
}
}
}
});
let consecutiveJumps = 0; // Initialize a variable to track consecutive jumps
const maxJumpCount = 3; // Maximum number of normal jumps before triggering a mega jump
const megaJumpMultiplier = 1.5; // Multiplier for the mega jump
function activateMegaJump() {
if (consecutiveJumps < maxJumpCount) {
// Perform a normal jump if within the max jump limit
playerVelocityY = playerJumpStrength; // Regular jump value
consecutiveJumps++; // Increment consecutive jumps
} else {
// Trigger a mega jump if max jump limit has been reached
playerVelocityY = playerJumpStrength * megaJumpMultiplier; // Apply mega jump
consecutiveJumps = 0; // Reset consecutive jumps to 0 after a mega jump
}
isJumping = true; // Set the jumping status to true
}
// Call this function whenever the player lands to reset the consecutive jumps count
function checkLanding() {
if (playerPositionY <= 0) { // Assuming ground level is at y = 0
consecutiveJumps = 0; // Reset consecutive jumps when landing
}
}
function activateBlazingTrail() {
let lives = 10; // Initialize lives
const maxLives = 10; // Maximum number of lives
code
// Set a timeout to reset lives after 10 seconds
setTimeout(() => {
lives = 10; // Reset lives back to 10
updateDisplay(); // Update the display
}, 10000); // 10 seconds
const trailInterval = setInterval(() => {
const trail = document.createElement('div');
trail.className = 'bullet';
trail.style.left = (playerPositionX + player.offsetWidth / 2) + 'px';
trail.style.bottom = (playerPositionY + player.offsetHeight / 2) + 'px';
trail.style.backgroundColor = 'orange';
gameWorld.appendChild(trail);
// Check collision with blocks (assuming blocks have class 'block')
document.querySelectorAll('.block').forEach(block => {
if (checkCollision(trail, block)) {
// Create burst effect
const burst = document.createElement('div');
burst.className = 'burst'; // The CSS class for the burst effect
burst.style.left = block.style.left; // Position it at the block's position
burst.style.bottom = block.style.bottom; // Position it at the block's position
gameWorld.appendChild(burst);
setTimeout(() => burst.remove(), 500); // Remove burst after 0.5 seconds
block.remove(); // Remove the block
lives = Math.min(lives + 1, maxLives); // Increase lives (up to 10)
updateDisplay(); // Update the life display
}
});
setTimeout(() => trail.remove(), 500); // Remove the trail after 0.5 seconds
}, 100); // The interval for creating the trails
// Clear the interval after 5 seconds
setTimeout(() => clearInterval(trailInterval), 5000);
}
function activateSonicWave() {
if (waveCooldown) return; // Prevent activation if already on cooldown
waveCooldown = true; // Set cooldown to prevent further activation
code
const wave = document.createElement('div');
wave.className = 'wave'; // Class for wave styling
wave.style.left = playerPositionX + 'px'; // Start at player's position
wave.style.bottom = (playerPositionY - 50) + 'px'; // Position just below player
wave.style.backgroundColor = 'cyan'; // Wave color
wave.style.width = '100px'; // Width of the wave
wave.style.height = '100px'; // Height of the wave
gameWorld.appendChild(wave);
let destroyedBlocks = 0; // Track how many blocks have been destroyed
// Move the wave forward quickly
let waveInterval = setInterval(() => {
wave.style.left = (parseInt(wave.style.left) + 20) + 'px'; // Move wave to the right
// Check for collision with blocks
document.querySelectorAll('obstacle').forEach(block => {
if (checkCollision(wave, block) && destroyedBlocks < 3) { // Destroy only the next 3 blocks
const burst = document.createElement('div'); // Create burst effect
burst.className = 'burst';
burst.style.left = block.style.left;
burst.style.bottom = block.style.bottom;
gameWorld.appendChild(burst);
setTimeout(() => burst.remove(), 500); // Remove burst after half a second
block.remove(); // Remove the block
destroyedBlocks++; // Increment the destroyed block count
}
});
// Cleanup if wave goes off screen or after a certain time
if (parseInt(wave.style.left) > gameWorld.offsetWidth) {
clearInterval(waveInterval); // Stop moving the wave if it goes off screen
wave.remove(); // Remove the wave
resetWave(); // Reset block destruction count
}
}, 50); // Adjust speed of the wave as needed
// Remove wave after a brief time
setTimeout(() => {
clearInterval(waveInterval); // Clear the interval
wave.remove(); // Remove the wave
resetWave(); // Also reset after the effect finishes
}, 500); // Duration of wave effect
}
// Reset wave properties for potential future use
function resetWave() {
destroyedBlocks = 0; // Reset the number of destroyed blocks for future waves
waveCooldown = false; // Reset the cooldown so the wave can be activated again
}
function activateDimensionShift() {
// Change the background color to indicate the shift
gameWorld.style.backgroundColor = 'black';
code
// Select all blocks in the game world
const blocks = document.querySelectorAll('.block'); // Assuming blocks have the class 'block'
// Fade out each block
blocks.forEach(block => {
block.style.transition = 'opacity 1s'; // Set the transition for fading effect
block.style.opacity = '0'; // Start fading the block
// After the fade out, remove the block or disable it as needed
setTimeout(() => {
block.remove(); // Remove the block from the game world
}, 1000); // Match the timeout to the fade duration (1 second)
});
// Reset background color after a period
setTimeout(() => {
gameWorld.style.backgroundColor = ''; // Reset the background color after 5 seconds
}, 5000); // Keep the black background for 5 seconds
if (Math.sqrt(dx * dx + dy * dy) < 100) { // Check if within hypnotize range
if (!enemy.classList.contains('hypnotized')) {
enemy.classList.add('hypnotized');
enemy.style.backgroundColor = 'violet'; // Change color to indicate hypnotization
// Create a heal block when the enemy is hypnotized
const healBlock = document.createElement('div');
healBlock.className = 'heal-block'; // Class for heal block styling
healBlock.style.left = enemy.style.left; // Position it at the enemy's position
healBlock.style.bottom = enemy.style.bottom; // Same height as the enemy
healBlock.style.width = '30px';
healBlock.style.height = '30px';
healBlock.style.backgroundColor = 'green'; // Set heal block color
gameWorld.appendChild(healBlock); // Add to the game world
// Add event listener for healing when touched
healBlock.addEventListener('click', () => {
if (lives < maxLives) { // Check if player can gain a life
lives++; // Increment lives
healBlock.remove(); // Remove the heal block after interacting
updateDisplay(); // Update UI for lives
}
});
// Remove the original enemy after creating the heal block
enemy.remove();
}
}
});
function interact() {
if (checkCollision(player, friend)) {
activateFriendDialogue();
}
bossDoors.forEach(door => {
if (checkCollision(player, door)) {
if (score >= level * bossScoreThreshold) {
openBossHallway();
} else {
displayMessage("You need more score to enter the boss area!");
}
}
});
}
code
function openBossHallway() {
bossHallway.style.display = 'flex';
clearAllElements();
clearInterval(gameInterval);
}
function startBossFight() {
bossHallway.style.display = 'none';
triggerBossFight();
gameInterval = setInterval(gameLoop, 1000 / 60); // Ensure the game loop is running for updates
}
code
function incrementLevel() {
level++;
playerMaxSpeed = 5; // Reset speed back to normal
if (level > maxLevels) {
endGame(true);
} else {
localStorage.setItem('playerLevel', level);
updateDisplay();
resetGame();
levelIntro.style.display = 'flex';
switchLevelBackground();
levelText.textContent = `Level ${level}: New Challenges Await!`;
}
}
function switchLevelBackground() {
const backgrounds = ['#333', '#1E90FF', '#228B22', '#E0FFFF', '#B22222'];
gameContainer.style.backgroundColor = backgrounds[(level - 1) % backgrounds.length];
}
function continueGame() {
levelIntro.style.display = 'none';
gameInterval = setInterval(gameLoop, 1000 / 60);
}
function gameLoop() {
if (!isPaused) {
updatePlayerPosition(); // Ensure this is called
spawnEntities(); // You may want to stop spawning entities during the boss fight
moveElements(); // This is optional, depending on your design
checkScoreForLevelTransition(); // This can also be conditional
}
}
function endGame(isWin = false) {
clearInterval(gameInterval);
if (!isWin) {
// Reset boss health if the game is lost
bossHealth = 100; // Reset to initial boss health
}
gameOverScreen.style.display = 'flex';
gameOverScreen.innerHTML = <p>${isWin ? 'Congratulations! You won!' : 'Game Over!'}</p> <button onclick="restartGame()">Restart</button>;
}
code
function restartGame() {
gameOverScreen.style.display = 'none';
resetGame();
startLevel();
}
function triggerBossFight() {
bossFightScreen.style.display = 'flex';
setTimeout(() => {
bossFightScreen.style.display = 'none';
startBossLogic();
}, 2000);
}
function startBossLogic() {
bossFightActive = true;
boss = createElement('boss', [], 600);
boss.style.bottom = '100px';
gameWorld.appendChild(boss);
displayBossHealth();
cycleBossAttacks(); // Start the attack pattern cycle
}
function cycleBossAttacks() {
if (bossHealth <= 0) return;
function bossEnemyBarrage() {
boss.style.animation = "boss-shake 1s infinite alternate"; // Boss shakes
code
let spawnCount = 0;
let spawnInterval = setInterval(() => {
if (spawnCount >= 10) { // Stops after 10 spawns
clearInterval(spawnInterval);
boss.style.animation = ""; // Stop shaking
setTimeout(cycleBossAttacks, 3000); // Cooldown before next attack
return;
}
let enemy = createElement('enemy', enemies, Math.random() * gameContainer.offsetWidth);
enemy.style.bottom = "400px"; // Start from top
let fallSpeed = 8;
let fallInterval = setInterval(() => {
enemy.style.bottom = (parseInt(enemy.style.bottom) - fallSpeed) + "px";
if (parseInt(enemy.style.bottom) <= 0) {
enemy.style.bottom = "0px"; // Stop at ground level
clearInterval(fallInterval);
}
// Check for collision with player
if (checkCollision(player, enemy)) {
reduceLives();
enemy.remove();
clearInterval(fallInterval);
}
}, 50);
spawnCount++;
}, 500); // Spawn every half second
}
function bossTargetSlam() {
let slamCount = 0;
boss.style.animation = "boss-shake 0.5s infinite alternate";
code
let followInterval = setInterval(() => {
if (slamCount >= 3) {
clearInterval(followInterval);
boss.style.animation = "";
boss.style.bottom = "100px"; // Reset position after all slams
setTimeout(cycleBossAttacks, 3000);
return;
}
// Position the boss over the player first
boss.style.left = player.style.left;
boss.style.bottom = "400px"; // Start at high position
let warningLine = document.createElement('div');
warningLine.classList.add('warning-line');
warningLine.style.left = player.style.left;
warningLine.style.bottom = "0px";
warningLine.style.width = "30px";
warningLine.style.height = "5px";
warningLine.style.backgroundColor = "red";
warningLine.style.position = "absolute";
gameWorld.appendChild(warningLine);
setTimeout(() => {
warningLine.remove();
// Slam down
boss.style.bottom = "100px"; // Slam down position
if (checkCollision(boss, player)) {
reduceLives(); // Deal damage to the player
}
createBurst(parseInt(boss.style.left) + boss.offsetWidth / 2, 30); // Create burst effect
// Check collision with player
if (checkCollision(boss, player)) {
reduceLives(); // Deal damage to the player
}
// Move the boss back up after the slam
setTimeout(() => {
boss.style.bottom = "0px"; // Move back up after slam
}, 500);
}, 1000); // Time until the slam occurs
slamCount++;
}, 2000); // Time interval between slams
}
function bossExplosionRain() {
boss.style.animation = "boss-shake 1s infinite alternate";
code
let dropCount = 0;
let dropInterval = setInterval(() => {
if (dropCount >= 10) {
clearInterval(dropInterval);
boss.style.animation = "";
setTimeout(cycleBossAttacks, 3000); // Cooldown before next attack
return;
}
// Randomize the X position based on the player's position
let playerPositionX = parseInt(player.style.left);
let explosionBlock = document.createElement('div'); // Corrected to use document.createElement
explosionBlock.classList.add('explosive-block'); // Add a class if you want to style it later
explosionBlock.style.position = "absolute"; // Important for positioning
explosionBlock.style.left = (playerPositionX + Math.random() * 30 - 15) + "px"; // Randomize the horizontal position
explosionBlock.style.bottom = "400px"; // Start high
explosionBlock.style.width = "30px"; // Width of the falling block
explosionBlock.style.height = "10px"; // Height of the falling block
explosionBlock.style.backgroundColor = "red"; // Color of the falling block
gameWorld.appendChild(explosionBlock);
let fallSpeed = 5; // Speed of fall
let fallInterval = setInterval(() => {
explosionBlock.style.bottom = (parseInt(explosionBlock.style.bottom) - fallSpeed) + "px";
if (parseInt(explosionBlock.style.bottom) <= 0) {
createBurst(parseInt(explosionBlock.style.left), 0); // Create burst effect
if (checkCollision(explosionBlock, player)) {
reduceLives(); // Reduce lives if hit
}
explosionBlock.remove(); // Remove block once it hits ground
clearInterval(fallInterval);
}
}, 50); // Update every 50ms
dropCount++;
}, 1000); // Drop every second
}
function bossNewPower() {
let shotsFired = 0;
const maxShots = 15;
const shotCooldown = 800; // 0.8 seconds between shots
code
const shootInterval = setInterval(() => {
if (shotsFired >= maxShots) {
clearInterval(shootInterval);
// Introduce a delay before invoking the next attack or phase
setTimeout(() => {
cycleBossAttacks(); // Call back the attack cycle function
}, 2000); // 2 seconds for any cooling down or animation effect
return; // Stop firing after maximum shots
}
// Calculate the boss's and player's positions
const bossX = parseInt(boss.style.left) + boss.offsetWidth / 2; // Middle of the boss
const bossY = parseInt(boss.style.bottom) + 30; // Just above the boss
const playerX = parseInt(player.style.left) + player.offsetWidth / 2; // Middle of the player
const playerY = parseInt(player.style.bottom); // Bottom of the player
// Calculate the direction vector
const dx = playerX - bossX;
const dy = playerY - bossY;
const distance = Math.sqrt(dx * dx + dy * dy);
const velocity = 10; // Speed of the projectile
// Create a projectile
const projectile = document.createElement('div');
projectile.classList.add('boss-projectile');
projectile.style.width = '10px';
projectile.style.height = '10px';
projectile.style.backgroundColor = 'orange';
projectile.style.position = 'absolute';
projectile.style.left = `${bossX - 5}px`; // Center it
projectile.style.bottom = `${bossY}px`; // Start just above the boss
gameWorld.appendChild(projectile);
let projectileInterval = setInterval(() => {
// Move projectile towards the player
const moveX = (dx / distance) * velocity; // Calculate x movement
const moveY = (dy / distance) * velocity; // Calculate y movement
projectile.style.left = (parseInt(projectile.style.left) + moveX) + 'px';
projectile.style.bottom = (parseInt(projectile.style.bottom) + moveY) + 'px';
// Check collision
if (checkCollision(player, projectile)) {
reduceLives(); // Reduce player lives on hit
projectile.remove(); // Remove projectile on hit
clearInterval(projectileInterval);
}
// Remove projectile if it goes off-screen
if (parseInt(projectile.style.bottom) > gameContainer.offsetHeight ||
parseInt(projectile.style.left) < 0 ||
parseInt(projectile.style.left) > gameContainer.offsetWidth) {
projectile.remove(); // Remove off-screen
clearInterval(projectileInterval);
}
}, 50); // Update every 50ms
shotsFired++;
}, shotCooldown); // Fire every 0.8 seconds
}
code
function displayBossHealth() {
bossHealthBar.style.display = 'block';
updateBossHealth();
}
function updateBossHealth() {
bossHealthDisplay.style.width = `${bossHealth}%`;
}
function spawnBossEnemies() {
if (bossShielded) {
for (let i = 0; i < 2; i++) {
const enemy = createElement('enemy', enemies, parseInt(boss.style.left) + (i * 50));
enemy.style.bottom = `${Math.random() * 250}px`;
}
}
}
function spawnBossBullets() {
const bullet = createBullet();
bullet.style.left = parseInt(boss.style.left) + 'px';
bullet.style.bottom = parseInt(boss.style.bottom) + 30 + 'px';
bullet.style.backgroundColor = 'orange';
gameWorld.appendChild(bullet);
bullets.push({ element: bullet, direction: -1 });
}
function checkBossHit() {
if (!boss || bossShielded) return; // Stop damaging if boss is shielded
code
bullets.forEach((bullet, bulletIndex) => {
if (checkCollision(bullet.element, boss)) {
bossHealth -= 2; // Decrement boss health
updateBossHealth();
bullet.element.remove();
bullets.splice(bulletIndex, 1);
// Check if the boss is defeated
if (bossHealth <= 0) {
displayMessage("Boss defeated!");
onBossDefeated(); // Trigger boss defeat logic
}
}
});
}
function onBossDefeated() {
bossHealthBar.style.display = 'none';
displayMessage("Noooo!");
friend.style.left = '400px';
friend.style.bottom = '100px';
friend.style.display = 'block';
interactMessage.textContent = "Press 'E' to interact with your friend!";
interactMessage.style.display = 'block';
code
setTimeout(() => {
// Move player back to doorway
player.style.left = "50px";
player.style.bottom = "0px";
setTimeout(() => {
activateBossPower();
level = 2; // Reset to Level 1
resetGame();
startLevel(); // Restart the game
}, 2000);
}, 3000);
function moveChargingEnemies() {
enemies.forEach((enemy, index) => {
if (enemy.classList.contains('charging-enemy')) {
let chargeTime = parseInt(enemy.getAttribute('data-charge'));
code
if (chargeTime < 60) {
// Charging phase (fading in/out glow)
enemy.setAttribute('data-charge', chargeTime + 1);
} else {
// Fully Charged (Solid Red Outline + Charging Forward)
enemy.classList.remove('charging-prep');
enemy.classList.add('charging-active');
enemy.style.left = (parseInt(enemy.style.left) - 6) + 'px';
// Create a bright red trail
createChargeTrail(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
}
// Check collision with player
if (checkCollision(player, enemy)) {
createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom)); // Impact explosion
reduceLives();
removeElement(enemy, enemies, index, 0);
}
// Remove if out of bounds
if (parseInt(enemy.style.left) < gameScrollPosition - enemy.offsetWidth) {
removeElement(enemy, enemies, index, 30);
}
}
});
The provided code is an HTML document that outlines a web-based adventure game. The game includes various components, such as a player character, obstacles, enemies, power-ups, and a boss fight. Below is a summary of the key elements and functions within the script:
Key Elements:
HTML Structure:
The game is contained within a div with id="game-container" which houses the game world and various UI elements like score, lives, level, and timer displays.
Styling:
There are numerous CSS styles defined for different game elements, including animations for character idle motion, bullet trails, coins, and explosions.
Game Features:
Player Movement:
The player can move left or right using arrow keys, jump with the arrow up key, and shoot projectiles with the space bar.
Collision Detection:
The game checks for collisions between the player and various game elements (enemies, obstacles, power-ups, etc.) using the checkCollision function, which verifies the boundaries of the character's rectangles.
Enemy Types:
The game includes multiple enemy types, each with unique behaviors, including flying enemies, charging enemies, and stealth enemies.
Power-Ups:
Players can collect power-ups that grant temporary abilities, such as increased speed, invincibility, and double shots. The behaviors are managed using a switch-case statement within the activatePowerUp function.
Boss Mechanics:
The game features a boss with its health bar, attack patterns (barrage, slam, explosive rain), and unique interactions with the player.
Leveling System:
Players transition between levels, with increasing challenges and new enemies. The game keeps track of score and lives, restarting the game upon failure.
Animation Effects:
The script includes several animations for visual effects, such as charging and boss attacks using CSS keyframes and JavaScript.
Interactivity:
The game allows for interactive storytelling through dialogue with a friend character and various UI messages to enhance gameplay experience.
Additional Notes:
The game is designed to be played in a web browser and makes use of JavaScript for dynamic interactions and animations.
The structure is modular, allowing easy addition or modification of game features, enemies, and power-ups.
The use of local storage helps retain player's progress across different game sessions.
Overall, the script presents a complex and interactive web-based game that combines platforming elements with adventure gameplay mechanics, significant enemy variety, and connectivity to user feedback through power-ups and obstacle interactions.