HTML5小游戲是一種輕便、簡單、好玩的游戲形式。20行代碼的HTML5小游戲代表著它的簡單易上手性,下面就為大家介紹一款經(jīng)典的貪吃蛇小游戲。
let canvas = document.getElementById('canvas'); let ctx = canvas.getContext('2d'); let grid = 16; let count = 0; let snake = { x: 160, y: 160, dx: grid, dy: 0, cells: [], maxCells: 4 }; let apple = { x: 320, y: 320 }; function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; } function loop() { requestAnimationFrame(loop); if (++count< 4) { return; } count = 0; ctx.clearRect(0,0,canvas.width,canvas.height); snake.x += snake.dx; snake.y += snake.dy; if (snake.x< 0) { snake.x = canvas.width - grid; } else if (snake.x >= canvas.width) { snake.x = 0; } if (snake.y< 0) { snake.y = canvas.height - grid; } else if (snake.y >= canvas.height) { snake.y = 0; } snake.cells.unshift({x: snake.x, y: snake.y}); if (snake.cells.length >snake.maxCells) { snake.cells.pop(); } ctx.fillStyle = 'red'; ctx.fillRect(apple.x, apple.y, grid-1, grid-1); ctx.fillStyle = 'green'; snake.cells.forEach(function(cell, index) { ctx.fillRect(cell.x, cell.y, grid-1, grid-1); if (cell.x === apple.x && cell.y === apple.y) { snake.maxCells++; apple.x = getRandomInt(0, 25) * grid; apple.y = getRandomInt(0, 25) * grid; } for (let i = index + 1; i< snake.cells.length; i++) { if (cell.x === snake.cells[i].x && cell.y === snake.cells[i].y) { window.location.reload(); } } }); } document.addEventListener('keydown', function(e) { if (e.which === 37 && snake.dx === 0) { snake.dx = -grid; snake.dy = 0; } else if (e.which === 38 && snake.dy === 0) { snake.dy = -grid; snake.dx = 0; } else if (e.which === 39 && snake.dx === 0) { snake.dx = grid; snake.dy = 0; } else if (e.which === 40 && snake.dy === 0) { snake.dy = grid; snake.dx = 0; } }); requestAnimationFrame(loop);
簡單說明一下這款游戲的代碼。用戶通過鍵盤控制蛇的行動,目的是將蘋果吃掉,蛇的身體就會增加一格。同時,蛇還需要避開墻壁和自己的身體,否則游戲結(jié)束。這款貪吃蛇小游戲的代碼僅有20行,非常簡單,而且可以通過不同的修改和拓展,實(shí)現(xiàn)更多有趣的小游戲。