DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML5特效代碼
用 HTML5 Canvas 實作貪吃蛇遊戲
編輯:HTML5特效代碼     

本範例以 HTML5 的 canvas 搭配 JavaScript,實作經典的貪吃蛇遊戲。玩家可用方向鍵控制蛇的移動,吃到食物後蛇身變長、分數累加,撞到牆壁或自身則遊戲結束並重新開始。請使用支援 HTML5 的瀏覽器,例如 IE9、Firefox 或 Chrome。

Your browser not support Canvas!

遊戲以 setInterval 驅動主迴圈,每次更新時清空畫布、移動蛇身、繪製食物與分數,並透過 keydown 事件監聽方向鍵。以下是完整程式碼:


<!DOCTYPE html>
<html>
<head>
<title>Snake</title>
</head>
<body>
<canvas id="canvas" width="600" height="600">
Your browser not support Canvas!
</canvas>
<script type="text/javascript">
var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
var canvasWidth, canvasHeight, snakeArray, px, cycle, gameLoop;
var left = 37, up = 38, right = 39, down = 40;
var d, f, score, flagD;
init();
function init(){
canvasWidth = c.width; canvasHeight = c.height; snakeArray = [];
px = 20; cycle = 500/1000; d = right; f = {x:-1,y:-1}; score = 0; flagD = true;
if(typeof gameLoop != 'undefined'){ clearInterval(gameLoop); }
initSnake(3); initFood(); play();
}
function play(){
gameLoop = setInterval(function(){
ctx.fillStyle = 'white'; ctx.fillRect(0,0,canvasWidth,canvasHeight);
ctx.strokeStyle = 'black'; ctx.strokeRect(0,0,canvasWidth,canvasHeight);
moveSnake(); paintSnake(snakeArray);
ctx.fillStyle = 'red'; paintCell(f.x,f.y);
ctx.fillText('Score:' + score,5,canvasHeight - 5);
},cycle*1000);
}
function initSnake(length){ for(var i=length;i>0;i--){ snakeArray.push({x:i,y:0}); } };
function paintSnake(){ ctx.fillStyle = 'blue'; for(var i=0;i<snakeArray.length;i++){ paintCell(snakeArray[i].x,snakeArray[i].y); } }
function paintCell(x,y){ ctx.fillRect(x*px,y*px,px-1,px-1); }
function moveSnake(){
flagD = false;
var p = {x:snakeArray[0].x,y:snakeArray[0].y};
if(d == left) p.x--; else if(d == right) p.x++; else if(d == up) p.y--; else if(d == down) p.y++;
if(p.x == f.x && p.y == f.y){ score++; initFood(); }else{ snakeArray.pop(); }
if(p.x == -1 || p.x == canvasWidth/px || p.y == -1 || p.y == canvasHeight/px || checkColliction(p.x,p.y)){ alert(p.x + ":" + p.y); init(); return; }
snakeArray.unshift(p); flagD = true;
}
function checkColliction(x,y){ for(var t in snakeArray){ if(x == snakeArray[t].x && y == snakeArray[t].y){ return true; } } return false; }
function initFood(){ var flag = false; do{ f.x = Math.floor(canvasWidth/px*Math.random()); f.y = Math.floor(canvasHeight/px*Math.random()); for(var t in snakeArray){ if(f.x == snakeArray[t].x && f.y == snakeArray[t].y) flag = true; } }while(flag); }
window.addEventListener('keydown',function(e){ if(flagD){ if(e.keyCode == left && d != right) d = left; else if(e.keyCode == right && d != left) d = right; else if(e.keyCode == up && d!= down) d = up; else if(e.keyCode == down && d != up) d = down; flagD = false; }; });
</script>
</body>
</html>
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved