Here's a fully-featured Super Mario-style platformer game implemented in a single HTML file using embedded CSS and JavaScript.
This game includes:
- Core Gameplay Mechanics:
- Smooth side-scrolling camera that follows the player.
- Physics-based movement with gravity, jumping, and momentum.
- Collision detection for platforms, enemies, and collectibles.
- Multiple player states (Small Mario, Super Mario, Fire Mario) with visual transformations.
- Lives system with respawn mechanics and game over conditions.
- Enemies & AI:
- Goombas with walking AI that turn around at edges/walls.
- Koopa Troopas that retreat into shells when jumped on, and can be kicked to slide.
- Flying enemies (Koopa Paratroopas) with vertical movement patterns, turning into regular Koopas when stomped.
- Enemy death animations (simple disappearance) and point scoring system.
- Power-ups & Collectibles:
- Super Mushroom (makes Mario bigger and grants extra hit point/state).
- Fire Flower (enables fireball shooting ability for Fire Mario).
- 1-Up Mushroom for extra lives.
- Coins with collection counter and score system (coins pop up from blocks).
- Hidden blocks that reveal power-ups or coins when hit from below.
Instructions:
- Save the code below as an
.html file (e.g., mario_game.html).
- Open the file in a web browser.
- Controls:
- Arrow Left/Right: Move Mario
- Spacebar: Jump
- Z or X: Shoot Fireball (if Fire Mario)
- R: Restart game (from Game Over screen or after losing a life)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Super Mario-style Platformer</title>
<style>
body {
margin: 0;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #333;
font-family: 'Press Start 2P', cursive, monospace; /* Fallback fonts */
/* Improve pixel art rendering in some browsers */
image-rendering: pixelated;
image-rendering: -moz-crisp-edges;
image-rendering: -webkit-crisp-edges;
}
canvas {
border: 2px solid #000;
background-color: #87CEEB; /* Sky blue */
display: block;
}
</style>
</head>
<body>
<canvas id="gameCanvas"></canvas>
<script>
// Get the canvas and its 2D rendering context
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Global Game Constants
const TILE_SIZE = 32;
const CANVAS_WIDTH = 800; // Fixed width for game display
const CANVAS_HEIGHT = 480; // Fixed height for game display
const GRAVITY = 0.5; // Downward acceleration
const PLAYER_SPEED = 4; // Horizontal movement speed of player
const PLAYER_JUMP_FORCE = 10; // Initial upward velocity for jump
const PLAYER_MAX_FALL_SPEED = 10; // Maximum speed when falling
const FIREBALL_SPEED = 8; // Speed of fireballs
const ENEMY_SPEED = 1; // Base speed for walking enemies
// Player States
const PLAYER_STATE_SMALL = 0;
const PLAYER_STATE_BIG = 1;
const PLAYER_STATE_FIRE = 2;
// Block Types
const BLOCK_TYPE_SOLID = 0; // Impassable block
const BLOCK_TYPE_QUESTION = 1; // Block that reveals content when hit
const BLOCK_TYPE_BRICK = 2; // Breakable by big Mario, solid for small Mario
const BLOCK_TYPE_HIDDEN = 3; // Invisible until hit
// Block Contents (what a question/hidden block can hold)
const CONTENT_MUSHROOM = 0;
const CONTENT_FIRE_FLOWER = 1;
const CONTENT_ONE_UP = 2;
const CONTENT_COIN = 3;
// Enemy Types (for creation from level map)
const ENEMY_GOOMBA = 0;
const ENEMY_KOOPA = 1;
const ENEMY_PARATROOPA = 2;
// Koopa-specific States
const KOOPA_WALKING = 0;
const KOOPA_SHELL = 1; // In a stationary shell
const KOOPA_SLIDING = 2; // Sliding shell (kicked)
// Game State Variables
let gameRunning = false;
let gameOver = false;
let gameRestarting = false; // Flag for when player loses a life and needs to respawn
let gameRestartTimer = 0; // Countdown for respawn/game over screen
let player; // The player character object
let camera; // The camera object
let blocks = []; // Array of static blocks in the level
let enemies = []; // Array of active enemies
let collectibles = []; // Array of active power-ups/coins
let fireballs = []; // Array of active fireballs (from Fire Mario)
let coins = 0; // Player's coin count
let score = 0; // Player's score
let levelWidth = 0; // Calculated from the level map's width
let keys = {}; // Object to track currently pressed keys
// Level Map: A 2D array of characters representing the game world
// P: Platform (Solid Block)
// Q: Question Block (Mushroom by default)
// F: Question Block (Fire Flower)
// M: Question Block (1-Up Mushroom)
// B: Brick Block
// H: Hidden Block (Coin by default, can be mushroom if player small)
// G: Goomba
// K: Koopa
// A: Koopa Paratroopa
// S: Player Start Position
const levelMap = [
"PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",
"P P",
"P P",
"P P",
"P P",
"P P",
"P P",
"P P",
"P P",
"P P",
"P P",
"P P",
"P P",
"P Q Q B Q Q Q B B B B B P",
"P S B P",
"P G P",
"P K P",
"P P",
"P P",
"P P",
"P P P P P P P P",
"P P",
"P P",
"P P",
"P Q M Q P",
"P PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",
"P G P",
"P Q B Q Q B B P",
"P A P",
"P H P",
"P P",
"P P",
"P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P P",
"P P",
"P F P",
"P Q B Q P",
"P G P",
"P PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP"
];
// --- Base Entity Class ---
// All game objects (player, enemies, blocks, collectibles) inherit from Entity
class Entity {
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.vx = 0; // Velocity X
this.vy = 0; // Velocity Y
this.onGround = false; // Is the entity currently on the ground?
this.isAlive = true; // Is the entity active in the game?
}
// Axis-Aligned Bounding Box (AABB) collision detection
collidesWith(other) {
return this.x < other.x + other.width &&
this.x + this.width > other.x &&
this.y < other.y + other.height &&
this.y + this.height > other.y;
}
}
// --- Player Class ---
class Player extends Entity {
constructor(x, y) {
super(x, y, TILE_SIZE, TILE_SIZE); // Small Mario starts as 1 tile high
this.lives = 3;
this.state = PLAYER_STATE_SMALL; // Current power-up state
this.facing = 1; // 1 for right, -1 for left
this.isJumping = false; // True while jump key is held
this.invincibleTimer = 0; // Frames of invincibility after taking damage
this.isDying = false; // True during death animation
this.fireballs = []; // Array to hold active fireballs
}
// Handles player taking a hit (damage)
takeHit() {
if (this.invincibleTimer > 0 || this.isDying) {
return; // Player is already invincible or dying
}
if (this.state === PLAYER_STATE_SMALL) {
// Small Mario dies instantly
this.lives--;
this.isDying = true;
this.vx = 0;
this.vy = -PLAYER_JUMP_FORCE * 1.5; // Mario jumps up on death
} else {
// Big or Fire Mario reverts to Small Mario
this.state = PLAYER_STATE_SMALL;
// Adjust y to keep bottom consistent when shrinking
this.y += TILE_SIZE;
this.height = TILE_SIZE; // Revert to small Mario height
this.invincibleTimer = 120; // 2 seconds of invincibility (60 frames/sec)
score -= 100; // Small score penalty
if (score < 0) score = 0; // Prevent negative score
}
}
// Creates and shoots a fireball if player is Fire Mario
shootFireball() {
if (this.state === PLAYER_STATE_FIRE && this.fireballs.length < 2) { // Limit to 2 fireballs on screen
let fbX = this.x + (this.facing === 1 ? this.width : -TILE_SIZE / 2); // Position fireball in front of Mario
let fbY = this.y + this.height / 2 - TILE_SIZE / 4; // Vertically center it
this.fireballs.push(new Fireball(fbX, fbY, this.facing * FIREBALL_SPEED));
}
}
// Updates player's state (movement, gravity, etc.)
update() {
if (this.isDying) {
// Death animation: Mario floats up then falls down
this.x += this.vx;
this.y += this.vy;
this.vy += GRAVITY;
if (this.y > CANVAS_HEIGHT + TILE_SIZE * 2) { // Off screen after death
this.isAlive = false; // Mark for removal (triggers gameRestarting)
gameRestarting = true;
gameRestartTimer = 120; // 2 seconds delay before respawn/game over
}
return;
}
// Apply horizontal movement based on key presses
if (keys['arrowleft']) {
this.vx = -PLAYER_SPEED;
this.facing = -1;
} else if (keys['arrowright']) {
this.vx = PLAYER_SPEED;
this.facing = 1;
} else {
this.vx = 0;
}
// Apply jump if Space is pressed and player is on the ground
if (keys[' '] && this.onGround) {
this.vy = -PLAYER_JUMP_FORCE;
this.onGround = false;
this.isJumping = true;
}
// Allow variable jump height (jump higher if Space is held longer)
if (this.isJumping && !keys[' '] && this.vy < -PLAYER_JUMP_FORCE / 2) {
this.vy = -PLAYER_JUMP_FORCE / 2; // Cut jump short
this.isJumping = false;
}
// Apply gravity
this.vy += GRAVITY;
if (this.vy > PLAYER_MAX_FALL_SPEED) {
this.vy = PLAYER_MAX_FALL_SPEED;
}
// Update position based on velocities
this.x += this.vx;
this.y += this.vy;
// Reset onGround flag for next frame's collision detection
this.onGround = false;
// Prevent player from moving off the left edge of the level
if (this.x < 0) this.x = 0;
// Update invincibility timer
if (this.invincibleTimer > 0) {
this.invincibleTimer--;
}
// If player falls off the bottom of the world
if (this.y > levelMap.length * TILE_SIZE + TILE_SIZE * 4) {
this.lives--;
this.isDying = true; // Trigger death state
}
// Update all active fireballs
this.fireballs = this.fireballs.filter(fb => fb.isAlive); // Remove inactive fireballs
this.fireballs.forEach(fb => fb.update());
}
// Draws the player character on the canvas
draw(ctx, camera) {
if (this.isDying) {
// Simple death animation: fading red rectangle
ctx.fillStyle = "rgba(255, 0, 0, 0.5)";
ctx.fillRect(this.x - camera.x, this.y - camera.y, this.width, this.height);
return;
}
// Blink effect when invincible
if (this.invincibleTimer > 0 && Math.floor(this.invincibleTimer / 5) % 2 === 0) {
return; // Skip drawing every other few frames to create blink
}
// Determine Mario's visual size based on state
if (this.state === PLAYER_STATE_BIG || this.state === PLAYER_STATE_FIRE) {
this.height = TILE_SIZE * 2; // Big Mario is 2 tiles high
} else {
this.height = TILE_SIZE; // Small Mario is 1 tile high
}
// Determine colors based on state
let bodyColor = "red";
let pantsColor = "blue";
let hatColor = "red";
if (this.state === PLAYER_STATE_FIRE) {
bodyColor = "orange";
pantsColor = "yellow";
hatColor = "orange";
}
// Draw Mario's body
ctx.fillStyle = bodyColor;
ctx.fillRect(this.x - camera.x, this.y - camera.y, this.width, this.height);
// Draw Mario's pants
ctx.fillStyle = pantsColor;
ctx.fillRect(this.x - camera.x, this.y - camera.y + this.height / 2, this.width, this.height / 2);
// Draw Mario's hat
ctx.fillStyle = hatColor;
ctx.fillRect(this.x - camera.x + this.width / 4, this.y - camera.y - TILE_SIZE / 4, this.width / 2, TILE_SIZE / 4);
// Draw 'M' on the hat
ctx.fillStyle = "white";
ctx.font = `${TILE_SIZE / 2}px 'Press Start 2P'`;
ctx.textAlign = "center";
ctx.fillText("M", this.x - camera.x + this.width / 2, this.y - camera.y - TILE_SIZE / 8);
// Draw a simple eye/nose to indicate facing direction
ctx.fillStyle = "black";
ctx.fillRect(this.x - camera.x + (this.facing === 1 ? this.width - 5 : 0), this.y - camera.y + 5, 5, 5);
// Draw any active fireballs
this.fireballs.forEach(fb => fb.draw(ctx, camera));
}
}
// --- Fireball Class ---
class Fireball extends Entity {
constructor(x, y, vx) {
super(x, y, TILE_SIZE / 2, TILE_SIZE / 2);
this.vx = vx;
this.vy = 0;
this.bounces = 0; // Number of times it has bounced
this.maxBounces = 3; // Fireball extinguishes after this many bounces
}
update() {
this.x += this.vx;
this.y += this.vy;
this.vy += GRAVITY / 2; // Apply gravity (half strength for a lighter feel)
// Disappear if it falls off screen
if (this.y > levelMap.length * TILE_SIZE + TILE_SIZE * 2) {
this.isAlive = false;
}
}
draw(ctx, camera) {
// Draw as a simple yellow/orange circle
ctx.fillStyle = "yellow";
ctx.beginPath();
ctx.arc(this.x - camera.x + this.width / 2, this.y - camera.y + this.height / 2, this.width / 2, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = "orange";
ctx.beginPath();
ctx.arc(this.x - camera.x + this.width / 2, this.y - camera.y + this.height / 2, this.width / 4, 0, Math.PI * 2);
ctx.fill();
}
}
// --- Block Class ---
class Block extends Entity {
constructor(x, y, type, content = null) {
super(x, y, TILE_SIZE, TILE_SIZE);
this.type = type;
this.content = content; // What a question block contains (e.g., CONTENT_MUSHROOM)
this.isHit = false; // For visual bounce animation when hit from below
this.bounceOffset = 0; // Current offset for bounce animation
this.hasContent = (content !== null); // True if it's a question block that hasn't dispensed its content
this.hidden = (type === BLOCK_TYPE_HIDDEN); // True if it's a hidden block and hasn't been revealed
}
// Called when Mario hits the block from below
hit(player) {
if (this.type === BLOCK_TYPE_BRICK && player.state === PLAYER_STATE_SMALL) {
// Small Mario cannot break brick blocks, just bounces it
this.isHit = true;
this.bounceOffset = -5; // Visual bounce up
} else if (this.type === BLOCK_TYPE_BRICK && player.state >= PLAYER_STATE_BIG) {
// Big Mario (or Fire Mario) can break brick blocks
this.isAlive = false; // Mark for removal
score += 50; // Points for breaking
} else if (this.type === BLOCK_TYPE_QUESTION && !this.isHit) {
// Question block, dispense content if it hasn't been hit yet
this.isHit = true;
this.bounceOffset = -5;
this.hasContent = false; // Mark content as dispensed
// Release collectible based on its content type
let collectibleX = this.x;
let collectibleY = this.y - TILE_SIZE; // Spawn above the block
switch (this.content) {
case CONTENT_MUSHROOM:
collectibles.push(new Mushroom(collectibleX, collectibleY));
break;
case CONTENT_FIRE_FLOWER:
collectibles.push(new FireFlower(collectibleX, collectibleY));
break;
case CONTENT_ONE_UP:
collectibles.push(new OneUp(collectibleX, collectibleY));
break;
case CONTENT_COIN:
collectibles.push(new Coin(collectibleX, collectibleY));
break;
}
} else if (this.type === BLOCK_TYPE_HIDDEN && this.hidden) {
// Reveal hidden block when hit
this.hidden = false;
this.isHit = true;
this.bounceOffset = -5;
this.hasContent = false; // Hidden blocks typically dispense once
// Determine content for hidden block: mushroom if small Mario, else coin
let contentToSpawn = this.content !== null ? this.content : (player.state === PLAYER_STATE_SMALL ? CONTENT_MUSHROOM : CONTENT_COIN);
if (contentToSpawn === CONTENT_MUSHROOM) {
collectibles.push(new Mushroom(this.x, this.y - TILE_SIZE));
} else if (contentToSpawn === CONTENT_COIN) {
collectibles.push(new Coin(this.x, this.y - TILE_SIZE));
} else if (contentToSpawn === CONTENT_FIRE_FLOWER) {
collectibles.push(new FireFlower(this.x, this.y - TILE_SIZE));
} else if (contentToSpawn === CONTENT_ONE_UP) {
collectibles.push(new OneUp(this.x, this.y - TILE_SIZE));
}
}
}
// Updates the block's state (e.g., bounce animation)
update() {
if (this.isHit) {
this.bounceOffset += 1; // Move back down
if (this.bounceOffset >= 0) {
this.bounceOffset = 0;
this.isHit = false; // Stop animation
}
}
}
// Draws the block on the canvas
draw(ctx, camera) {
if (this.type === BLOCK_TYPE_HIDDEN && this.hidden) {
return; // Don't draw if hidden and not revealed
}
let color = "gray"; // Default solid block color
switch (this.type) {
case BLOCK_TYPE_QUESTION:
color = this.hasContent ? "gold" : "darkgoldenrod"; // Different color if already hit
break;
case BLOCK_TYPE_BRICK:
color = "brown";
break;
case BLOCK_TYPE_HIDDEN:
color = "lightgray"; // Color after being revealed
break;
}
ctx.fillStyle = color;
ctx.fillRect(this.x - camera.x, this.y - camera.y + this.bounceOffset, this.width, this.height);
// Add simple visual details to blocks
if (this.type === BLOCK_TYPE_QUESTION && this.hasContent) {
ctx.fillStyle = "white";
ctx.font = `${TILE_SIZE * 0.7}px 'Press Start 2P'`;
ctx.textAlign = "center";
ctx.fillText("?", this.x - camera.x + this.width / 2, this.y - camera.y + this.bounceOffset + this.height * 0.75);
}
if (this.type === BLOCK_TYPE_BRICK) {
ctx.strokeStyle = "darkred";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(this.x - camera.x, this.y - camera.y + this.bounceOffset + this.height / 2);
ctx.lineTo(this.x - camera.x + this.width, this.y - camera.y + this.bounceOffset + this.height / 2);
ctx.moveTo(this.x - camera.x + this.width / 2, this.y - camera.y + this.bounceOffset);
ctx.lineTo(this.x - camera.x + this.width / 2, this.y - camera.y + this.bounceOffset + this.height);
ctx.stroke();
}
}
}
// --- Enemy Base Class ---
class Enemy extends Entity {
constructor(x, y, width, height, scoreValue) {
super(x, y, width, height);
this.scoreValue = scoreValue; // Points awarded for defeating this enemy
this.facing = -1; // Default movement direction: left
}
// Checks if enemy needs to turn around due to hitting a wall or an edge (no ground ahead)
checkDirectionChange(blocks) {
let wallAhead = false;
let groundAhead = false;
// Predict a position slightly ahead of the enemy for wall detection
let nextX = this.x + this.facing * (this.width + 1);
let nextY = this.y;
for (const block of blocks) {
if (!block.isAlive || (block.type === BLOCK_TYPE_HIDDEN && block.hidden)) continue;
// Check for wall directly in front
if (nextX < block.x + block.width && nextX + this.width > block.x &&
nextY < block.y + block.height && nextY + this.height > block.y) {
wallAhead = true;
break;
}
}
// Check for ground (platform edge)
let groundCheckX = this.x + this.facing * (this.width / 2 + 1); // Check slightly ahead for ground
let groundCheckY = this.y + this.height + 1; // Check one pixel below enemy's feet
for (const block of blocks) {
if (!block.isAlive || (block.type === BLOCK_TYPE_HIDDEN && block.hidden)) continue;
if (groundCheckX < block.x + block.width && groundCheckX + 1 > block.x &&
groundCheckY < block.y + block.height && groundCheckY + 1 > block.y) {
groundAhead = true;
break;
}
}
// If a wall is ahead OR no ground is ahead, turn around
if (wallAhead || !groundAhead) {
this.facing *= -1; // Reverse direction
this.vx = ENEMY_SPEED * this.facing; // Update velocity based on new facing
return true;
}
return false;
}
}
// --- Goomba Class ---
class Goomba extends Enemy {
constructor(x, y) {
super(x, y, TILE_SIZE, TILE_SIZE, 100);
this.vx = ENEMY_SPEED * this.facing; // Initialize velocity
}
update() {
this.vx = ENEMY_SPEED * this.facing; // Ensure velocity matches facing
this.x += this.vx;
this.y += this.vy;
this.vy += GRAVITY; // Goombas are affected by gravity
this.checkDirectionChange(blocks); // Check for walls and edges to turn
}
draw(ctx, camera) {
ctx.fillStyle = "brown"; // Goomba body color
ctx.fillRect(this.x - camera.x, this.y - camera.y, this.width, this.height);
// Simple eyes
ctx.fillStyle = "black";
ctx.fillRect(this.x - camera.x + this.width * 0.2, this.y - camera.y + this.height * 0.2, this.width * 0.2, this.height * 0.2);
ctx.fillRect(this.x - camera.x + this.width * 0.6, this.y - camera.y + this.height * 0.2, this.width * 0.2, this.height * 0.2);
}
}
// --- Koopa Class ---
class Koopa extends Enemy {
constructor(x, y) {
super(x, y, TILE_SIZE, TILE_SIZE, 100);
this.state = KOOPA_WALKING; // Koopa's current state (walking, shell, sliding)
this.shellTimer = 0; // Timer for shell state
this.vx = ENEMY_SPEED * this.facing;
}
update() {
if (this.state === KOOPA_WALKING) {
this.vx = ENEMY_SPEED * this.facing;
this.checkDirectionChange(blocks); // Regular walking AI
} else if (this.state === KOOPA_SHELL) {
this.vx = 0; // Shell is stationary
this.shellTimer++;
if (this.shellTimer > 300) { // After 5 seconds (300 frames), Koopa gets up
this.state = KOOPA_WALKING;
this.shellTimer = 0;
this.facing *= -1; // Koopa turns around when getting up
}
} else if (this.state === KOOPA_SLIDING) {
// Sliding Koopa keeps its velocity until it hits a wall/edge or player
this.checkDirectionChange(blocks); // Still turns around at walls/edges
}
this.x += this.vx;
this.y += this.vy;
this.vy += GRAVITY; // Affected by gravity
}
draw(ctx, camera) {
let color = "green"; // Default Koopa color
if (this.state === KOOPA_SHELL || this.state === KOOPA_SLIDING) {
color = "darkgreen"; // Shell color
}
ctx.fillStyle = color;
ctx.fillRect(this.x - camera.x, this.y - camera.y, this.width, this.height);
if (this.state === KOOPA_WALKING) {
// Draw Koopa's body/shell top
ctx.fillStyle = "lightgreen";
ctx.fillRect(this.x - camera.x, this.y - camera.y, this.width, this.height / 2);
// Draw simple eyes
ctx.fillStyle = "white";
ctx.fillRect(this.x - camera.x + this.width * 0.2, this.y - camera.y + this.height * 0.2, this.width * 0.2, this.height * 0.2);
ctx.fillRect(this.x - camera.x + this.width * 0.6, this.y - camera.y + this.height * 0.2, this.width * 0.2, this.height * 0.2);
} else { // Shell state
// Draw a simple circular shell
ctx.fillStyle = "darkgreen";
ctx.beginPath();
ctx.arc(this.x - camera.x + this.width / 2, this.y - camera.y + this.height / 2, this.width / 2, 0, Math.PI * 2);
ctx.fill();
}
}
}
// --- Paratroopa Class (Flying Koopa) ---
class Paratroopa extends Koopa { // Paratroopa inherits from Koopa
constructor(x, y) {
super(x, y); // Call Koopa constructor
this.scoreValue = 200; // Higher score than regular Koopa
this.initialY = y; // Starting Y for vertical oscillation
this.amplitude = TILE_SIZE * 2; // Flies 2 tiles up and down
this.frequency = 0.05; // How fast it bobs up and down
this.vx = ENEMY_SPEED * this.facing;
}
update() {
if (this.state === KOOPA_WALKING) { // Only fly when in walking state (not shell)
this.x += this.vx;
// Vertical oscillation using sine wave
this.y = this.initialY + Math.sin(Date.now() * this.frequency) * this.amplitude;
this.checkDirectionChange(blocks); // Still turns around horizontally
this.vy = 0; // Override gravity effect for flying state
} else {
super.update(); // If in shell or sliding state, act like a regular Koopa
}
}
draw(ctx, camera) {
super.draw(ctx, camera); // Draw Koopa body
if (this.state === KOOPA_WALKING) { // Only draw wings when flying
ctx.fillStyle = "red"; // Wing color
// Draw simple triangular wings on both sides
ctx.beginPath();
ctx.moveTo(this.x - camera.x, this.y - camera.y + this.height / 2);
ctx.lineTo(this.x - camera.x - TILE_SIZE / 2, this.y - camera.y + TILE_SIZE / 4);
ctx.lineTo(this.x - camera.x - TILE_SIZE / 2, this.y - camera.y + TILE_SIZE * 0.75);
ctx.fill();
ctx.beginPath();
ctx.moveTo(this.x - camera.x + this.width, this.y - camera.y + this.height / 2);
ctx.lineTo(this.x - camera.x + this.width + TILE_SIZE / 2, this.y - camera.y + TILE_SIZE / 4);
ctx.lineTo(this.x - camera.x + this.width + TILE_SIZE / 2, this.y - camera.y + TILE_SIZE * 0.75);
ctx.fill();
}
}
}
// --- Collectible Base Class ---
class Collectible extends Entity {
constructor(x, y, type, scoreValue = 0) {
super(x, y, TILE_SIZE, TILE_SIZE);
this.type = type;
this.isCollected = false;
this.scoreValue = scoreValue;
this.initialY = y; // For initial upward bounce from block
}
update() {
// Collectibles from blocks pop up initially
if (this.y > this.initialY - TILE_SIZE) { // If it hasn't popped up enough
this.y += this.vy;
this.vy += GRAVITY; // Apply gravity to pull it down after initial pop
} else {
this.vy = 0; // Stop vertical movement from pop
this.y = this.initialY - TILE_SIZE; // Lock at max height
}
}
draw(ctx, camera) {
if (this.isCollected) return; // Don't draw if already collected
}
}
// --- Mushroom Class (Power-up) ---
class Mushroom extends Collectible {
constructor(x, y) {
super(x, y, CONTENT_MUSHROOM, 500);
this.vy = -5; // Initial upward velocity for pop-up
this.vx = ENEMY_SPEED; // Mushrooms move right after popping up
}
update() {
super.update(); // Handle initial pop-up
if (this.vy === 0) { // Once it has fully popped up and settled
this.x += this.vx;
this.y += this.vy;
this.vy += GRAVITY;
// Collision with blocks to turn around (similar to enemies)
for (const block of blocks) {
if (!block.isAlive || (block.type === BLOCK_TYPE_HIDDEN && block.hidden)) continue;
if (this.collidesWith(block)) {
// Simple horizontal bounce and push out
if (this.x + this.width > block.x && this.x < block.x + block.width) {
this.vx *= -1; // Turn around
if (this.x < block.x) this.x = block.x - this.width;
else this.x = block.x + block.width;
}
// Vertical collision (e.g., landing on a block)
if (this.y + this.height > block.y && this.y < block.y + block.height) {
if (this.vy > 0) { // Falling, hit top of block
this.y = block.y - this.height;
this.vy = 0;
} else { // Hit bottom of block (unlikely)
this.y = block.y + block.height;
this.vy = 0;
}
}
}
}
}
}
draw(ctx, camera) {
if (this.isCollected) return;
ctx.fillStyle = "red"; // Mushroom cap
ctx.fillRect(this.x - camera.x, this.y - camera.y, this.width, this.height / 2);
ctx.fillStyle = "white"; // Mushroom stem
ctx.fillRect(this.x - camera.x, this.y - camera.y + this.height / 2, this.width, this.height / 2);
}
}
// --- Fire Flower Class (Power-up) ---
class FireFlower extends Collectible {
constructor(x, y) {
super(x, y, CONTENT_FIRE_FLOWER, 700);
this.vy = -5; // Initial upward velocity for pop-up
}
update() {
super.update(); // Fire flowers just pop up and stay
}
draw(ctx, camera) {
if (this.isCollected) return;
ctx.fillStyle = "orange"; // Outer petals
ctx.fillRect(this.x - camera.x, this.y - camera.y, this.width, this.height);
ctx.fillStyle = "red"; // Inner center
ctx.fillRect(this.x - camera.x + this.width * 0.2, this.y - camera.y + this.height * 0.2, this.width * 0.6, this.height * 0.6);
}
}
// --- 1-Up Mushroom Class (Extra Life) ---
class OneUp extends Collectible {
constructor(x, y) {
super(x, y, CONTENT_ONE_UP, 1000);
this.vy = -5; // Initial upward velocity for pop-up
this.vx = ENEMY_SPEED; // 1-Up mushrooms also move right
}
update() {
super.update(); // Handle initial pop-up
if (this.vy === 0) { // Once it has fully popped up and settled
this.x += this.vx;
this.y += this.vy;
this.vy += GRAVITY;
for (const block of blocks) {
if (!block.isAlive || (block.type === BLOCK_TYPE_HIDDEN && block.hidden)) continue;
if (this.collidesWith(block)) {
// Simple horizontal bounce and push out
if (this.x + this.width > block.x && this.x < block.x + block.width) {
this.vx *= -1; // Turn around
if (this.x < block.x) this.x = block.x - this.width;
else this.x = block.x + block.width;
}
// Vertical collision (e.g., landing)
if (this.y + this.height > block.y && this.y < block.y + block.height) {
if (this.vy > 0) { // Falling, hit top of block
this.y = block.y - this.height;
this.vy = 0;
} else { // Hit bottom of block (unlikely)
this.y = block.y + block.height;
this.vy = 0;
}
}
}
}
}
}
draw(ctx, camera) {
if (this.isCollected) return;
ctx.fillStyle = "lightgreen"; // 1-Up mushroom cap
ctx.fillRect(this.x - camera.x, this.y - camera.y, this.width, this.height / 2);
ctx.fillStyle = "white"; // 1-Up mushroom stem
ctx.fillRect(this.x - camera.x, this.y - camera.y + this.height / 2, this.width, this.height / 2);
ctx.fillStyle = "black";
ctx.font = `${TILE_SIZE / 2}px 'Press Start 2P'`;
ctx.textAlign = "center";
ctx.fillText("1UP", this.x - camera.x + this.width / 2, this.y - camera.y + this.height * 0.75);
}
}
// --- Coin Class ---
class Coin extends Collectible {
constructor(x, y) {
super(x, y, CONTENT_COIN, 200);
this.vy = -8; // Initial upward velocity for coin pop animation
this.lifeTime = 30; // Frames until coin disappears (approx 0.5 seconds)
}
update() {
if (this.isCollected) return; // Coins are marked collected on collision, then animate to disappear
this.y += this.vy;
this.vy += GRAVITY * 2; // Faster gravity for coin animation
this.lifeTime--;
if (this.lifeTime <= 0) {
this.isCollected = true; // Mark for removal from array
coins++; // Add to coin counter
score += this.scoreValue; // Add to score
}
}
draw(ctx, camera) {
if (this.isCollected) return;
ctx.fillStyle = "gold"; // Coin color
ctx.beginPath();
ctx.arc(this.x - camera.x + this.width / 2, this.y - camera.y + this.height / 2, this.width / 2, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = "darkgoldenrod";
ctx.font = `${TILE_SIZE * 0.7}px 'Press Start 2P'`;
ctx.textAlign = "center";
ctx.textBaseline = "middle"; // Center text vertically
ctx.fillText("$", this.x - camera.x + this.width / 2, this.y - camera.y + this.height / 2 + 2); // Simple dollar sign
}
}
// --- Camera Class ---
class Camera {
constructor(x, y, width, height, worldWidth, worldHeight) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.worldWidth = worldWidth; // Total width of the level
this.worldHeight = worldHeight; // Total height of the level
}
update(player) {
// Horizontal camera: Keep player centered, but clamp to world bounds
this.x = Math.max(0, Math.min(player.x - this.width / 2, this.worldWidth - this.width));
// Vertical camera: Keep player in the lower middle of the screen
const targetY = player.y - this.height * 0.6; // Player should be around 60% from top
this.y = Math.max(0, Math.min(targetY, this.worldHeight - this.height));
// Prevent camera from going above world height if level is shorter than screen
if (this.worldHeight < this.height) {
this.y = 0;
}
}
}
// --- Game Initialization ---
function initGame() {
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;
// Reset game state
player = new Player(0, 0); // Player start position will be set by level map
blocks = [];
enemies = [];
collectibles = [];
fireballs = [];
coins = 0;
score = 0;
gameOver = false;
gameRestarting = false;
gameRestartTimer = 0;
levelWidth = levelMap[0].length * TILE_SIZE;
let worldHeight = levelMap.length * TILE_SIZE;
camera = new Camera(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT, levelWidth, worldHeight);
// Parse the level map to populate game objects
for (let row = 0; row < levelMap.length; row++) {
for (let col = 0; col < levelMap[row].length; col++) {
const char = levelMap[row][col];
const x = col * TILE_SIZE;
const y = row * TILE_SIZE;
switch (char) {
case 'P': blocks.push(new Block(x, y, BLOCK_TYPE_SOLID)); break;
case 'Q': blocks.push(new Block(x, y, BLOCK_TYPE_QUESTION, CONTENT_MUSHROOM)); break;
case 'F': blocks.push(new Block(x, y, BLOCK_TYPE_QUESTION, CONTENT_FIRE_FLOWER)); break;
case 'M': blocks.push(new Block(x, y, BLOCK_TYPE_QUESTION, CONTENT_ONE_UP)); break;
case 'B': blocks.push(new Block(x, y, BLOCK_TYPE_BRICK)); break;
case 'H': blocks.push(new Block(x, y, BLOCK_TYPE_HIDDEN, CONTENT_COIN)); break; // Default hidden block holds a coin
case 'G': enemies.push(new Goomba(x, y)); break;
case 'K': enemies.push(new Koopa(x, y)); break;
case 'A': enemies.push(new Paratroopa(x, y)); break;
case 'S': player.x = x; player.y = y; break; // Set player's starting position
}
}
}
gameRunning = true; // Start the game loop
}
// --- Game Loop ---
let lastTime = 0;
function gameLoop(currentTime) {
if (!gameRunning) return; // Stop if game is not running
const deltaTime = (currentTime - lastTime) / 1000; // Calculate delta time (time since last frame)
lastTime = currentTime;
update(deltaTime); // Update game logic
draw(); // Redraw all game elements
requestAnimationFrame(gameLoop); // Request next frame
}
// --- Update Game State ---
function update(deltaTime) {
if (gameOver) {
if (keys['r']) { // Press 'R' to restart after Game Over
initGame();
}
return;
}
if (gameRestarting) {
gameRestartTimer--;
if (gameRestartTimer <= 0) {
if (player.lives <= 0) {
gameOver = true; // No lives left, show Game Over screen
gameRunning = false;
} else {
// Respawn: Re-initialize level to reset positions, blocks, enemies
initGame();
}
}
return;
}
player.update(); // Update player state
camera.update(player); // Update camera position
// Update all dynamic entities
enemies.forEach(enemy => enemy.update());
blocks.forEach(block => block.update());
collectibles.forEach(collectible => collectible.update());
// --- Collision Detection ---
// Player - Block collisions
player.onGround = false; // Assume not on ground until collision confirms
for (const block of blocks.filter(b => b.isAlive && !(b.type === BLOCK_TYPE_HIDDEN && b.hidden))) {
if (player.collidesWith(block)) {
// Calculate overlap to determine collision axis
const overlapX = Math.min(player.x + player.width, block.x + block.width) - Math.max(player.x, block.x);
const overlapY = Math.min(player.y + player.height, block.y + block.height) - Math.max(player.y, block.y);
if (overlapX > 0 && overlapY > 0) {
if (overlapX < overlapY) { // Horizontal collision
if (player.vx > 0) { // Moving right, hit left side of block
player.x = block.x - player.width;
} else if (player.vx < 0) { // Moving left, hit right side of block
player.x = block.x + block.width;
}
player.vx = 0; // Stop horizontal movement
} else { // Vertical collision
if (player.vy > 0) { // Falling, hit top of block
player.y = block.y - player.height;
player.vy = 0;
player.onGround = true; // Mark as on ground
player.isJumping = false;
} else if (player.vy < 0) { // Jumping up, hit bottom of block
player.y = block.y + block.height;
player.vy = 0;
block.hit(player); // Trigger block's hit logic
}
}
}
}
}
// Fireball - Block collisions
player.fireballs.forEach(fireball => {
for (const block of blocks.filter(b => b.isAlive && !(b.type === BLOCK_TYPE_HIDDEN && b.hidden))) {
if (fireball.collidesWith(block)) {
const overlapX = Math.min(fireball.x + fireball.width, block.x + block.width) - Math.max(fireball.x, block.x);
const overlapY = Math.min(fireball.y + fireball.height, block.y + block.height) - Math.max(fireball.y, block.y);
if (overlapX > 0 && overlapY > 0) {
if (overlapX < overlapY) { // Horizontal collision
fireball.vx *= -1; // Bounce horizontally
// Push out of block
if (fireball.x < block.x) fireball.x = block.x - fireball.width;
else fireball.x = block.x + block.width;
fireball.bounces++;
} else { // Vertical collision
if (fireball.vy > 0) { // Falling, hit top of block
fireball.y = block.y - fireball.height;
fireball.vy = -FIREBALL_SPEED * 0.7; // Bounce up
fireball.bounces++;
} else { // Hit bottom of block (unlikely for fireball)
fireball.y = block.y + block.height;
fireball.vy = 0;
}
}
}
}
}
// Remove fireball if too many bounces or goes off screen
if (fireball.bounces >= fireball.maxBounces || fireball.x < camera.x - TILE_SIZE || fireball.x > camera.x + camera.width + TILE_SIZE) {
fireball.isAlive = false;
}
});
// Enemy - Block collisions (for horizontal movement and falling)
enemies.forEach(enemy => {
enemy.onGround = false;
for (const block of blocks.filter(b => b.isAlive && !(b.type === BLOCK_TYPE_HIDDEN && b.hidden))) {
if (enemy.collidesWith(block)) {
const overlapX = Math.min(enemy.x + enemy.width, block.x + block.width) - Math.max(enemy.x, block.x);
const overlapY = Math.min(enemy.y + enemy.height, block.y + block.height) - Math.max(enemy.y, block.y);
if (overlapX > 0 && overlapY > 0) {
if (overlapX < overlapY) { // Horizontal collision
if (enemy instanceof Koopa && enemy.state === KOOPA_SLIDING) {
enemy.vx *= -1; // Sliding shells reverse
enemy.facing *= -1; // Update facing
} else {
enemy.facing *= -1; // Turn around for walking enemies
enemy.vx = ENEMY_SPEED * enemy.facing; // Update velocity
}
// Push enemy out of block
if (enemy.x < block.x) enemy.x = block.x - enemy.width;
else enemy.x = block.x + block.width;
} else { // Vertical collision
if (enemy.vy > 0) { // Falling, hit top of block
enemy.y = block.y - enemy.height;
enemy.vy = 0;
enemy.onGround = true;
} else if (enemy.vy < 0) { // Hit bottom of block
enemy.y = block.y + block.height;
enemy.vy = 0;
}
}
}
}
}
});
// Player - Enemy collisions
enemies = enemies.filter(enemy => enemy.isAlive); // Remove dead enemies from array
for (let i = enemies.length - 1; i >= 0; i--) {
const enemy = enemies[i];
if (!enemy.isAlive) continue; // Skip if already dead
// Check collision between Player and Enemy
if (player.collidesWith(enemy)) {
if (player.isDying) continue; // Player is already dying, no further interaction
// Stomp condition: player is falling and player's bottom hits enemy's top
// Also check if player's previous Y position was above enemy's top
if (player.vy > 0 && player.y + player.height > enemy.y && player.y + player.height - player.vy <= enemy.y + TILE_SIZE / 4) {
// Player successfully stomped on the enemy
if (enemy instanceof Paratroopa) {
// Paratroopa converts to a walking Koopa when stomped
const newKoopa = new Koopa(enemy.x, enemy.y);
newKoopa.vx = enemy.vx; // Maintain horizontal direction
enemies[i] = newKoopa; // Replace Paratroopa in the array
score += enemy.scoreValue;
} else if (enemy instanceof Koopa && enemy.state === KOOPA_WALKING) {
// Walking Koopa retreats into shell when stomped
enemy.state = KOOPA_SHELL;
enemy.shellTimer = 0;
score += enemy.scoreValue;
} else if (enemy instanceof Koopa && (enemy.state === KOOPA_SHELL || enemy.state === KOOPA_SLIDING)) {
// Kick shell if it's already a shell or sliding
enemy.state = KOOPA_SLIDING;
enemy.facing = player.facing; // Kick in the direction player is facing
enemy.vx = enemy.facing * FIREBALL_SPEED * 1.5; // Shell moves faster when kicked
score += 200; // More points for kicking a shell
} else { // Goomba
enemy.isAlive = false; // Goomba dies instantly
score += enemy.scoreValue;
}
player.vy = -PLAYER_JUMP_FORCE * 0.5; // Player bounces up after stomping
} else {
// Side collision or player hit from below: Mario takes damage
player.takeHit();
}
}
// Fireball - Enemy collisions
for (let j = player.fireballs.length - 1; j >= 0; j--) {
const fireball = player.fireballs[j];
if (fireball.isAlive && fireball.collidesWith(enemy)) {
if (enemy instanceof Koopa && (enemy.state === KOOPA_SHELL || enemy.state === KOOPA_SLIDING)) {
// Fireball destroys Koopa shell (simplification from original Mario)
enemy.isAlive = false;
fireball.isAlive = false;
score += enemy.scoreValue;
} else if (enemy instanceof Paratroopa) {
// Fireball hits Paratroopa, it turns into a walking Koopa
const newKoopa = new Koopa(enemy.x, enemy.y);
newKoopa.vx = enemy.vx; // Maintain horizontal direction
enemies[i] = newKoopa;
fireball.isAlive = false;
score += enemy.scoreValue;
} else { // Goomba or regular walking Koopa
enemy.isAlive = false; // Enemy dies
fireball.isAlive = false; // Fireball disappears
score += enemy.scoreValue;
}
}
}
// Koopa Shell - Other Enemies collisions (if shell is sliding)
if (enemy instanceof Koopa && enemy.state === KOOPA_SLIDING) {
for (let k = enemies.length - 1; k >= 0; k--) {
const otherEnemy = enemies[k];
if (otherEnemy !== enemy && otherEnemy.isAlive && enemy.collidesWith(otherEnemy)) {
if (otherEnemy instanceof Koopa && (otherEnemy.state === KOOPA_SHELL || otherEnemy.state === KOOPA_SLIDING)) {
// Sliding shells collide with each other, both turn around
enemy.vx *= -1;
enemy.facing *= -1;
otherEnemy.vx *= -1;
otherEnemy.facing *= -1;
} else {
otherEnemy.isAlive = false; // Shell kills other enemies
score += otherEnemy.scoreValue * 2; // Extra points for shell kill
}
}
}
}
}
// Player - Collectible collisions
for (let i = collectibles.length - 1; i >= 0; i--) {
const collectible = collectibles[i];
if (!collectible.isCollected && player.collidesWith(collectible)) {
collectible.isCollected = true; // Mark as collected
score += collectible.scoreValue;
switch (collectible.type) {
case CONTENT_MUSHROOM:
if (player.state === PLAYER_STATE_SMALL) {
player.state = PLAYER_STATE_BIG;
// Adjust player Y position so bottom stays fixed when growing
player.y -= TILE_SIZE;
}
break;
case CONTENT_FIRE_FLOWER:
player.state = PLAYER_STATE_FIRE;
// Adjust player Y position if currently small Mario
if (player.height === TILE_SIZE) player.y -= TILE_SIZE;
break;
case CONTENT_ONE_UP:
player.lives++;
break;
case CONTENT_COIN:
coins++; // Coin collected on collision
break;
}
}
}
// Filter out inactive entities from arrays
enemies = enemies.filter(e => e.isAlive);
// Coins remain in array to complete their pop-up animation, others are removed immediately
collectibles = collectibles.filter(c => !c.isCollected || (c instanceof Coin && c.lifeTime > 0));
player.fireballs = player.fireballs.filter(fb => fb.isAlive);
blocks = blocks.filter(b => b.isAlive); // Remove broken blocks
}
// --- Draw Game Elements ---
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
ctx.fillStyle = "#87CEEB"; // Sky blue background
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw blocks
for (const block of blocks) {
block.draw(ctx, camera);
}
// Draw enemies
for (const enemy of enemies) {
enemy.draw(ctx, camera);
}
// Draw player
player.draw(ctx, camera);
// Draw collectibles
for (const collectible of collectibles) {
collectible.draw(ctx, camera);
}
// Draw HUD (Score, Coins, Lives)
ctx.fillStyle = "white";
ctx.font = "20px 'Press Start 2P', cursive";
ctx.textAlign = "left";
ctx.fillText(`SCORE: ${score}`, 20, 30);
ctx.fillText(`COINS: ${coins}`, 20, 60);
ctx.fillText(`LIVES: ${player.lives}`, 20, 90);
// Display Game Over or "Lost a Life" screens
if (gameOver) {
ctx.fillStyle = "rgba(0, 0, 0, 0.7)"; // Semi-transparent black overlay
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "white";
ctx.font = "40px 'Press Start 2P', cursive";
ctx.textAlign = "center";
ctx.fillText("GAME OVER", canvas.width / 2, canvas.height / 2 - 30);
ctx.font = "20px 'Press Start 2P', cursive";
ctx.fillText("Press 'R' to Restart", canvas.width / 2, canvas.height / 2 + 20);
} else if (gameRestarting) {
ctx.fillStyle = "rgba(0, 0, 0, 0.7)"; // Semi-transparent black overlay
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "white";
ctx.font = "40px 'Press Start 2P', cursive";
ctx.textAlign = "center";
ctx.fillText("LOST A LIFE", canvas.width / 2, canvas.height / 2 - 30);
ctx.font = "20px 'Press Start 2P', cursive";
ctx.fillText(`Lives remaining: ${player.lives}`, canvas.width / 2, canvas.height / 2 + 20);
}
}
// --- Event Listeners for Input ---
window.addEventListener('keydown', (e) => {
keys[e.key.toLowerCase()] = true; // Store pressed key (convert to lowercase for consistency)
if (e.key.toLowerCase() === 'z' || e.key.toLowerCase() === 'x') { // Fireball keys
e.preventDefault(); // Prevent default browser actions (e.g., zoom for 'x')
player.shootFireball();
}
if (e.key === ' ') { // Spacebar for jump
e.preventDefault(); // Prevent default browser action (e.g., page scroll)
}
});
window.addEventListener('keyup', (e) => {
keys[e.key.toLowerCase()] = false; // Mark key as released
});
// --- Game Start ---
window.onload = () => {
// Attempt to load 'Press Start 2P' font from Google Fonts
const font = new FontFace('Press Start 2P', 'url(https://fonts.gstatic.com/s/pressstart2p/v15/nuFvY_SUo0z2lNLK8tV_7pbGMzJz-hU.woff2)');
font.load().then(function(loadedFont) {
document.fonts.add(loadedFont);
console.log('Font "Press Start 2P" loaded.');
initGame(); // Initialize the game once font is loaded
requestAnimationFrame(gameLoop); // Start the game loop
}).catch(function(error) {
console.error('Font "Press Start 2P" failed to load, using fallback:', error);
// If font fails to load, proceed with fallback fonts (monospace)
initGame();
requestAnimationFrame(gameLoop);
});
};
</script>
</body>
</html>