make it so this is fixed cuz powerups don't work when this is pressed
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 ' ':
if (canShoot) {
shootBullet(currentDirection);
canShoot = false;
setTimeout(() => canShoot = true, 300);
}
break;
case 'z':
case 'Z':
if (bossPowerObtained) {
isCharging = true;
chargeTime = 0;
} else {
usePowerUp();
}
break;
case 'e':
case 'E':
interact(); // Trigger the interact function when 'E' is pressed
break;
}
}
Assistant
To ensure that power-ups can still be used while the space bar is pressed (which is used for shooting), you need to manage the states more carefully. One approach is to allow the use of power-ups regardless of whether the space bar is pressed.
<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 = 1;
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 ' ':
if (canShoot) {
shootBullet(currentDirection);
canShoot = false;
setTimeout(() => canShoot = true, 300);
}
break;
case 'z':
case 'Z':
if (bossPowerObtained) {
isCharging = true;
chargeTime = 0;
} else {
usePowerUp();
}
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;
}
}
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 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!");
}
}
});
}
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
}
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 cycleBossAttacks() {
if (bossHealth <= 0) return;
bossAttacking = true;
bossShielded = true;
boss.classList.add('boss-shielded'); // Show shield effect
// Determine which attack phase to use based on current value
if (bossAttackPhase === 0) {
bossEnemyBarrage(); // First attack: barrage of enemies
} else if (bossAttackPhase === 1) {
bossTargetSlam(); // Second attack: target slam
} else if (bossAttackPhase === 2) {
bossExplosionRain(); // Third attack: explosion rain
} else if (bossAttackPhase === 3) {
bossNewPower(); // Fourth attack: rapid fire projectiles
}
setTimeout(() => {
bossShielded = false;
boss.classList.remove('boss-shielded'); // Remove shield effect
displayMessage("Boss shield is OFF! Attack now!");
}, 5000); // Boss is shielded temporarily after each attack
// Cycle through the attack phases
bossAttackPhase = (bossAttackPhase + 1) % 4; // Now cycling through 4 phases
}
function bossEnemyBarrage() {
boss.style.animation = "boss-shake 1s infinite alternate"; // Boss shakes
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";
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 = "30px"; // Slam down position
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 = "100px"; // 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";
let dropCount = 0;
let dropInterval = setInterval(() => {
if (dropCount >= 10) {
clearInterval(dropInterval);
boss.style.animation = "";
setTimeout(cycleBossAttacks, 3000); // Cooldown before next attack
return;
}
let explosionBlock = createElement('explosive-block', [], playerPositionX + Math.random() * 30 - 15);
explosionBlock.style.bottom = "400px"; // Start from the top
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;
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 = 10;
const shotCooldown = 1000; // 1 second between shots
let shootInterval = setInterval(() => {
if (shotsFired >= maxShots) {
clearInterval(shootInterval);
return; // Stop firing after maximum shots
}
// 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 = (parseInt(boss.style.left) + boss.offsetWidth / 2 - 5) + 'px';
projectile.style.bottom = (parseInt(boss.style.bottom) + 30) + 'px'; // Start just above the boss
gameWorld.appendChild(projectile);
let projectileInterval = setInterval(() => {
projectile.style.bottom = (parseInt(projectile.style.bottom) + 10) + 'px'; // Move projectile down
// 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 too low
if (parseInt(projectile.style.bottom) > gameContainer.offsetHeight) {
projectile.remove(); // Remove off-screen
clearInterval(projectileInterval);
}
}, 50); // Update every 50ms
shotsFired++;
}, shotCooldown); // Fire every second
}
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 draining health if shield is active
function moveChargingEnemies() {
enemies.forEach((enemy, index) => {
if (enemy.classList.contains('charging-enemy')) {
let chargeTime = parseInt(enemy.getAttribute('data-charge'));
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);
}
}
});
You've got a solid foundation for an advanced adventure game here! The HTML structure and the corresponding JavaScript function seem robust and contain many features typical in modern games, like power-ups, enemy behavior, and various interactions.
Here’s a high-level overview and some points you might want to consider or enhance:
Overview:
Game Mechanics:
You've implemented multiple player actions (jumping, shooting, power-ups, and interactions).
A variety of enemies with different mechanics and power-ups add depth to gameplay.
The game includes a boss fight with multiple attack phases, making it challenging.
Visuals:
The CSS gives a clean design to the game.
Animations for player actions and enemies, along with power-up effects, enhance the user experience.
Game Structure:
The organization appears sound with clear sections for setup, action handling, animations, and enemy behaviors.
Suggestions for Improvement:
Code Optimization:
Consider breaking down some of the larger functions into smaller, more manageable ones to improve readability and maintainability.
Look into DRY (Don't Repeat Yourself) principles; for instance, the power-up application logic might be centralized.
Game Difficulty Scaling:
Implement a proper difficulty curve. As players progress through levels, ensure that the enemy spawn rates and behaviors evolve to maintain challenge without becoming overwhelming.
User Experience:
Adding audio cues (e.g., when shooting, taking damage, or obtaining power-ups) can greatly enhance player immersion.
Consider implementing a tutorial or guided gameplay for new users.
Game Balance:
Review the balance of power-ups and their cooldowns. Some might feel too overpowered or too weak, impacting the gameplay experience.
Ensure that the game's scoring system rewards players adequately but doesn’t make them feel rewarded too easily.
Responsive Design:
Ensure that the game scales well to various devices and screen sizes. The current fixed dimensions might limit playability on mobile.
Consider adding a responsive layout or adjusting parameters dynamically based on the viewport.
Debugging and Testing:
Make sure to test for bugs rigorously. A logging system might help track down errors during gameplay.
Playtesting with real users can provide insights into difficulty balancing and playability.
Additional Features:
Incorporate saving/loading features so players can return to where they left off.
Add more interactive elements in the world, such as environmental hazards or varied terrain.
Documentation and Comments:
Adding comments explaining complex parts of the code can assist future developers (or yourself) when revisiting the project.
Conclusion:
Your script already looks quite promising! By considering a few optimizations and enhancements, you can improve both the development process and the player's experience. Keep iterating on it, and good luck with your game development! If you have specific aspects you're looking to improve or questions about the implementation, feel free to ask!
Key Changes:
Prevent usePowerUp() from being called when the space key is pressed for shooting.
Maintain the distinction between shooting and power-up usage without interfering with each other.
Here’s how you can modify your handleKeydown function:
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;
}
}
Notes:
The key change is the placement of the if (currentPowerUp) check right before calling usePowerUp(). Now, we first check if there is an active power-up. If not, we then check if the boss power is obtained.
This ensures that pressing the space bar does not interfere with the power-up’s activation or use, while still allowing the appropriate actions based on the power-up states.
Make sure your variable currentPowerUp is correctly set to indicate whether the player has an active power-up. Also, ensure that your logic for activating and using power-ups behaves as expected when the Z key is pressed.
With these adjustments, power-ups should activate correctly regardless of interaction with the shooting mechanism.