Area_and_Perimeter / index.html
Pp's picture
Update index.html
0b63f64 verified
raw
history blame
3.74 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Area & Perimeter Adventure</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="game-container">
<h1>🏰 Area & Perimeter Adventure 🏰</h1>
<div class="controls">
<button id="add-mode" class="mode-active">✏️ Add Squares</button>
<button id="erase-mode">🧽 Erase Squares</button>
</div>
<div class="grid-wrapper">
<div class="grid" id="grid"></div>
</div>
<div class="stats">
<div class="stat-box">
<div>Area:</div>
<div class="stat-value"><span id="area">0</span> 🟩</div>
</div>
<div class="stat-box">
<div>Perimeter:</div>
<div class="stat-value"><span id="perimeter">0</span> πŸ“</div>
</div>
</div>
</div>
<script>
const gridSize = 15;
const grid = document.getElementById('grid');
const areaDisplay = document.getElementById('area');
const perimeterDisplay = document.getElementById('perimeter');
const addModeBtn = document.getElementById('add-mode');
const eraseModeBtn = document.getElementById('erase-mode');
let mode = 'add';
let filledCells = new Set();
// Initialize grid
function initGrid() {
grid.innerHTML = '';
for (let i = 0; i < gridSize * gridSize; i++) {
const cell = document.createElement('div');
cell.className = 'cell';
cell.dataset.index = i;
cell.addEventListener('click', handleCellClick);
grid.appendChild(cell);
}
}
// Handle cell clicks
function handleCellClick(e) {
const index = e.target.dataset.index;
if (mode === 'add' && !filledCells.has(index)) {
e.target.classList.add('filled');
filledCells.add(index);
} else if (mode === 'erase' && filledCells.has(index)) {
e.target.classList.remove('filled');
filledCells.delete(index);
}
updateStats();
}
// Calculate stats
function updateStats() {
const area = filledCells.size;
let perimeter = 0;
filledCells.forEach(index => {
const i = parseInt(index);
// Check adjacent cells (top, right, bottom, left)
if (!filledCells.has(i - gridSize)) perimeter++; // top
if (!filledCells.has(i + 1) || i % gridSize === gridSize - 1) perimeter++; // right
if (!filledCells.has(i + gridSize)) perimeter++; // bottom
if (!filledCells.has(i - 1) || i % gridSize === 0) perimeter++; // left
});
areaDisplay.textContent = area;
perimeterDisplay.textContent = perimeter;
}
// Mode switching
addModeBtn.addEventListener('click', () => {
mode = 'add';
addModeBtn.classList.add('mode-active');
eraseModeBtn.classList.remove('mode-active');
});
eraseModeBtn.addEventListener('click', () => {
mode = 'erase';
eraseModeBtn.classList.add('mode-active');
addModeBtn.classList.remove('mode-active');
});
// Initialize
initGrid();
</script>
</body>
</html>