DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> js貪吃蛇游戲實現思路和源碼
js貪吃蛇游戲實現思路和源碼
編輯:關於JavaScript     

本文實例為大家分享了js貪吃蛇游戲的相關代碼,供大家參考,具體內容如下

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>貪吃蛇小游戲</title>
  <style>
*{margin:0; padding:0;}
header {
  display: block;
  margin: 0 auto;
  width: 500px;
  text-align: center;
}
header h1 {
  font-family: Arial;
  font-weight: bold;
}
header #newGameButton {
  display: block;
  margin: 20px auto;
  width: 100px;
  padding: 10px 10px;
  background-color: #8f7a66;
  font-family: Arial;
  color: white;
  border-radius: 10px;
  text-decoration: none;
}
header #newGameButton:hover {
  background-color: #9f8b77;
}
header p {
  font-family: Arial;
  font-size: 25px;
  margin: 20px auto;
}
canvas{
  display:block; 
  border:medium double black;
  margin:4px auto;
}
  </style>
</head>
<body>
  <header>
    <h1>貪吃蛇小游戲</h1>
    <a href="javascript:newgame();" id="newGameButton">New Game</a>
    <p>score:<span id="score">0</span></p>
  </header>
  <canvas id="canvas">
    Your browser doesn't support the <code>canvas</code> element.
  </canvas>
  <script>
  var CANVAS = document.getElementById("canvas");
var CTX = CANVAS.getContext("2d");
var SNAKE = new Array();  //用隊列模擬蛇身
var DIR = "right";        //用來控制蛇頭的方向
var SIZE = 20;        //蛇身的寬度
var FOODX = 0;      //食物的x坐標
var FOODY = 0;      //食物的y坐標
var HEADX = 0;    //蛇頭的x坐標
var HEADY = 0;    //蛇頭的y坐標
var MAXWIDTH = 200;    //畫布的高度
var MAXHEIGHT = 200;  //畫布的寬度
var TIME = 400;      //蛇的速度
var SCORE = 0;      //計算玩家分數
var interval = null;

CANVAS.width = MAXWIDTH;
CANVAS.height = MAXHEIGHT;

