HTML5已經(jīng)成為了現(xiàn)代Web開發(fā)的利器,在它的高度推廣下,越來越多的網(wǎng)站開始使用HTML5的新特性。而作為前端開發(fā)的必修課,貪吃蛇游戲也成為了各位開發(fā)者學(xué)習(xí)HTML5的練手好項目。在這里,我們推薦一份HTML5實用教程貪吃蛇源代碼,為大家介紹一下這個項目的核心思路。
window.onload = function() { var canvasWidth = 900; var canvasHeight = 600; var blockSize = 30; var ctx; var delay = 100; var snakee; init(); function init() { var canvas = document.createElement("canvas"); canvas.width = canvasWidth; canvas.height = canvasHeight; canvas.style.border = "30px solid gray"; canvas.style.margin = "50px auto"; canvas.style.display = "block"; canvas.style.backgroundColor = "#ddd"; document.body.appendChild(canvas); ctx = canvas.getContext('2d'); snakee = new Snake([[6, 4], [5, 4], [4, 4]], "right"); refreshCanvas(); } function refreshCanvas() { ctx.clearRect(0, 0, canvasWidth, canvasHeight); snakee.advance(); drawSnake(); setTimeout(refreshCanvas, delay); } function drawBlock(ctx, position) { var x = position[0] * blockSize; var y = position[1] * blockSize; ctx.fillRect(x, y, blockSize, blockSize); } function drawSnake() { for (var i = 0; i< snakee.body.length; i++) { drawBlock(ctx, snakee.body[i]); } } function Snake(body, direction) { this.body = body; this.direction = direction; this.advance = function() { var nextPosition = this.body[0].slice(); switch (this.direction) { case "left": nextPosition[0] -= 1; break; case "right": nextPosition[0] += 1; break; case "down": nextPosition[1] += 1; break; case "up": nextPosition[1] -= 1; break; default: throw ("Invalid Direction"); } this.body.unshift(nextPosition); this.body.pop(); }; } }
在這份源代碼當(dāng)中,我們首先定義了一些必要的變量,包括畫布大小,方塊大小,延遲時間,以及存儲貪吃蛇身體信息的變量。在init()函數(shù)當(dāng)中,我們創(chuàng)建了一個畫布,并將其添加到HTML頁面當(dāng)中。在drawBlock()函數(shù)中,我們定義了一個HTML5畫布API規(guī)定的畫方塊的方法,并在drawSnake()函數(shù)中使用它來畫出整個貪吃蛇的身體。在Snake()函數(shù)中,我們定義了一個貪吃蛇對象,并添加了其移動的方法,實現(xiàn)了貪吃蛇的基本邏輯。