HTML5 Canvas開發迷宮遊戲例子

來源:互聯網
上載者:User

本文介紹如何使用Canvas畫布製作一個簡單的迷宮遊戲:使用者按下方向鍵時,笑臉表徵圖會沿相應的方向移動(移動時有動畫效果),遇到牆壁時(碰撞檢測)就會停下來。

1,線上範例
載入困難迷宮 載入簡單迷宮

2,實現原理
(1)迷宮的產生:我們這裡是使用一幅迷宮圖片,然後把整幅圖繪製到畫布上。
(2)通過設定 window.onkeydown 的響應函數 processKey(),當使用者按下方向鍵的時候,根據鍵碼調整笑臉各方向上的速度。
(3)drawFrame() 函數每10毫秒重新整理畫布,如果笑臉有速度則移動並繪製軌跡,同時作碰撞檢測。最後還會檢測笑臉是否到底部,到了話彈出成功訊息框。

3,碰撞檢測
這裡使用的是基於像素顏色碰撞檢測,我們取笑臉所在地區的像素塊(在笑臉四周再稍微擴充一點),判斷其中是否有黑色像素,有的話則說明撞牆了。

4,完整代碼

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8" />
  <title>hangge.com</title>
  <style>
    canvas {
      border: 6px double black;
      background: white;
    }
 
    img {
      display: none;
    }
 
    button {
      padding: 3px;
    }
  </style>
  <script>
    var canvas;
    var context;
 
    // 記錄笑臉表徵圖的當前位置
    var x = 0;
    var y = 0;
 
    // 記錄笑臉在x軸和y軸方向上每一幀要移動多少像素
    var dx = 0;
    var dy = 0;
 
    window.onload = function() {
      // 設定畫布
      canvas = document.getElementById("canvas");
      context = canvas.getContext("2d");
 
      // 繪製迷宮背景
      drawMaze('http://www.hangge.com/blog_uploads/201602/2016022313460193716.png', 5, 5);
 
      // 當使用者按下鍵盤上的鍵時,運行processKey()函數
      window.onkeydown = processKey;
    };
 
 
    // timer引用,這樣重新載入迷宮的時候可以很方便地停止繪製
    var timer;
 
    function drawMaze(mazeFile, startingX, startingY) {
      // 先停止繪製
      clearTimeout(timer);
 
      // 停止笑臉
      dx = 0;
      dy = 0;
 
      // 載入迷宮圖片
      var imgMaze = new Image();
      imgMaze.onload = function() {
        // 調整畫布大小以適應迷宮圖片
        canvas.width = imgMaze.width;
        canvas.height = imgMaze.height;
 
        // 繪製迷宮
        context.drawImage(imgMaze, 0,0);
 
        // 繪製笑臉
        x = startingX;
        y = startingY;
 
        var imgFace = document.getElementById("face");
        context.drawImage(imgFace, x, y);
        context.stroke();
 
        // 10毫秒後繪製下一幀
        timer = setTimeout(drawFrame, 10);
      };
      imgMaze.src = mazeFile;
    }
 
 
    function processKey(e) {
      // 如果笑臉在移動,停止
      dx = 0;
      dy = 0;
 
      // 按下了向上鍵,向上移動
      if (e.keyCode == 38) {
        dy = -1;
      }
 
      // 按下了向下鍵,向下移動
      if (e.keyCode == 40) {
        dy = 1;
      }
 
      // 按下了向左鍵,向左移動
      if (e.keyCode == 37) {
        dx = -1;
      }
 
      // 按下了向右鍵,向右移動
      if (e.keyCode == 39) {
        dx = 1;
      }
    }
 
    function checkForCollision() {
      // 取得笑臉所在的像素塊,再稍微擴充一點
      var imgData = context.getImageData(x-1, y-1, 15+2, 15+2);
      var pixels = imgData.data;
 
      // 檢測其中的像素
      for (var i = 0; n = pixels.length, i < n; i += 4) {
        var red = pixels[i];
        var green = pixels[i+1];
        var blue = pixels[i+2];
        var alpha = pixels[i+3];
 
        // 檢測黑色的牆(如果檢測到,說明撞牆了)
        if (red == 0 && green == 0 && blue == 0) {
          return true;
        }
        // 檢測灰色的邊(如果檢測到,說明撞牆了)
        if (red == 169 && green == 169 && blue == 169) {
          return true;
        }
      }
      // 沒有撞牆
      return false;
    }
 
 
    function drawFrame() {
      // 檢測笑臉是否正在哪個方向上移動,如果不是,則什麼也不做。
      if (dx != 0 || dy != 0) {
        // 在笑臉當前位置繪製一塊黃色背景(表示移動痕迹),然後把笑臉移到下一個位置
        context.beginPath();
        context.fillStyle = "rgb(254,244,207)";
        context.rect(x, y, 15, 15);
        context.fill()
 
        // 增大位置值
        x += dx;
        y += dy;
 
        // 碰撞檢測(撞牆的話笑臉需要放回上一個位置並停止移動)
        if (checkForCollision()) {
          x -= dx;
          y -= dy;
          dx = 0;
          dy = 0;
        }
 
        // 這裡可以繪製笑臉
        var imgFace = document.getElementById("face");
        context.drawImage(imgFace, x, y);
 
        // 檢測笑臉是否已經到達迷宮底部,是的話提示成功
        if (y > (canvas.height - 17)) {
          alert("You win!");
          return;
        }
      }
 
      // 10毫秒後繪製下一正
      timer = setTimeout(drawFrame, 10);
    }
 
    function loadEasy() {
      drawMaze('http://www.hangge.com/blog_uploads/201602/2016022313460193716.png', 5, 5);
    }
 
    function loadHard() {
      drawMaze('http://www.hangge.com/blog_uploads/201602/2016022313455480577.png', 268, 5);
    }
  
  </script>
