ntainer = document.querySelector("#gameContainer"); for (let i = 0; i < gridSize; i++) { const row = document.createElement("div"); row.classList.add("row"); for (let j = 0; j < gridSize; j++) { const cell = document.createElement("div"); cell.classList.add("cell"); row.appendChild(cell); } gameContainer.appendChild(row); } // Place player on initial position const initialCell = gameContainer.querySelector(".row:nth-child(1) .cell:nth-child(1)"); initialCell.innerHTML = playerIcon; // Handle player movement function handlePlayerMovement(e) { const key = e.key; let newPosition; switch (key) { case "ArrowUp": newPosition = [playerPosition[0] - 1, playerPosition[1]]; break; case "ArrowDown": newPosition = [playerPosition[0] + 1, playerPosition[1]]; break; case "ArrowLeft": newPosition = [playerPosition[0], playerPosition[1] - 1]; break; case "ArrowRight": newPosition = [playerPosition[0], playerPosition[1] + 1]; break; default: return; } // Check if new position is within grid boundaries if (newPosition[0] >= 0 && newPosition[0] < gridSize && newPosition[1] >= 0 && newPosition[1] < gridSize) { // Clear current player position const currentCell = gameContainer.querySelector(`.row:nth-child(${playerPosition[0] + 1}) .cell:nth-child(${playerPosition[1] + 1})`); currentCell.innerHTML = ""; // Update player position playerPosition = newPosition; // Move player to new position const newCell = gameContainer.querySelector(`.row:nth-child(${playerPosition[0] + 1}) .cell:nth-child(${playerPosition[1] + 1})`); newCell.innerHTML = playerIcon; } } // Start game function startGame() { document.addEventListener("keydown", handlePlayerMovement); } // Initialize game on page load window.addEventListener("load", function() { initializeGame(); startGame(); });