Okay, creating a full-fledged fighting game in just HTML is impossible, as games require dynamic behavior and logic. HTML provides the structure. We'll need CSS for styling and, critically, JavaScript for the game's logic (movement, combat, enemy AI, scoring, etc.).
Here's a basic structure using HTML, CSS, and JavaScript to get you started with the core idea:
1. index.html (The Structure)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Web Fighter</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="game-container">
<div id="score-display">Score: 0</div>
<div id="player-health">Health: 100</div>
<div id="game-area">
<!-- Player character will be here -->
<div id="player"></div>
<!-- Enemies will be added here by JavaScript -->
<div class="enemy" data-id="enemy-1"></div>
<div class="enemy" data-id="enemy-2"></div>
<div class="enemy" data-id="enemy-3"></div>
</div>
<div id="game-message" class="hidden"></div>
<div id="controls">
<button id="btn-left">Left</button>
<button id="btn-attack">Attack</button>
<button id="btn-right">Right</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Explanation:
<!DOCTYPE html>: Standard HTML5 declaration.
<html lang="en">: Root element.
<head>: Contains meta-information.
<meta charset="UTF-8">: Character encoding.
<meta name="viewport"...>: Ensures responsiveness on different devices.
<title>: Title shown in browser tab.
<link rel="stylesheet" href="style.css">: Links the CSS file for styling.
<body>: Contains the visible page content.
<div id="game-container">: A main wrapper for the entire game area and UI.
<div id="score-display">: Displays the player's score.
<div id="player-health">: Displays the player's health.
<div id="game-area">: The stage where the fighting happens.
<div id="player">: Represents the main character.
<div class="enemy" ...>: Represents initial enemies. More will be added/removed dynamically by JavaScript. data-id is a custom attribute to easily reference them later if needed.
<div id="game-message" class="hidden">: Used to show messages like "Game Over" or "Wave Complete". Initially hidden.
<div id="controls">: Contains the buttons for player actions (useful for touch or simple click controls).
<button> elements for Left, Attack, Right.
<script src="script.js"></script>: Links the JavaScript file. Placed at the end of the body so it runs after the HTML elements are created.
2. style.css (The Appearance)
body {
margin: 0;
padding: 0;
background-color: #f0f0f0;
font-family: sans-serif;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh; /* Center content vertically */
}
#game-container {
width: 600px;
height: 400px;
border: 1px solid #333;
background-color: #fff;
position: relative; /* Allows absolute positioning of children */
overflow: hidden; /* Hide anything outside the game area */
box-shadow: 0 0 10px rgba(0,0,0,0.2);
}
#score-display, #player-health {
position: absolute;
top: 10px;
padding: 5px 10px;
background-color: rgba(0, 0, 0, 0.7);
color: white;
font-size: 14px;
z-index: 10; /* Make sure they are above game elements */
}
#score-display {
left: 10px;
}
#player-health {
right: 10px;
}
#game-area {
width: 100%;
height: 300px; /* Height for the fighting area */
position: relative; /* Crucial for positioning player/enemies */
top: 40px; /* Give space for score/health */
background-color: #e0e0e0; /* Ground/background color */
}
#player {
width: 40px;
height: 50px;
background-color: blue;
position: absolute; /* Position relative to game-area */
bottom: 10px; /* Player stands near the bottom */
left: 50px; /* Starting horizontal position */
transition: left 0.1s ease-out; /* Smooth movement */
}
.enemy {
width: 40px;
height: 50px;
background-color: red;
position: absolute; /* Position relative to game-area */
bottom: 10px; /* Enemies stand near the bottom */
right: 50px; /* Starting horizontal position for enemies */
transition: left 0.1s linear; /* Can animate movement */
}
#game-message {
position: absolute;
top: 50%;
left: 0;
width: 100%;
text-align: center;
font-size: 24px;
color: #333;
z-index: 20;
transform: translateY(-50%);
}
.hidden {
display: none;
}
#controls {
position: absolute;
bottom: 10px;
left: 0;
width: 100%;
text-align: center;
z-index: 10;
}
#controls button {
padding: 10px 20px;
margin: 0 5px;
font-size: 16px;
cursor: pointer;
}
Explanation:
- Basic body styling for centering.
#game-container: Sets the overall size, border, and makes it a positioning context (position: relative).
#score-display, #player-health: Positioned absolutely at the top corners, semi-transparent background, text styling. z-index ensures they are on top.
#game-area: Defines the space for action, positioned below the info displays. position: relative is crucial for positioning the player and enemies within it.
#player, .enemy: Styled as colored rectangles (div). position: absolute places them precisely within #game-area. bottom: 10px puts them slightly above the bottom edge. left and right are starting positions. transition adds simple movement animation.
#game-message: Positioned in the center of the container, hidden by default.
.hidden: A utility class to hide elements.
#controls: Positioned at the bottom for the buttons.
3. script.js (The Logic)
This is where the actual game rules and interactions are defined. This example provides a very basic framework:
// --- Game State Variables ---
const player = {
element: document.getElementById('player'),
x: 50, // Initial X position (relative to game-area)
speed: 5, // Pixels per step
health: 100,
attackRange: 70, // Horizontal range to hit enemies
attackDamage: 20,
isAttacking: false // Flag to track if player is in attack state
};
const enemies = []; // Array to hold enemy objects
const gameArea = document.getElementById('game-area');
const gameAreaWidth = gameArea.offsetWidth; // Get actual width
const gameAreaHeight = gameArea.offsetHeight; // Get actual height (might not need Y for simple horizontal)
let score = 0;
let gameLoopInterval; // To hold the interval ID for the game loop
// --- DOM Elements ---
const scoreDisplay = document.getElementById('score-display');
const healthDisplay = document.getElementById('player-health');
const gameMessage = document.getElementById('game-message');
const btnLeft = document.getElementById('btn-left');
const btnRight = document.getElementById('btn-right');
const btnAttack = document.getElementById('btn-attack');
// --- Game Functions ---
// Update the player's visual position on screen
function updatePlayerPosition() {
player.element.style.left = player.x + 'px';
}
// Update score and health displays
function updateDisplay() {
scoreDisplay.textContent = `Score: ${score}`;
healthDisplay.textContent = `Health: ${player.health}`;
}
// Spawn enemies
function spawnEnemy(initialRightPosition = 50) {
const enemyElement = document.createElement('div');
enemyElement.classList.add('enemy');
// Assign a unique ID or just store properties in the object
const enemy = {
element: enemyElement,
x: gameAreaWidth - initialRightPosition - enemyElement.offsetWidth, // Calculate X from right
speed: Math.random() * 2 + 1, // Random speed between 1 and 3
health: 40,
damage: 10 // Damage dealt to player on collision
};
enemyElement.style.left = enemy.x + 'px'; // Set initial position
gameArea.appendChild(enemyElement); // Add to game area
enemies.push(enemy); // Add to our enemies array
}
// Update enemy positions and handle movement
function updateEnemies() {
for (let i = enemies.length - 1; i >= 0; i--) {
const enemy = enemies[i];
// Move enemy towards the player (simple horizontal tracking)
if (enemy.x > player.x) {
enemy.x -= enemy.speed;
} else {
enemy.x += enemy.speed;
}
// Keep enemy within bounds (optional but good practice)
enemy.x = Math.max(0, Math.min(enemy.x, gameAreaWidth - enemy.element.offsetWidth));
// Update enemy's visual position
enemy.element.style.left = enemy.x + 'px';
// --- Check for collision with player ---
// Simple AABB collision check (Axis-Aligned Bounding Box)
const playerRect = player.element.getBoundingClientRect();
const enemyRect = enemy.element.getBoundingClientRect();
const gameAreaRect = gameArea.getBoundingClientRect(); // Get game area position relative to viewport
// Adjust rect positions relative to the game-area for collision logic
const playerRelativeRect = {
left: playerRect.left - gameAreaRect.left,
right: playerRect.right - gameAreaRect.left,
top: playerRect.top - gameAreaRect.top,
bottom: playerRect.bottom - gameAreaRect.top
};
const enemyRelativeRect = {
left: enemyRect.left - gameAreaRect.left,
right: enemyRect.right - gameAreaRect.left,
top: enemyRect.top - gameAreaRect.top,
bottom: enemyRect.bottom - gameAreaRect.top
};
// Check for overlap
const isCollidingWithPlayer = !(
playerRelativeRect.right < enemyRelativeRect.left ||
playerRelativeRect.left > enemyRelativeRect.right ||
playerRelativeRect.bottom < enemyRelativeRect.top ||
playerRelativeRect.top > enemyRelativeRect.bottom
);
if (isCollidingWithPlayer) {
takeDamage('player', enemy.damage);
// Optional: Push enemy back slightly or deal damage over time
}
}
}
// Player attacks
function playerAttack() {
if (player.isAttacking) return; // Prevent spamming
player.isAttacking = true;
// Optional: Add an attack animation class
// player.element.classList.add('attacking');
// Check for enemies within attack range
for (let i = enemies.length - 1; i >= 0; i--) {
const enemy = enemies[i];
// Calculate horizontal distance
const distance = Math.abs(player.x - enemy.x);
// Check if enemy is within attack range horizontally
if (distance < player.attackRange) {
takeDamage(enemy, player.attackDamage);
}
}
// End attack state after a short duration
setTimeout(() => {
player.isAttacking = false;
// Optional: Remove attack animation class
// player.element.classList.remove('attacking');
}, 300); // Attack lasts 300ms
}
// Apply damage to a target (player or enemy object)
function takeDamage(target, amount) {
target.health -= amount;
if (target === player) {
if (player.health < 0) player.health = 0; // Don't show negative health
updateDisplay();
if (player.health <= 0) {
gameOver();
}
} else { // Assuming target is an enemy object
if (target.health <= 0) {
removeEnemy(target);
score += 10; // Increase score for defeating enemy
updateDisplay();
// Check if all enemies are defeated
if (enemies.length === 0) {
setTimeout(nextWave, 1000); // Start next wave after a delay
}
}
}
}
// Remove enemy from game
function removeEnemy(enemy) {
enemy.element.remove(); // Remove from DOM
const index = enemies.indexOf(enemy);
if (index > -1) {
enemies.splice(index, 1); // Remove from array
}
}
// Game Over sequence
function gameOver() {
clearInterval(gameLoopInterval); // Stop the game loop
gameMessage.textContent = 'Game Over!';
gameMessage.classList.remove('hidden');
// Disable controls? Reload button?
}
// Start next wave (simple: just spawn more enemies)
function nextWave() {
gameMessage.textContent = 'Wave Clear!';
gameMessage.classList.remove('hidden');
// Clear message after a delay and spawn enemies
setTimeout(() => {
gameMessage.classList.add('hidden');
const numEnemies = 3 + Math.floor(score / 50); // Spawn more enemies based on score
for(let i = 0; i < numEnemies; i++) {
// Spawn enemies at varying positions on the right
spawnEnemy(50 + i * 60);
}
}, 2000); // Show message for 2 seconds
}
// Game Loop function - runs repeatedly
function gameLoop() {
if (player.health <= 0) return; // Stop loop logic if game is over
// Update player position based on input flags (if using keyboard, otherwise buttons handle directly)
// (For button controls, movement is handled by button clicks directly)
updateEnemies(); // Move enemies and check collisions
// Other game logic (e.g., check win conditions)
// Check if game is over (redundant check, but good practice)
if (player.health <= 0) {
gameOver();
}
}
// --- Event Listeners for Controls ---
btnLeft.addEventListener('mousedown', () => { // mousedown allows holding button
// Simple move: Update position directly
player.x -= player.speed;
// Keep player within left bound
player.x = Math.max(0, player.x);
updatePlayerPosition();
});
btnRight.addEventListener('mousedown', () => { // mousedown allows holding button
// Simple move: Update position directly
// Need the player element's current width to stay within bounds
const playerWidth = player.element.offsetWidth;
player.x += player.speed;
// Keep player within right bound
player.x = Math.min(player.x, gameAreaWidth - playerWidth);
updatePlayerPosition();
});
btnAttack.addEventListener('click', playerAttack);
// --- Initialization ---
function initGame() {
// Reset state
player.health = 100;
score = 0;
enemies.forEach(enemy => enemy.element.remove()); // Remove existing enemy elements
enemies.length = 0; // Clear the array
updateDisplay();
updatePlayerPosition();
gameMessage.classList.add('hidden');
// Spawn initial enemies
for(let i = 0; i < 3; i++) {
spawnEnemy(50 + i * 60); // Spawn 3 enemies slightly apart on the right
}
// Start the game loop (updates ~60 times per second)
gameLoopInterval = setInterval(gameLoop, 1000 / 60); // 60 FPS
}
// Start the game when the page loads
initGame();
// Optional: Add keyboard controls
document.addEventListener('keydown', (event) => {
const playerWidth = player.element.offsetWidth;
switch (event.key) {
case 'ArrowLeft':
player.x -= player.speed * 5; // Move a bit faster with keys
player.x = Math.max(0, player.x);
updatePlayerPosition();
break;
case 'ArrowRight':
player.x += player.speed * 5; // Move a bit faster with keys
player.x = Math.min(player.x, gameAreaWidth - playerWidth);
updatePlayerPosition();
break;
case ' ': // Space bar for attack
playerAttack();
break;
}
});
Explanation:
- State Variables: Objects and arrays (
player, enemies) store the dynamic data of the game elements (position, health, speed, etc.). Simple variables track score and game state.
- DOM Elements: Get references to the HTML elements the script needs to interact with.
updatePlayerPosition(): Reads the player.x value and updates the CSS left style of the player element.
updateDisplay(): Updates the text content of the score and health elements.
spawnEnemy(): Creates a new enemy div, styles it, adds it to the game-area in the HTML, and adds a corresponding enemy object to the enemies array.
updateEnemies(): This is a core part of the game loop. It iterates through the enemies array:
- Moves each enemy horizontally towards the player's current
x position.
- Updates the enemy's visual position in the DOM.
- Performs a simple collision check between the player and each enemy using
getBoundingClientRect(). If they collide, the player takes damage.
playerAttack(): Triggered when the attack button is pressed or attack key is hit.
- Checks if the player is already attacking.
- Sets an
isAttacking flag (though not heavily used for visuals in this basic version).
- Iterates through enemies and checks if their horizontal position is within the player's
attackRange.
- If an enemy is within range, calls
takeDamage() on that enemy.
- Uses
setTimeout to reset the isAttacking flag after a brief period.
takeDamage(): Handles reducing health for either the player or an enemy.
- If health drops to 0 or less, it calls
gameOver() for the player or removeEnemy() and updates the score for an enemy.
removeEnemy(): Removes an enemy's div from the HTML and its object from the enemies array.
gameOver(): Stops the main game loop and displays a "Game Over" message.
- Called when all enemies are defeated. Displays a "Wave Clear" message briefly, then spawns a new set of enemies (potentially more than the previous wave).
To Run This Code:
- Save the first block as
index.html.
- Save the second block as
style.css in the same folder.
- Save the third block as
script.js in the same folder.
- Open the
index.html file in your web browser.
This provides a very simple foundation. You can build upon this by:
- Adding more complex animations (CSS classes and JS to toggle them).
- Different enemy types with varying behaviors.
- More sophisticated combat (combos, special moves, hitboxes).
- Score system and win conditions.
- Sound effects and music.
- Better visual feedback for attacks and damage.
- Keyboard event listeners for movement and attack instead of or in addition to buttons.