<script>
const gameContainer = document.getElementById('game-container');
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 splashScreen = document.getElementById('splash-screen');
const bossFightScreen = document.getElementById('boss-fight');
const gameOverScreen = document.getElementById('game-over');
let playerPositionX = 50;
let playerPositionY = 0;
let playerVelocityX = 0;
let playerVelocityY = 0;
let playerMaxSpeed = 5;
let isJumping = false;
let isPaused = false;
let canShoot = true;
let gameInterval;
let obstacles = [];
let enemies = [];
let bullets = [];
let powerUps = [];
let collectibles = [];
let platforms = [];
let levelDoors = [];
let score = 0;
let lives = 3;
let level = 1;
let secretBossActive = false;
let currentPowerUp = null;
let powerUpTimer = 0;
const gravity = 0.5;
const jumpStrength = 12;
const maxLevels = 5;
let movingLeft = false, movingRight = false;
let levitatedEnemy = null;
document.addEventListener('keydown', handleKeydown);
document.addEventListener('keyup', handleKeyup);
function handleKeydown(e) {
switch (e.key) {
case 'ArrowLeft':
movingLeft = true;
break;
case 'ArrowRight':
movingRight = true;
break;
case 'ArrowUp':
if (!isJumping) jump();
break;
case ' ':
if (canShoot) {
shootBullet();
canShoot = false;
setTimeout(() => canShoot = true, 200);
}
break;
case 'z':
case 'Z':
usePowerUp();
break;
case 'e':
case 'E':
interact();
break;
case 'p':
case 'P':
togglePause();
break;
}
}
function handleKeyup(e) {
switch (e.key) {
case 'ArrowLeft':
movingLeft = false;
break;
case 'ArrowRight':
movingRight = false;
break;
}
}
function jump() {
if (!isJumping) {
playerVelocityY = jumpStrength;
isJumping = true;
}
}
function shootBullet() {
const bullet = document.createElement('div');
bullet.classList.add('bullet');
const bulletDirection = movingRight ? 1 : -1;
bullets.push({ element: bullet, direction: bulletDirection });
bullet.style.left = (bulletDirection > 0 ? playerPositionX + player.offsetWidth : playerPositionX) + 'px';
bullet.style.bottom = (playerPositionY + player.offsetHeight / 2) + 'px';
gameContainer.appendChild(bullet);
}
function startGame() {
instructions.style.display = 'none';
levelIntro.style.display = 'flex';
levelText.textContent = `Level 1: Get Ready for Adventure!`;
resetGame();
}
function startLevel() {
levelIntro.style.display = 'none';
gameInterval = setInterval(gameLoop, 1000 / 60);
}
function resetGame() {
score = 0;
lives = 3;
level = 1;
playerPositionX = 50;
playerPositionY = 0;
playerVelocityX = 0;
playerVelocityY = 0;
isJumping = false;
clearAllElements();
updateDisplay();
}
function updateDisplay() {
scoreDisplay.textContent = `Score: ${score}`;
livesDisplay.textContent = `Lives: ${lives}`;
levelDisplay.textContent = `Level: ${level}`;
timerDisplay.textContent = `Timer: ${powerUpTimer}`;
}
function updatePlayerPosition() {
if (movingLeft) {
playerVelocityX = -playerMaxSpeed;
} else if (movingRight) {
playerVelocityX = playerMaxSpeed;
} else {
playerVelocityX = 0;
}
playerPositionX += playerVelocityX;
playerPositionX = Math.max(0, Math.min(gameContainer.offsetWidth - player.offsetWidth, playerPositionX));
player.style.left = playerPositionX + 'px';
let onPlatform = false;
platforms.forEach(platform => {
if (checkCollision(player, platform) && playerVelocityY < 0) {
playerPositionY = parseInt(platform.style.bottom) + platform.offsetHeight;
playerVelocityY = 0;
isJumping = false;
onPlatform = true;
}
});
if (!onPlatform || isJumping || playerPositionY > 0) {
playerVelocityY -= gravity;
playerPositionY += playerVelocityY;
if (playerPositionY <= 0) {
playerPositionY = 0;
isJumping = false;
}
}
player.style.bottom = playerPositionY + 'px';
}
function spawnEntities() {
if (!isPaused) {
if (Math.random() < 0.01) spawnObstacle();
if (Math.random() < 0.005) spawnEnemy();
if (Math.random() < 0.002 && !currentPowerUp) spawnPowerUps();
if (Math.random() < 0.002) spawnCollectible();
if (Math.random() < 0.001) spawnPlatform();
if (Math.random() < 0.001) spawnEndDoor();
}
}
function moveElements() {
moveArray(obstacles, 2, 15);
moveArray(enemies, 1, 30);
moveArray(powerUps, 2, 0, true);
moveArray(collectibles, 1, 5);
moveArray(platforms, 1, 0);
moveArray(levelDoors, 0, 0);
moveBullets();
}
function spawnObstacle() {
createElement('obstacle', obstacles, gameContainer.offsetWidth);
}
function spawnEnemy() {
createElement('enemy', enemies, gameContainer.offsetWidth);
}
function spawnPowerUps() {
const powerUpTypes = ['ice', 'fire', 'levitate', 'hypno'];
const type = powerUpTypes[Math.floor(Math.random() * powerUpTypes.length)];
const powerUp = createElement(`power-up-${type}`, powerUps, gameContainer.offsetWidth, type);
powerUp.style.bottom = '0px';
}
function spawnCollectible() {
const collectible = createElement('collectible', collectibles, gameContainer.offsetWidth);
collectible.style.bottom = (Math.random() * 100 + 50) + 'px';
}
function spawnPlatform() {
const platform = createElement('platform', platforms, gameContainer.offsetWidth);
platform.style.bottom = Math.floor(Math.random() * 200 + 100) + 'px';
}
function spawnEndDoor() {
if (Math.random() < 0.2) {
const endDoor = createElement('end-door', levelDoors, gameContainer.offsetWidth);
endDoor.style.bottom = '0px';
}
}
function createElement(className, array, leftPosition, type = '') {
const element = document.createElement('div');
element.classList.add(className);
if (type) element.setAttribute('data-type', type);
element.style.left = leftPosition + 'px';
gameContainer.appendChild(element);
array.push(element);
return element;
}
function moveArray(array, speed, scoreValue, isPowerUp = false) {
array.forEach((el, index) => {
if (speed > 0 && !el.classList.contains('frozen')) {
el.style.left = (parseInt(el.style.left) - Math.max(speed, 1)) + 'px';
}
if (parseInt(el.style.left) < -el.offsetWidth) {
removeElement(el, array, index, scoreValue);
} else if (checkCollision(player, el)) {
handleCollision(el, array, index, scoreValue, isPowerUp);
}
});
}
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 (isPowerUp) {
applyPowerUp(el);
} else if (el.classList.contains('end-door')) {
triggerEndOfLevel();
} else if (el.classList.contains('enemy') || el.classList.contains('obstacle')) {
reduceLives();
}
removeElement(el, array, index, scoreValue);
}
function moveBullets() {
[{ bullets: bullets, attackable: enemies }, { bullets: [], attackable: [player] }]
.forEach(group => {
group.bullets.forEach((bulletObj, index) => {
const bullet = bulletObj.element;
bullet.style.left = (parseInt(bullet.style.left) + (bulletObj.direction * 5)) + 'px';
if (parseInt(bullet.style.left) > gameContainer.offsetWidth || parseInt(bullet.style.left) < 0) {
bullet.remove();
group.bullets.splice(index, 1);
}
group.attackable.forEach((entity, entityIndex) => {
if (checkCollision(bullet, entity)) {
bullet.remove();
group.bullets.splice(index, 1);
if (entity !== player) {
entity.remove();
enemies.splice(entityIndex, 1);
score += 10;
} else {
reduceLives();
}
updateDisplay();
}
});
});
});
}
function applyPowerUp(el) {
if (currentPowerUp) return;
const type = el.getAttribute('data-type');
currentPowerUp = type;
let duration;
switch (type) {
case 'ice':
player.style.backgroundColor = 'blue';
duration = 30;
break;
case 'fire':
player.style.backgroundColor = 'red';
duration = 25;
break;
case 'levitate':
player.style.backgroundColor = 'green';
duration = 20;
break;
case 'hypno':
player.style.backgroundColor = 'pink';
duration = 25;
break;
case 'boss':
player.style.background = 'linear-gradient(90deg, red, orange, yellow, green, blue, indigo, violet)';
player.style.animation = 'rainbow 3s infinite linear';
duration = 25;
break;
default:
player.style.backgroundColor = '#4CAF50';
duration = 0;
}
powerUpTimer = duration;
const powerUpInterval = setInterval(() => {
powerUpTimer--;
updateDisplay();
if (powerUpTimer <= 0) {
clearInterval(powerUpInterval);
resetPowerUp();
}
}, 1000);
}
function resetPowerUp() {
currentPowerUp = null;
player.style.backgroundColor = '#4CAF50';
player.style.background = '';
player.style.animation = '';
}
function usePowerUp() {
if (!currentPowerUp) return;
switch (currentPowerUp) {
case 'ice':
shootIce();
break;
case 'fire':
shootFire();
break;
case 'levitate':
useLevitate();
break;
case 'hypno':
shootHypno();
break;
case 'boss':
performBossPowers();
break;
default:
break;
}
}
function shootIce() {
const iceBullet = document.createElement('div');
iceBullet.classList.add('ice');
iceBullet.style.left = playerPositionX + 'px';
iceBullet.style.bottom = (playerPositionY + player.offsetHeight / 2) + 'px';
gameContainer.appendChild(iceBullet);
const iceBulletObj = { element: iceBullet, direction: movingRight ? 1 : -1 };
animateBullet(iceBulletObj, 5, (target) => {
if (target.classList.contains('obstacle')) {
target.classList.add('frozen');
target.style.backgroundColor = '#00f';
}
});
}
function shootFire() {
const fireBullet = document.createElement('div');
fireBullet.classList.add('fire');
fireBullet.style.left = playerPositionX + 'px';
fireBullet.style.bottom = (playerPositionY + player.offsetHeight / 2) + 'px';
gameContainer.appendChild(fireBullet);
const fireBulletObj = { element: fireBullet, direction: movingRight ? 1 : -1 };
animateBullet(fireBulletObj, 5, (target) => {
if (target.classList.contains('obstacle')) {
target.style.transition = 'opacity 0.5s';
target.style.opacity = '0';
setTimeout(() => target.remove(), 500);
}
});
}
function useLevitate() {
if (levitatedEnemy) {
const levitatedElement = document.createElement('div');
levitatedElement.classList.add('bullet');
levitatedElement.style.left = levitatedEnemy.style.left;
levitatedElement.style.bottom = levitatedEnemy.style.bottom;
levitatedElement.style.backgroundColor = '#0f0';
gameContainer.appendChild(levitatedElement);
animateBullet({ element: levitatedElement, direction: 1 }, 10, (target) => {
if (target.classList.contains('obstacle')) {
target.remove();
}
});
levitatedEnemy.remove();
levitatedEnemy = null;
} else {
const nearestEnemy = enemies.reduce((prev, curr) => {
const prevDistance = Math.hypot(playerPositionX - parseInt(prev.style.left), playerPositionY - parseInt(prev.style.bottom));
const currDistance = Math.hypot(playerPositionX - parseInt(curr.style.left), playerPositionY - parseInt(curr.style.bottom));
return (currDistance < prevDistance ? curr : prev);
}, enemies[0]);
if (nearestEnemy) {
levitatedEnemy = nearestEnemy;
levitatedEnemy.style.transform = 'translateY(-20px)';
}
}
}
function shootHypno() {
const hypnoBullet = document.createElement('div');
hypnoBullet.classList.add('hypno');
hypnoBullet.style.left = playerPositionX + 'px';
hypnoBullet.style.bottom = (playerPositionY + player.offsetHeight / 2) + 'px';
gameContainer.appendChild(hypnoBullet);
const hypnoBulletObj = { element: hypnoBullet, direction: movingRight ? 1 : -1 };
animateBullet(hypnoBulletObj, 5, (target) => {
if (target.classList.contains('enemy')) {
target.style.transform = 'scaleX(-1)';
moveArray([target], -1, 0);
}
});
}
function animateBullet(bulletObj, speed, impactCallback) {
const bulletInterval = setInterval(() => {
const bullet = bulletObj.element;
bullet.style.left = (parseInt(bullet.style.left) + (bulletObj.direction * speed)) + 'px';
if (parseInt(bullet.style.left) > gameContainer.offsetWidth || parseInt(bullet.style.left) < 0) {
bullet.remove();
clearInterval(bulletInterval);
} else {
obstacles.forEach(target => {
if (checkCollision(bullet, target)) {
impactCallback(target);
bullet.remove();
clearInterval(bulletInterval);
}
});
}
}, 1000 / 60);
}
function performBossPowers() {
const laser = document.createElement('div');
laser.classList.add('bullet');
laser.style.left = playerPositionX + 'px';
laser.style.bottom = (playerPositionY + player.offsetHeight / 2) + 'px';
laser.style.width = '5px';
laser.style.height = gameContainer.offsetHeight + 'px';
laser.style.backgroundColor = '#f00';
obstacles.forEach(obstacle => obstacle.remove());
obstacles = [];
gameContainer.appendChild(laser);
}
function reduceLives() {
lives--;
updateDisplay();
if (lives <= 0) endGame();
}
function checkCollisionWithClass(entity, className) {
return [...document.querySelectorAll(`.${className}`)].some(el => checkCollision(entity, el));
}
function checkCollision(rect1, rect2) {
const rect1Bounds = rect1.getBoundingClientRect();
const rect2Bounds = rect2.getBoundingClientRect();
return !(rect1Bounds.top > rect2Bounds.bottom || rect1Bounds.bottom < rect2Bounds.top ||
rect1Bounds.left > rect2Bounds.right || rect1Bounds.right < rect2Bounds.left);
}
function togglePause() {
if (isPaused) {
splashScreen.style.display = 'none';
gameInterval = setInterval(gameLoop, 1000 / 60);
isPaused = false;
} else {
clearInterval(gameInterval);
splashScreen.style.display = 'flex';
isPaused = true;
}
}
function clearAllElements() {
[
obstacles, enemies, bullets.map(b => b.element), powerUps,
collectibles, platforms, levelDoors
].forEach(arr => clearSpecificElements(arr));
}
function clearSpecificElements(array) {
array.forEach(el => el.remove());
array.length = 0;
}
function interact() {
levelDoors.forEach((door) => {
if (checkCollision(player, door)) {
secretBossActive = true;
triggerSecretBoss();
}
});
}
function incrementLevel() {
level++;
if (level > maxLevels) {
endGame(true);
} else {
updateDisplay();
levelIntro.style.display = 'flex';
levelText.textContent = `Level ${level}: New Challenges Await!`;
switch (level) {
case 2:
gameContainer.style.transition = 'background-color 2s';
gameContainer.style.backgroundColor = '#004466';
break;
case 3:
gameContainer.style.backgroundColor = '#224422';
break;
case 4:
gameContainer.style.backgroundColor = '#555555';
break;
case 5:
gameContainer.style.backgroundColor = '#aaaaff';
break;
}
}
}
function showCutscene() {
splashScreen.style.display = 'flex';
setTimeout(() => continueGame(), 3000);
}
function continueGame() {
splashScreen.style.display = 'none';
incrementLevel();
gameInterval = setInterval(gameLoop, 1000 / 60);
}
function gameLoop() {
if (!isPaused) {
updatePlayerPosition();
spawnEntities();
moveElements();
moveBullets(); // Ensure this is called every frame
checkScoreForLevelTransition();
}
}
function endGame(isWin = false) {
clearInterval(gameInterval);
gameOverScreen.style.display = 'flex';
gameOverScreen.innerHTML = `<p>${isWin ? 'Congratulations! You won!' : 'Game Over!'}</p>
<button onclick="startGame()">Restart</button>`;
}
function triggerEndOfLevel() {
clearInterval(gameInterval);
splashScreen.style.display = 'flex';
setTimeout(() => {
splashScreen.style.display = 'none';
incrementLevel();
startLevel();
}, 3000);
}
function triggerSecretBoss() {
if (!secretBossActive) return;
bossFightScreen.style.display = 'flex';
setTimeout(() => {
bossFightScreen.style.display = 'none';
clearAllElements();
const boss = document.createElement('div');
boss.classList.add('boss');
boss.style.left = '300px';
boss.style.bottom = '100px';
gameContainer.appendChild(boss);
bosses.push(boss);
let bossKillCount = 0;
const bossInterval = setInterval(() => {
if (checkCollision(player, boss)) {
reduceLives();
}
const enemiesToShoot = 10;
if (enemiesToShoot > bossKillCount) {
spawnEnemy();
bossKillCount++;
}
}, 1000 / 60);
}, 2000);
}
function checkScoreForLevelTransition() {
if (score >= level * 1000) {
triggerEndOfLevel();
}
}
</script>