window.onload = function(){
  newgame();
};
document.getElementById("newGameButton").click(function(){
  newgame();
});
function newgame(){
  SNAKE = [];    //用隊列模擬蛇身
  DIR = "right";  //用來控制蛇頭的方向
  HEADX = 0;    //蛇頭的x坐標
  HEADY = 0;    //蛇頭的y坐標
  SCORE = 0;
  window.clearInterval(interval);
  interval = null;
  //初始化畫布
  CTX.clearRect(0, 0, MAXWIDTH, MAXHEIGHT);
  //畫一條蛇
  drawSnake();
  //放置食物
  setFood();
  //移動蛇
  interval = window.setInterval(move, TIME);

}
function move(){
  switch(DIR){
    case "up":HEADY = HEADY-SIZE;break;
    case "right":HEADX = HEADX+SIZE;break;
    case "down":HEADY = HEADY+SIZE;break;
    case "left":HEADX = HEADX-SIZE;break;
  }
  if(HEADX>MAXWIDTH-SIZE || HEADY>MAXHEIGHT-SIZE || HEADX<0 || HEADY<0){
    alert("你的分數為:"+SCORE+"分,繼續努力吧!失敗原因:碰壁了.....");
    window.location.reload();
  }
  for(var i=1;i<SNAKE.length;i++){
    if(SNAKE[i][0] == SNAKE[0][0] && SNAKE[i][1] == SNAKE[0][1]){
      alert("你的分數為:"+SCORE+"分,繼續努力吧!失敗原因:撞到自己了.....");
      window.location.reload();
    }
  }
  if(SNAKE.length == MAXWIDTH *MAXHEIGHT){
    alert("好厲害!麼麼哒~");
    window.location.reload();
  }
  moveIn(HEADX, HEADY);//移動一格
}
document.onkeydown = function(e) { //改變蛇方向
  var code = e.keyCode - 37;
  switch(code){
    case 1 : DIR = "up";break;//上
    case 2 : DIR = "right";break;//右
    case 3 : DIR = "down";break;//下
    case 0 : DIR = "left";break;//左
  }
}
//=============================畫一條蛇=======================================================
function drawSnake(){
  CTX.fillStyle = "black";
  //畫蛇頭
  CTX.fillRect (HEADX, HEADY, SIZE, SIZE);
  SNAKE.push([HEADX, HEADY]);
  
  //畫蛇身
  switch(DIR){
    case "up": 
      drawBody(HEADX, HEADY + SIZE, HEADX, HEADY + 2 * SIZE);
      break;
    case "right": 
      drawBody(HEADX - SIZE, HEADY, HEADX - 2 * SIZE, HEADY);
      break;
    case "down": 
      drawBody(HEADX, HEADY - SIZE, HEADX, HEADY - 2 * SIZE);
      break;
    case "left": 
      drawBody(HEADX + SIZE, HEADY, HEADX + 2 * SIZE, HEADY);
      break;
  }
}
function drawBody(x1, y1, x2, y2){
  CTX.fillRect (x1, y1, SIZE, SIZE); 
  CTX.fillRect (x2, y2, SIZE, SIZE); 
  SNAKE.push([x1, y1]);
  SNAKE.push([x2, y2]);
}
//===========================放置食物==============================
function setFood(){
  do{
    FOODX = SIZE * Math.floor(Math.random() * MAXWIDTH / SIZE);
    FOODY = SIZE * Math.floor(Math.random() * MAXHEIGHT / SIZE);
  }while(foodInSnake());
  CTX.fillStyle = "red";
  CTX.fillRect (FOODX, FOODY, SIZE, SIZE);
}
function foodInSnake(){
  for (var i = 0; i < SNAKE.length; i++) {
    if(FOODX == SNAKE[i][0] && FOODY == SNAKE[i][1]){
      return true;
    }
  }
  return false;
}
//========================================移動一格===========================
function moveIn(x, y){
  CTX.fillStyle = "black";
  CTX.fillRect(x, y, SIZE, SIZE);//重畫蛇頭  
  //把新蛇頭添加到 SNAKE 數組
  var newSnake = [[x, y]];
  SNAKE = newSnake.concat(SNAKE);

  if(false == eatFood()){//如果沒吃到食物,減少一格蛇尾  
    var snakeTail = SNAKE.pop();//獲得蛇尾位置
    CTX.clearRect(snakeTail[0], snakeTail[1], SIZE, SIZE);//去掉蛇尾  
  }
}
function eatFood(){
  if(HEADX == FOODX && HEADY == FOODY){
    CTX.fillStyle = "block";
    CTX.fillRect (FOODX, FOODY, SIZE, SIZE);

    setFood();
    SCORE++;
    //$("#score").text(SCORE);
    document.getElementById("score").innerHTML = SCORE;
    return true;
  }
  return false;
}

  </script>
</html>

效果圖:

思路:

function newgame(){
  重置蛇和分數的數據;
  清除interval;
  初始化畫布;
  畫一條蛇;
  放置食物;
  使用定時器(setInterval)使蛇移動(move函數);
}
function move(){
  根據方向改變蛇頭下一格將要到達的位置;
  判斷游戲是否結束,以及顯示結束的原因(包含輸贏);
  蛇移動一格(moveIn函數);
}
對鍵盤的方向鍵作監控,當改變方向時,修改全局變量DIR的值(用於存儲方向);
function moveIn(){
  在蛇頭的前一格增加一格作為新的蛇頭,並將蛇頭的坐標作為第一個元素加入到代表蛇的數組中;
  if(沒吃到食物){
    刪除一格蛇尾,在畫布中做相應改變;
  }
}

需要注意的是,如果需要在JS中設定canvas中的寬度和高度,和設置其他CSS屬性略有不同。

CANVAS.width = MAXWIDTH;CANVAS.height = MAXHEIGHT;

小編還為大家准備了精彩的專題:javascript經典小游戲匯總

以上就是本文的全部內容,希望對大家學習javascript程序設計有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved