Certainly! I'll provide an improved and fully functional version of your platformer game with an enhanced level editor. The enhancements include:
- Integrated Block Management: Blocks are managed alongside platforms with different behaviors based on their types (solid, hazard, currency, etc.).
- Enhanced Collision Detection: Improved collision handling for various block types.
- Player Interactions: Hazards will reset the player, and currency blocks can be collected to increase the score.
- Level Editor Enhancements: Ability to remove blocks, save and load levels, and better UI feedback.
- Additional UI Elements: Displaying the score and providing instructions.
- Code Organization: Improved code structure for better readability and maintenance.
Below is the complete enhanced code with detailed explanations of the improvements.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Enhanced Platformer Game with Level Editor</title>
<style>
body {
margin: 0;
overflow: hidden; /* Prevent scrollbars */
background-color: #f2f2f2; /* Light gray background */
font-family: Arial, sans-serif;
}
canvas {
display: block; /* Center the canvas */
background-color: #87ceeb; /* Sky background */
}
#editor {
position: absolute;
top: 10px;
left: 10px;
color: white;
background-color: rgba(0, 0, 0, 0.7);
padding: 10px;
border-radius: 5px;
display: none; /* Initially hidden */
z-index: 1;
}
#block-palette {
display: flex;
gap: 5px;
margin-top: 10px;
}
.block {
width: 40px;
height: 40px;
cursor: pointer;
border: 2px solid white;
border-radius: 3px;
}
.block.selected {
border: 2px solid yellow;
}
.solid { background-color: green; }
.hazard { background-color: red; }
.currency { background-color: gold; }
/* UI Elements */
#ui {
position: absolute;
top: 10px;
right: 10px;
color: white;
background-color: rgba(0, 0, 0, 0.5);
padding: 10px;
border-radius: 5px;
z-index: 1;
}
#instructions {
position: absolute;
bottom: 10px;
left: 10px;
color: white;
background-color: rgba(0, 0, 0, 0.7);
padding: 10px;
border-radius: 5px;
z-index: 1;
max-width: 300px;
font-size: 14px;
}
</style>
</head>
<body>
<canvas id="game-canvas" width="1000" height="600"></canvas>
<div id="editor">
<div><strong>Level Editor</strong></div>
<div id="block-palette">
<div class="block solid selected" data-type="solid" title="Solid Block"></div>
<div class="block hazard" data-type="hazard" title="Hazard Block"></div>
<div class="block currency" data-type="currency" title="Currency Block"></div>
</div>
<div style="margin-top:10px;">
<button id="save-btn">Save Level</button>
<button id="load-btn">Load Level</button>
<button id="clear-btn">Clear Blocks</button>
</div>
</div>
<div id="ui">
<div>Score: <span id="score">0</span></div>
<div>Press '0' to Toggle Editor</div>
</div>
<div id="instructions">
<strong>Instructions:</strong>
<ul>
<li>Use Arrow Keys to move and jump.</li>
<li>Press '0' to toggle the Level Editor.</li>
<li>In Editor Mode:</li>
<ul>
<li>Click to place a block of the selected type.</li>
<li>Right-click on a block to remove it.</li>
<li>Select block type from the palette.</li>
<li>Use buttons to save, load, or clear the level.</li>
</ul>
</ul>
</div>
<script>
const canvas = document.getElementById("game-canvas");
const ctx = canvas.getContext("2d");
const editorDiv = document.getElementById("editor");
const blockPalette = document.getElementById("block-palette");
const scoreElement = document.getElementById("score");
const saveBtn = document.getElementById("save-btn");
const loadBtn = document.getElementById("load-btn");
const clearBtn = document.getElementById("clear-btn");
// Player properties
const player = {
x: 100,
y: 500,
width: 40,
height: 60,
speed: 5,
jumping: false,
yVelocity: 0,
color: "blue",
score: 0
};
// Keyboard controls
const keys = {
right: false,
left: false,
up: false
};
// Editor state
let editorActive = false;
let currentBlockType = 'solid'; // Default block type
const blocks = []; // Array to hold all blocks
// Platforms (static level platforms)
const platforms = [
{ x: 0, y: 560, width: 1000, height: 40 },
{ x: 200, y: 450, width: 200, height: 20 },
{ x: 500, y: 350, width: 200, height: 20 },
{ x: 750, y: 250, width: 200, height: 20 }
];
// Prevent context menu on right-click in editor
canvas.addEventListener("contextmenu", (e) => {
e.preventDefault();
});
// Handle keyboard input
document.addEventListener("keydown", (e) => {
switch (e.code) {
case "ArrowRight":
keys.right = true;
break;
case "ArrowLeft":
keys.left = true;
break;
case "ArrowUp":
case "Space":
if (!player.jumping) {
player.jumping = true;
player.yVelocity = -15;
}
break;
case "Digit0":
toggleEditor();
break;
}
});
document.addEventListener("keyup", (e) => {
switch (e.code) {
case "ArrowRight":
keys.right = false;
break;
case "ArrowLeft":
keys.left = false;
break;
case "ArrowUp":
case "Space":
keys.up = false;
break;
}
});
// Toggle Level Editor
function toggleEditor() {
editorActive = !editorActive;
editorDiv.style.display = editorActive ? 'block' : 'none';
blockPalette.querySelectorAll('.block').forEach(block => block.classList.remove('selected'));
if (editorActive) {
// Select the current block type in the palette
const selectedBlock = blockPalette.querySelector(`.block[data-type="${currentBlockType}"]`);
if (selectedBlock) selectedBlock.classList.add('selected');
console.log("Level Editor Activated");
} else {
console.log("Level Editor Deactivated");
}
}
// Handle block palette selection
blockPalette.addEventListener("click", (e) => {
if (e.target.classList.contains("block")) {
currentBlockType = e.target.getAttribute("data-type");
blockPalette.querySelectorAll('.block').forEach(block => block.classList.remove('selected'));
e.target.classList.add('selected');
console.log(`Selected Block Type: ${currentBlockType}`);
}
});
// Handle canvas clicks for placing/removing blocks
canvas.addEventListener("mousedown", (e) => {
if (!editorActive) return;
const rect = canvas.getBoundingClientRect();
const mouseX = e.clientX - rect.left;
const mouseY = e.clientY - rect.top;
const gridSize = 40;
const x = Math.floor(mouseX / gridSize) * gridSize;
const y = Math.floor(mouseY / gridSize) * gridSize;
if (e.button === 0) { // Left-click to place
blocks.push({ x, y, type: currentBlockType, width: gridSize, height: gridSize });
console.log(`Placed ${currentBlockType} block at (${x}, ${y})`);
} else if (e.button === 2) { // Right-click to remove
// Find and remove the block under the cursor
for (let i = blocks.length - 1; i >= 0; i--) {
const block = blocks[i];
if (mouseX >= block.x && mouseX < block.x + block.width &&
mouseY >= block.y && mouseY < block.y + block.height) {
blocks.splice(i, 1);
console.log(`Removed block at (${block.x}, ${block.y})`);
break;
}
}
}
});
// Save level to localStorage
saveBtn.addEventListener("click", () => {
const levelData = JSON.stringify(blocks);
localStorage.setItem("savedLevel", levelData);
alert("Level Saved!");
});
// Load level from localStorage
loadBtn.addEventListener("click", () => {
const levelData = localStorage.getItem("savedLevel");
if (levelData) {
blocks.length = 0; // Clear existing blocks
const loadedBlocks = JSON.parse(levelData);
loadedBlocks.forEach(block => {
blocks.push(block);
});
alert("Level Loaded!");
} else {
alert("No saved level found.");
}
});
// Clear all blocks
clearBtn.addEventListener("click", () => {
if (confirm("Are you sure you want to clear all blocks?")) {
blocks.length = 0;
alert("All blocks cleared.");
}
});
// Drawing functions
function drawPlayer() {
ctx.fillStyle = player.color;
ctx.fillRect(player.x, player.y, player.width, player.height);
}
function drawPlatforms() {
ctx.fillStyle = "green";
platforms.forEach(platform => {
ctx.fillRect(platform.x, platform.y, platform.width, platform.height);
});
}
function drawBlocks() {
blocks.forEach(block => {
ctx.fillStyle = getBlockColor(block.type);
ctx.fillRect(block.x, block.y, block.width, block.height);
});
}
function getBlockColor(type) {
switch (type) {
case 'solid': return 'green';
case 'hazard': return 'red';
case 'currency': return 'gold';
default: return 'gray';
}
}
function drawUI() {
// Score is already handled via HTML element
// Additional UI elements can be added here if needed
}
// Game physics and movement
function updatePlayer() {
// Horizontal Movement
if (keys.right) {
player.x += player.speed;
if (player.x + player.width > canvas.width) {
player.x = canvas.width - player.width;
}
}
if (keys.left) {
player.x -= player.speed;
if (player.x < 0) {
player.x = 0;
}
}
// Apply gravity
player.yVelocity += 0.8; // Gravity strength
player.y += player.yVelocity;
// Collision with ground
if (player.y + player.height >= canvas.height) {
player.y = canvas.height - player.height;
player.jumping = false;
player.yVelocity = 0;
}
// Collision with platforms and blocks
handleCollisions();
}
function handleCollisions() {
// Combine platforms and solid blocks for collision
const collisionBlocks = [
...platforms,
...blocks.filter(block => block.type === 'solid')
];
collisionBlocks.forEach(block => {
if (isColliding(player, block)) {
// From above
if (player.y + player.height - player.yVelocity <= block.y) {
player.y = block.y - player.height;
player.jumping = false;
player.yVelocity = 0;
}
// From below
else if (player.y - player.yVelocity >= block.y + block.height) {
player.y = block.y + block.height;
player.yVelocity = 0;
}
// From sides
else {
if (player.x < block.x) {
player.x = block.x - player.width;
} else {
player.x = block.x + block.width;
}
}
}
});
// Handle interactions with non-solid blocks
blocks.forEach((block, index) => {
if (block.type === 'hazard' && isColliding(player, block)) {
resetPlayer();
}
if (block.type === 'currency' && isColliding(player, block)) {
player.score += 10;
scoreElement.textContent = player.score;
blocks.splice(index, 1); // Remove the collected currency
}
});
}
// Simple AABB collision detection
function isColliding(rect1, rect2) {
return (
rect1.x < rect2.x + rect2.width &&
rect1.x + rect1.width > rect2.x &&
rect1.y < rect2.y + rect2.height &&
rect1.y + rect1.height > rect2.y
);
}
// Reset player position and score
function resetPlayer() {
alert("You hit a hazard! Resetting position.");
player.x = 100;
player.y = 500;
player.yVelocity = 0;
player.jumping = false;
player.score = 0;
scoreElement.textContent = player.score;
}
// Game loop
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Update and draw
updatePlayer();
drawPlatforms();
drawBlocks();
drawPlayer();
drawUI();
requestAnimationFrame(gameLoop);
}
// Start the game loop
gameLoop();
</script>
</body>
</html>
Key Enhancements Explained
1. Integrated Block Management
- Unified Blocks and Platforms: Blocks are treated alongside platforms, allowing for diverse interactions based on their types.
- Types of Blocks: Each block has a
type attribute determining its behavior:
- Solid: Acts like a platform for the player to stand on.
- Hazard: Kills or resets the player upon collision.
- Currency: Collectible items that increase the player's score.
2. Enhanced Collision Detection
- Improved Logic: Collision detection now accounts for player velocity and determines the collision direction (top, bottom, sides) to respond appropriately.
- Handling Different Block Types:
- Solid Blocks: Prevent the player from passing through and allow standing.
- Hazard Blocks: Trigger a player reset when collided with.
- Currency Blocks: Increase score and remove the block upon collection.
3. Player Interactions
- Hazards: Colliding with a hazard block resets the player's position and score, providing a classic platformer challenge.
- Currency Collection: Collecting currency blocks increases the player's score, incentivizing exploration and collection.
4. Enhanced Level Editor
- Block Placement and Removal:
- Left-Click: Places a block of the selected type on the grid.
- Right-Click: Removes a block if one exists at the clicked position.
- Block Palette:
- Selection Indication: The selected block type is highlighted with a yellow border for clarity.
- Save and Load Functionality:
- Save Level: Saves the current blocks to
localStorage.
- Load Level: Loads the saved blocks from
localStorage.
- Clear Blocks: Removes all blocks from the current level after confirmation.
- Preventing Default Right-Click Menu: Right-clicking within the editor allows block removal without triggering the browser's context menu.
5. Additional UI Elements
- Score Display: The player's current score is displayed on the top-right corner and updates in real-time.
- Instructions: Clear instructions are provided at the bottom-left corner to guide players on controls and editor usage.
- UI Styling: Enhanced styling for better visibility and user experience, including tooltips for block types in the palette.
6. Code Organization and Quality
- Modular Functions: Separation of concerns with distinct functions for drawing, updating, collision handling, and UI management.
- Comments and Readability: Added comments and clear variable naming for better understanding and maintenance.
- Responsive Controls: Smooth and responsive player movement and interactions.
How to Use the Enhanced Game
-
Playing the Game:
- Movement: Use the Arrow Keys to move the player left and right.
- Jumping: Press the Up Arrow or Spacebar to make the player jump.
-
Using the Level Editor:
- Toggle Editor: Press the '0' key to enter or exit the Level Editor mode.
- Selecting Block Types: Click on a block in the palette to select its type (Solid, Hazard, Currency).
- Placing Blocks: Left-click on the canvas to place the selected block type.
- Removing Blocks: Right-click on an existing block to remove it.
- Saving Level: Click the "Save Level" button to save the current block layout.
- Loading Level: Click the "Load Level" button to load the saved block layout.
- Clearing Blocks: Click the "Clear Blocks" button to remove all blocks from the level.
-
Game Objectives:
- Avoid Hazards: Steer clear of red hazard blocks to prevent resetting your position and score.
- Collect Currency: Gather gold currency blocks to increase your score.
- Navigate Platforms: Use the platforms to reach higher areas and collect more currency.
Conclusion
This enhanced version of your platformer game provides a more engaging and interactive experience with an improved level editor. Players can not only enjoy the game but also create and customize their own levels, adding significant replay value. The code is organized for better readability and future enhancements, making it easier to expand upon features like adding enemies, different levels, or more intricate platforms.
Feel free to further customize and expand upon this foundation to create a rich and dynamic platformer game!