document.addEventListener('DOMContentLoaded', () => {
const mazeElement = document.getElementById('maze');
const messageElement = document.getElementById('message');
const mazeLayout = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 'S', 0, 0, 0, 1, 0, 0, 0, 1],
[1, 1, 1, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 0, 0, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 1, 1, 1, 0, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 1, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 'E', 1, 1, 1, 1, 1, 1, 1, 1]
];
let playerPosition = { row: 1, col: 1 };
function createMaze() {
mazeElement.innerHTML = '';
for (let row = 0; row < mazeLayout.length; row++) {
for (let col = 0; col < mazeLayout[row].length; col++) {
const cell = document.createElement('div');
cell.classList.add('cell');
cell.dataset.row = row;
cell.dataset.col = col;
const cellValue = mazeLayout[row][col];
if (cellValue === 1) {
cell.classList.add('wall');
} else if (cellValue === 'S') {
cell.classList.add('start');
cell.textContent = 'S';
} else if (cellValue === 'E') {
cell.classList.add('end');
cell.textContent = 'E';
}
mazeElement.appendChild(cell);
}
}
placePlayer();
}
function placePlayer() {
document.querySelectorAll('.player').forEach(player => player.remove());
const playerCell = document.querySelector(`.cell[data-row="${playerPosition.row}"][data-col="${playerPosition.col}"]`);
const playerDiv = document.createElement('div');
playerDiv.classList.add('player');
playerCell.appendChild(playerDiv);
}
function isValidMove(row, col) {
if (row < 0 || row >= mazeLayout.length || col < 0 || col >= mazeLayout[0].length) {
return false;
}
return mazeLayout[row][col] !== 1;
}
function checkWin() {
if (mazeLayout[playerPosition.row][playerPosition.col] === 'E') {
messageElement.textContent = "Congratulations! You Escaped the Maze!";
document.removeEventListener('keydown', handleKeyPress);
}
}
function handleKeyPress(event) {
let newRow = playerPosition.row;
let newCol = playerPosition.col;
switch(event.key) {
case 'ArrowUp':
newRow--;
break;
case 'ArrowDown':
newRow++;
break;
case 'ArrowLeft':
newCol--;
break;
case 'ArrowRight':
newCol++;
break;
default:
return;
}
if (isValidMove(newRow, newCol)) {
playerPosition.row = newRow;
playerPosition.col = newCol;
placePlayer();
checkWin();
}
}
createMaze();
document.addEventListener('keydown', handleKeyPress);
});