貪吃蛇游戲是一款經典的游戲,讓我們一起看看使用HTML5如何實現一個貪吃蛇的游戲。
//設置畫板 const canvas = document.querySelector('canvas'); const ctx = canvas.getContext('2d'); //定義貪吃蛇 let snake = [ {x: 10, y: 10}, {x: 9, y: 10}, {x: 8, y: 10}, {x: 7, y: 10}, {x: 6, y: 10}, {x: 5, y: 10} ]; let dx = 1; let dy = 0; //生成食物 let food = {x: getRandomInt(20), y: getRandomInt(20)} //監聽鍵盤事件 document.addEventListener("keydown",changeDirection); //游戲開始 function game(){ clearCanvas(); drawFood(); drawSnake(); moveSnake(); //判斷是否結束游戲 if(gameOver()){ alert("游戲結束!"); return; } //下一幀 requestAnimationFrame(game); } //定義函數 function clearCanvas(){ //清除畫板 ctx.fillStyle = "white"; ctx.fillRect(0,0,canvas.width,canvas.height); } function drawSnake(){ //繪制蛇身 ctx.fillStyle = "blue"; snake.forEach(snakePart =>ctx.fillRect(snakePart.x, snakePart.y, 1, 1)); } function drawFood(){ //繪制食物 ctx.fillStyle = "red"; ctx.fillRect(food.x, food.y, 1, 1); } function moveSnake(){ //移動蛇身 const head = {x: snake[0].x + dx, y: snake[0].y + dy}; snake.unshift(head); //判斷是否吃到食物 if(head.x == food.x && head.y == food.y){ food = {x: getRandomInt(20), y: getRandomInt(20)} }else{ snake.pop(); } } function gameOver(){ //判斷是否撞線或者自己撞到自己 const head = snake[0]; return(head.x< 0 || head.x >= 20 || head.y< 0 || head.y >= 20 || snake.slice(1).some(snakePart =>snakePart.x === head.x && snakePart.y === head.y)); } function getRandomInt(max){ //得到0到20的隨機整數 return Math.floor(Math.random()*Math.floor(max)); } function changeDirection(e){ //監聽鍵盤事件 const LEFT_KEY = 37; const RIGHT_KEY = 39; const UP_KEY = 38; const DOWN_KEY = 40; const keyPressed = e.keyCode; const goingLeft = dx === -1; const goingUp = dy === -1; const goingRight = dx === 1; const goingDown = dy === 1; if(keyPressed === LEFT_KEY && !goingRight){ dx = -1; dy = 0; } if(keyPressed === UP_KEY && !goingDown){ dx = 0; dy = -1; } if(keyPressed === RIGHT_KEY && !goingLeft){ dx = 1; dy = 0; } if(keyPressed === DOWN_KEY && !goingUp){ dx = 0; dy = 1; } } //調用游戲函數 game();
通過上述代碼,我們可以看到如何使用HTML5實現一個貪吃蛇游戲,其中還涉及到了canvas畫板的使用,鍵盤事件的監聽,以及函數的調用等知識點。