</head>
 
<body>  
  <canvas id="canvas">
  </canvas>
  <div>
    <button onclick="loadHard()">載入困難迷宮</button>
    <button onclick="loadEasy()">載入簡單迷宮</button>
  </div>
 
  <img id="face" src="2016022313454739977.png">
</body>
</html>

HTML5 canvas 小遊戲練手

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
<style type="text/css">
*{padding:0;margin:0;color:#fff;}
a {text-decoration:none;}
html,body{background-color:#000;}
#canvas{background-color:#001022;position:absolute;z-index:-1000;top:0}
#game{margin:auto;width:40%;background-color:#001022;}
#lay{width:100%;height:100%;position:relative}
#game p,h2{text-align:center;width:100%}
#gameInfo{position:relative;margin-top:150px;}

#gameState{margin-top:20px;margin-left:-400px;}
#reset{position:absolute;top:20px;text-decoration:none;margin-left:150px;}
#reset:hover{color:blue}
#play{width:80px;height:40px; font-weight:bold;font-size:25px;margin:10px}
h2{font-size:40px}
#footer{margin-top:120px;display:none}
#play {background: #CCC;color: #333;border-radius: 5px;}
</style>
</head>

<body>
<div id="game">
<p><a href="#" id="reset">Reset</a></p>
<a >太空保齡球</a>
<div id="lay">
<div id="gameUI">
<div id="gameInfo">
<p><h2>Space bowling</h2></p>
<p>This is an awesome game.</p>
<p><button id="play">Play</buttom>
</div>
<div id="gameState">
<p>Asteroids:<label id="bowlNum"></label></p>
<p>&nbsp;&nbsp; Clicks:<label id="ClickNum"></label></p>

</div>
<div id="footer">
<h2>You Win!</h2>
<p>Congratulations,you completed</p>
<p>the game in clicks</p>
<p>Play again</p>

</div>
</div>
</div>
<canvas id="canvas"></canvas>
</div>
</body>
</html>
<script type="text/javascript">

var bowlNum=0;
var clickNum=0;
var viewWidth = 0;
var viewHeight = 0;
try{
viewWidth=document.documentElement.clientWidth;
viewHeight = document.documentElement.clientHeight;
}catch(e){
viewWidth = document.body.clientWidth;
viewHeight = document.body.clientHeight;
}
var canvas = document.getElementById("canvas");
//canvas.width=546
canvas.height=viewHeight;
canvas.width=viewWidth/2.5;

var context = canvas.getContext("2d");
var play = document.getElementById("play");


play.onclick=function(){//開始遊戲
document.getElementById("gameInfo").style.display="none";
document.getElementById("footer").style.display="none";
drawBegin();
}

//建立小球類
function bowling(x,y,radius,mass,firction){
this.x = x;
this.y=y;
this.radius = radius;
this.mass = mass;
this.firction=firction;
this.vX=0;
this.vY=0;
this.player=true;
this.R=10;
}
var bowlingArr = new Array();


function drawBegin(){
context.fillStyle="#646464";
context.beginPath();
context.arc(canvas.width/2,160,80,0,2*Math.PI,true);
context.closePath();
context.fill();

context.fillStyle="#fff";
context.beginPath();
context.arc(canvas.width/2,canvas.height-60,10,0,2*Math.PI,true);
var playBowling = new bowling(canvas.width/2,canvas.height-60,0,100,10);
bowlingArr.push(playBowling);
context.closePath();
context.fill();

var radius = 0;
//畫若干小球在圓台上
for(var i=0;i<8;i++){
var x=canvas.width/2;
var y=100;
radius=Math.PI/4*(i);
x = Math.floor(x+Math.sin(radius)*60);
y = Math.floor(y+60-Math.cos(radius)*60);
var tempalBowling = new bowling(x,y,10,100,0.95);
tempalBowling.vX=0;
tempalBowling.vY=0;
bowlingArr.push(tempalBowling);
context.beginPath();
context.arc(x,y,10,0,Math.PI*2,true);
context.closePath();
context.fill();
}

var tempalBowling = new bowling(canvas.width/2,160,10,100,0.95);
tempalBowling.vX=0;
tempalBowling.vY=0;
bowlingArr.push(tempalBowling);
context.beginPath();
context.arc(canvas.width/2,160,10,0,Math.PI*2,true);
context.closePath();
context.fill();


radius = 0;
for(var i=0;i<5;i++){
var x=canvas.width/2;
var y=130;
radius=Math.PI*0.4*(i+1);
x = Math.floor(x+Math.sin(radius)*30);
y = Math.floor(y+30-Math.cos(radius)*30);
var tempalBowling = new bowling(x,y,10,100,0.95);
tempalBowling.vX=0;
tempalBowling.vY=0;
bowlingArr.push(tempalBowling);
context.beginPath();
context.arc(x,y,10,0,Math.PI*2,true);
context.closePath();
context.fill();
}

//畫一個拖動圓台 描述允許拖動的範圍

}


//重新整理
function UpdateUI(){
context.clearRect(0,0,canvas.width,canvas.height);

 

context.fillStyle="#646464";
context.beginPath();
context.arc(canvas.width/2,canvas.height-60,10,0,Math.PI*2,false);
context.closePath();
context.fill();
//圓台
context.fillStyle="#646464";
context.beginPath();
context.arc(canvas.width/2,160,80,0,2*Math.PI,true);
context.closePath();
context.fill();
//15個小球
for(var i=0;i<bowlingArr.length;i++){
if(bowlingArr.player==false)
continue;
context.fillStyle="#ffffff";
context.beginPath();
context.arc(bowlingArr[i].x,bowlingArr[i].y,bowlingArr[i].R,0,Math.PI*2,false);
context.closePath();
context.fill();
if(bowlingArr[i].player==true)
bowlNum++;
}
//更新圓台上小球的數量
document.getElementById("bowlNum").innerHTML=bowlNum;
//更新點擊釋放小球的次數
document.getElementById("ClickNum").innerHTML = clickNum;
deleteBowling();

}
//刪除小球 重設小球
function deleteBowling(){
for(var i=1;i<bowlingArr.length;i++){
if(bowlingArr[i].vX!=0||bowlingArr[i].vY!=0){
var dx=Math.abs(bowlingArr[i].x-canvas.width/2);
var dy=Math.abs(bowlingArr[i].y-160);
var distance = Math.floor(Math.sqrt(dx*dx+dy*dy));
if(distance>80){
bowlingArr[i].R-=0.5;
if(bowlingArr[i].R<=0)
bowlingArr[i].R=0;
bowlingArr[i].player=false;//不將其計入遊戲了
}
}
}
//重設拖拽的小球
if(bowlingArr[0].x>canvas.width||bowlingArr[0].y<0||bowlingArr[0].y>canvas.height||bowlingArr[0].y<0){
bowlingArr[0].R=10;
bowlingArr[0].x=canvas.width/2;
bowlingArr[0].y=canvas.height-60;
bowlingArr[0].vX=0;
bowlingArr[0].vY=0;
}
}

//重設遊戲
document.getElementById("reset").onclick = function(e){
var evt = e||window.event;
if(!!evt.preventDefualt){
evt.preventDefualt();
}
else{
evt.returnValue=false;
}
document.getElementById("gameInfo").style.display="block";
context.clearRect(0,0,canvas.width,canvas.height);
bowlingArr.length=0;
}

 

//小球動畫
function animate(){
//bowlingArr[0].y-=bowlingArr[0].vy;
for(var i=0;i<bowlingArr.length;i++){
//碰撞檢測 方法是兩兩比較,如果碰撞,能量轉化
var tempalA = bowlingArr[i];
for(var j=i+1;j<bowlingArr.length;j++){
var tempalB=bowlingArr[j];
var dx = Math.abs(tempalB.x-tempalA.x);
var dy = Math.abs(tempalB.y-tempalA.y);
var distanceAB = Math.sqrt(dx*dx+dy*dy); //勾股定理

//檢測碰撞
if(distanceAB<=tempalA.R+tempalB.R){
//碰了
var angle =Math.atan2(dy,dx);

var sine = Math.sin(angle);
var cosin = Math.cos(angle);

var x=0;
var y=0;

var xB=dx*cosin+dy*sine;
var yB=dy*cosin+dx*sine;

var vy=tempalA.vX*cosin+tempalA.vY*sine;
var vx=tempalA.vY*cosin+tempalA.vX*sine;

var vBX = tempalB.vX*cosin+tempalB.vY*sine;
var vBY = tempalB.vY*cosin+tempalB.vX*sine;

var xTotal = vx-vBX;
vX = ((tempalA.mass-tempalB.mass)*vx+2*tempalB.mass*vBX)/(tempalA.mass+tempalB.mass);
vBX = xTotal+vx;
vY = ((tempalA.mass-tempalB.mass)*vy+2*tempalB.mass*vBY)/(tempalA.mass+tempalB.mass);
vBY = xTotal+vy;

xB = x+(tempalA.radius+tempalB.radius);

tempalA.x = tempalA.x+(x*cosin-y*sine);
tempalA.y = tempalA.y+(y*cosin+x*sine);

tempalB.x = tempalB.x+(xB*cosin-yB*sine);
tempalB.y = tempalB.y+(yB*cosin+yB*sine);

 

tempalA.vX = vx*cosin - vy*sine;
tempalA.vY = vy*cosin + vx*sine;

tempalB.vX = vBX*cosin - vBY*sine;
tempalB.vY = vBY*cosin + vBY*sine;

}
}
bowlingArr[i].x+=bowlingArr[i].vX;
bowlingArr[i].y+=bowlingArr[i].vY;

}
UpdateUI();
setTimeout(arguments.callee,40);
}

//監聽滑鼠拖拽,釋放小球
var moveAble=false;
var dragable=false;
var clickYN = false;
canvas.onmousedown = function(){
if(bowlingArr[0].y>=canvas.height-60)//必須在這個範圍才能拖拽小球
clickYN=true;
}
canvas.onmousemove = function(e){
if(clickYN==true){
dragable=true;
}
if(dragable==true){

//計算拖動角度
bowlingArr[0].x = e.clientX-canvas.offsetLeft;
bowlingArr[0].y = e.clientY-canvas.offsetTop;
bowlingArr[0].vX = -(bowlingArr[0].x-canvas.width/2);
bowlingArr[0].vY = -(bowlingArr[0].y-canvas.height+60);
UpdateUI();
}
}
canvas.onmouseup = function(){
clickYN=false;
if(dragable==true){
clickNum++;//點擊次數增加
dragable=false;
moveAble=true;

//開始遊戲
if(moveAble)
animate();
}
}
</script>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.