HTML小球走迷宮代碼是一種前端交互性的開發方式,通過定義迷宮的結構,并控制小球的運動,實現用戶互動的游戲體驗。
<html> <head> <style> #maze{ display: grid; grid-template-columns: repeat(6, 50px); grid-template-rows: repeat(6, 50px); background-color: black; } .wall{ background-color: blue; } .ball{ background-color: red; border-radius: 50%; } .exit{ background-color: green; } </style> </head> <body> <div id="maze"> </div> <script> const mazeGrid = document.querySelector("#maze"); let ballPosition = 0; const createMaze = () => { for (let i=0; i<36; i++){ const square = document.createElement("div"); mazeGrid.appendChild(square); if (maze[i] === "W"){ square.classList.add("wall"); } else if (maze[i] === "E"){ square.classList.add("exit"); } } } const moveBall = (event) => { const squares = document.querySelectorAll("#maze div"); squares[ballPosition].classList.remove("ball"); switch(event.keyCode){ case 37: if (ballPosition % 6 !== 0) ballPosition -= 1; break; case 38: if (ballPosition > 5) ballPosition -= 6; break; case 39: if (ballPosition % 6 < 5) ballPosition += 1; break; case 40: if (ballPosition < 30) ballPosition += 6; break; } squares[ballPosition].classList.add("ball"); checkWin(); } const checkWin = () => { const squares = document.querySelectorAll("#maze div"); if (squares[ballPosition].classList.contains("exit")){ alert("You win!"); } } createMaze(); const squares = document.querySelectorAll("#maze div"); squares[ballPosition].classList.add("ball"); document.addEventListener("keydown", moveBall); const maze = [ "S","W","W","W","W","W", "E"," ","W"," "," ","W", " "," ","W"," "," ","W", " ","W","W"," "," ","W", " "," ","W"," "," "," ", "W","W","W","W","W","W" ]; </script> </body> </html>
以上便是這個HTML小球走迷宮代碼的實現方式,通過創建元素表示迷宮中的空間,定義按鍵事件控制小球的移動,并判定是否達到終點達成勝利。
上一篇python 連續讀文件
下一篇python 技術工程師