Your "Infinite Wave Game" is a solid foundation inspired by Geometry Dash! To enhance the gameplay experience, consider implementing the following improvements:
Enhanced Graphics and Animations
Background Layers: Add parallax scrolling backgrounds to create depth.
Player Animation: Introduce animated sprites or more complex shapes.
Obstacle Variety: Different shapes and moving obstacles to increase challenge.
Sound Effects and Music
Add background music to make the game more engaging.
Include sound effects for jumping, collisions, and scoring.
Improved Controls
Implement smoother controls with variable jump heights based on how long the input is held.
Add touch gesture support for mobile devices.
Power-ups and Collectibles
Introduce collectibles that grant temporary abilities or score bonuses.
Add power-ups like shields or speed boosts.
Dynamic Difficulty
Increase game difficulty based on the player's score or time survived.
Introduce different obstacle patterns as the game progresses.
Responsive Design
Make the game canvas responsive to different screen sizes for better accessibility on various devices.
Leaderboard and Persistence
Implement a leaderboard to display high scores.
Save the highest score using localStorage.
Visual Enhancements
Use gradients and shadows to make graphics more appealing.
Add particle effects upon collisions or scoring.
Below is an improved version of your game incorporating several of these enhancements:
Enhanced Infinite Wave Game
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Infinite Wave Game</title>
<style>
/* Reset and Body Styling */
body {
margin: 0;
overflow: hidden;
background-color: #1e1e1e;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
/* Center the Canvas */
canvas {
display: block;
margin: 0 auto;
background-color: #111;
}
/* Score Display */
#score {
position: absolute;
top: 20px;
left: 50%;
transform: translateX(-50%);
color: #fff;
font-size: 24px;
z-index: 1;
text-shadow: 2px 2px 4px #000;
}
/* High Score Display */
#highScore {
position: absolute;
top: 60px;
left: 50%;
transform: translateX(-50%);
color: #fff;
font-size: 20px;
z-index: 1;
text-shadow: 2px 2px 4px #000;
}
/* Game Over Overlay */
#gameOver {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.95);
color: #fff;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: 32px;
z-index: 2;
visibility: hidden;
opacity: 0;
transition: opacity 0.5s;
}
#gameOver.visible {
visibility: visible;
opacity: 1;
}
#gameOver button {
margin-top: 20px;
padding: 10px 20px;
font-size: 24px;
cursor: pointer;
background-color: #00ffea;
border: none;
border-radius: 5px;
transition: background-color 0.3s;
}
#gameOver button:hover {
background-color: #00c4b4;
}
/* Instruction Text */
#instruction {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
color: #fff;
font-size: 18px;
z-index: 1;
text-shadow: 1px 1px 2px #000;
}
</style>
</head>
<body>
<!-- Score Display -->
<div id="score">Score: 0</div>
<div id="highScore">High Score: 0</div>
<!-- Game Canvas -->
<canvas id="gameCanvas" width="800" height="400"></canvas>
<!-- Game Over Overlay -->
<div id="gameOver">
<div id="gameOverText">Game Over! Your score: 0</div>
<button id="restartButton">Restart</button>
</div>
<!-- Instruction Text -->
<div id="instruction">Hold Space or Click to Move Up</div>
<!-- Game Script -->
<script>
// Canvas Setup
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const WIDTH = canvas.width;
const HEIGHT = canvas.height;
// DOM Elements
const scoreDisplay = document.getElementById('score');
const highScoreDisplay = document.getElementById('highScore');
const gameOverOverlay = document.getElementById('gameOver');
const gameOverText = document.getElementById('gameOverText');
const restartButton = document.getElementById('restartButton');
// Load High Score from localStorage
let highScore = localStorage.getItem('highScore') || 0;
highScoreDisplay.innerText = `High Score: ${highScore}`;
// Game Variables
let score = 0;
let gameSpeed = 5;
let obstacles = [];
let keys = {};
let animationId;
let obstacleSpawnInterval;
let lastTime = 0;
let playerColor = '#00ffea';
let inputHeld = false; // Flag to track user input
// Asset Loading
const backgroundImage = new Image();
backgroundImage.src = 'https://i.imgur.com/5sKZJ8L.png'; // Example background image URL
const jumpSound = new Audio('https://actions.google.com/sounds/v1/cartoon/wood_plank_flicks.ogg');
const collisionSound = new Audio('https://actions.google.com/sounds/v1/cartoon/clang_and_wobble.ogg');
const backgroundMusic = new Audio('https://www.bensound.com/bensound-music/bensound-anewbeginning.mp3');
backgroundMusic.loop = true;
backgroundMusic.volume = 0.5;
// Player Object (Wave Shape)
const player = {
x: 100,
y: HEIGHT / 2,
width: 40,
height: 40,
dy: 0,
gravity: 0.6,
lift: -12, // Upward force when input is held
maxY: HEIGHT - 40, // Prevent player from going below the canvas
color: playerColor,
isAnimating: false,
update: function() {
if (inputHeld) {
this.dy = this.lift;
} else {
this.dy += this.gravity;
}
this.y += this.dy;
// Boundary Detection
if (this.y + this.height > HEIGHT) {
this.y = HEIGHT - this.height;
this.dy = 0;
endGame();
}
if (this.y < 0) {
this.y = 0;
this.dy = 0;
}
this.draw();
},
draw: function() {
ctx.fillStyle = this.color;
ctx.beginPath();
// Create a wave-like shape using arcs and curves
ctx.moveTo(this.x, this.y + this.height / 2);
ctx.quadraticCurveTo(
this.x + this.width / 2, this.y - this.height / 2,
this.x + this.width, this.y + this.height / 2
);
ctx.quadraticCurveTo(
this.x + this.width / 2, this.y + this.height * 1.5,
this.x, this.y + this.height / 2
);
ctx.closePath();
ctx.fill();
}
};
// Obstacle Class
class Obstacle {
constructor() {
this.width = 30 + Math.random() * 20;
this.height = 30 + Math.random() * 100;
this.x = WIDTH;
this.y = HEIGHT - this.height;
this.color = getRandomColor();
this.speed = gameSpeed;
}
update() {
this.x -= this.speed;
this.draw();
}
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
// Utility Functions
function getRandomColor() {
const colors = ['#ff005e', '#00ffea', '#ffea00', '#00ff85', '#ff00c8'];
return colors[Math.floor(Math.random() * colors.length)];
}
function spawnObstacle() {
obstacles.push(new Obstacle());
// Spawn next obstacle between 1 to 1.5 seconds
const time = 1000 + Math.random() * 500;
obstacleSpawnInterval = setTimeout(spawnObstacle, time);
}
// Collision Detection using Axis-Aligned Bounding Box (AABB)
function collisionDetection() {
for (let obs of obstacles) {
if (
player.x < obs.x + obs.width &&
player.x + player.width > obs.x &&
player.y < obs.y + obs.height &&
player.y + player.height > obs.y
) {
collisionSound.play();
endGame();
}
}
}
// Update Score
function updateScore(deltaTime) {
score += deltaTime * 0.01; // Increment score based on time
scoreDisplay.innerText = `Score: ${Math.floor(score)}`;
}
// End Game Function
function endGame() {
cancelAnimationFrame(animationId);
clearTimeout(obstacleSpawnInterval);
backgroundMusic.pause();
gameOverText.innerText = `Game Over! Your score: ${Math.floor(score)}`;
// Update High Score
if (score > highScore) {
highScore = Math.floor(score);
localStorage.setItem('highScore', highScore);
highScoreDisplay.innerText = `High Score: ${highScore}`;
}
gameOverOverlay.classList.add('visible');
}
// Restart Game Function
function restartGame() {
// Reset Variables
score = 0;
gameSpeed = 5;
obstacles = [];
player.y = HEIGHT / 2;
player.dy = 0;
inputHeld = false;
scoreDisplay.innerText = `Score: ${score}`;
gameOverOverlay.classList.remove('visible');
// Restart Obstacle Spawning and Game Loop
spawnObstacle();
lastTime = performance.now();
backgroundMusic.currentTime = 0;
backgroundMusic.play();
gameLoop(lastTime);
}
// Main Game Loop
function gameLoop(timestamp) {
const deltaTime = timestamp - lastTime;
lastTime = timestamp;
ctx.clearRect(0, 0, WIDTH, HEIGHT);
// Draw Background
// For simplicity, using a solid color. Replace with image for parallax.
ctx.fillStyle = '#1e1e1e';
ctx.fillRect(0, 0, WIDTH, HEIGHT);
// Update and Draw Player
player.update();
// Update and Draw Obstacles
for (let i = obstacles.length - 1; i >= 0; i--) {
obstacles[i].update();
// Remove off-screen obstacles
if (obstacles[i].x + obstacles[i].width < 0) {
obstacles.splice(i, 1);
score += 10; // Bonus for passing an obstacle
// Optionally, add a sound or particle effect here
}
}
// Collision Detection
collisionDetection();
// Update Score
updateScore(deltaTime);
// Gradually Increase Game Speed
gameSpeed += 0.0005; // Adjust this value for difficulty ramp
for (let obs of obstacles) {
obs.speed = gameSpeed;
}
animationId = requestAnimationFrame(gameLoop);
}
// Event Listeners for Controls
document.addEventListener('keydown', function(e) {
if (e.code === 'Space' || e.code === 'ArrowUp') {
if (!keys[e.code]) { // Trigger only on key press
jumpSound.play();
}
keys[e.code] = true;
inputHeld = true;
}
});
document.addEventListener('keyup', function(e) {
if (e.code === 'Space' || e.code === 'ArrowUp') {
keys[e.code] = false;
inputHeld = false;
}
});
// Handle Mouse Clicks or Touches
document.addEventListener('mousedown', function() {
inputHeld = true;
jumpSound.play();
});
document.addEventListener('mouseup', function() {
inputHeld = false;
});
// For touch devices
document.addEventListener('touchstart', function(e) {
e.preventDefault(); // Prevents mouse events from also firing
inputHeld = true;
jumpSound.play();
}, { passive: false });
document.addEventListener('touchend', function(e) {
e.preventDefault();
inputHeld = false;
}, { passive: false });
// Restart Button Event Listener
restartButton.addEventListener('click', restartGame);
// Start the Game
backgroundMusic.play();
spawnObstacle();
lastTime = performance.now();
gameLoop(lastTime);
</script>
</body>
</html>
Key Improvements Explained
High Score Tracking
Utilizes localStorage to save and display the highest score achieved by the player.
Sound Effects and Music
Added background music that loops during gameplay.
Incorporated sound effects for jumping (jumpSound) and collisions (collisionSound).
Visual Enhancements
Dynamic Background: Although the current implementation uses a solid color, you can replace it with a background image for a more engaging scene. Uncomment and adjust the background image section as needed.
Obstacle Colors: Obstacles now have random colors selected from a predefined palette to add variety.
Responsive Controls
Enhanced responsiveness for both keyboard and touch inputs.
Added jumpSound to provide immediate audio feedback on input.
Improved Game Over Mechanics
The game updates and displays the high score if the current score exceeds it.
Pauses background music upon game over and resets it upon restart.
Enhanced Player Feedback
Sound effects enhance the gameplay feel, making actions more satisfying.
Code Optimization and Readability
Organized and commented code for better readability and maintenance.
Created utility functions like getRandomColor() to streamline obstacle color assignment.
Future-Proofing for Additional Features
The structure allows easy addition of new features like power-ups, different obstacle types, or multiple player characters.
Additional Recommendations
Parallax Backgrounds: Implement multiple layers moving at different speeds to create a parallax effect, adding depth to the scene.
Animated Player Sprite: Replace the static wave shape with an animated sprite to make the player character more lively.
Power-ups and Collectibles: Introduce items that the player can collect for extra points or temporary abilities.
Different Obstacle Types: Add moving obstacles or those with varying behaviors to increase game complexity.
Particle Effects: Implement particle effects upon collision or while passing obstacles to enhance visual feedback.
Mobile Optimization: Ensure the game scales and responds well on various screen sizes for a seamless mobile experience.
Accessibility Features: Include options like customizable controls or colorblind modes to make the game accessible to a wider audience.
Implementing a Parallax Background (Example)
To add a parallax scrolling background, you can introduce multiple background layers moving at different speeds. Here's how you can implement it:
function drawBackground() {
bgLayers.forEach(layer => {
layer.x -= layer.speed;
if (layer.x <= -WIDTH) {
layer.x = 0;
}
ctx.drawImage(layer.image, layer.x, 0, WIDTH, HEIGHT);
ctx.drawImage(layer.image, layer.x + WIDTH, 0, WIDTH, HEIGHT);
});
}
function gameLoop(timestamp) {
const deltaTime = timestamp - lastTime;
lastTime = timestamp;
ctx.clearRect(0, 0, WIDTH, HEIGHT);
// Draw Background
drawBackground();
// ... rest of the game loop
}
Note: Ensure your background images are seamless to allow for smooth looping.
Conclusion
By implementing these enhancements, your "Infinite Wave Game" will offer a more engaging and polished experience, drawing players in with improved visuals, audio, and gameplay mechanics. Feel free to iterate and customize further based on your creative vision!