DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> js編寫“貪吃蛇”的小游戲
js編寫“貪吃蛇”的小游戲
編輯:關於JavaScript     

貪吃蛇兒時的回憶,今天剛好學習到這了,就剛好做了一個,也是學習了吧,需要掌握的知識:

  1、JS函數的熟練掌握,

  2、JS數組的應用,

  3、JS小部分AJAX的學習

  4、JS中的splice、shift等一些函數的應用,

基本上就這些吧,下面提重點部分:
前端的頁面,這裡可自行布局,我這邊提供一個我自己的布局:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">                     
<head>
  <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
  <title>貪吃蛇</title>
  <link rel="stylesheet" type="text/css" href="./css.css">
  <script type="text/javascript" src="./jquery-1.7.2.min.js"></script>
  <script type="text/javascript" src="./js.js"></script>
</head>
<body>
  <div id="info">  
    <div id="score">0</div>
    <form action="" id="form" name="form">
      <input type="radio" name='time' value="500" checked='checked'/>簡單
      <input type="radio" name='time' value="300"/>中等
      <input type="radio" name='time' value="150"/>高級
      <input type="radio" name='time' value="50"/>神速
      <input type="button" value="開始" class="button" id="start"/>
      <input type="button" value="重玩" class="button" id="res"/> 
    </form>
     
  </div>
  <div id="main">
    <div id="home">
      <!--<div style="background:url(./images/snake0.png) no-repeat;"></div>
      <div style="background:url(./images/snake1.png) no-repeat; left:20px;"></div>
      <div style="background:url(./images/snake2.png) no-repeat; left:40px;"></div>
      <div style="background:url(./images/snake3.png) no-repeat; left:60px;"></div>-->
    </div>
    <div class="wall left"></div>
    <div class="wall right"></div>
    <div class="wall top"></div>
    <div class="wall bottom"></div>
  </div>                            
</body> 
</html>

 這裡是css代碼:

*{padding: 0px; margin: 0px;font-size: 12px}
body{background: #ccc}
input.button{
  width: 60px;
  cursor: pointer;
}
#info{
  width: 540px;
  height: 30px;
  margin: 30px auto 5px;
  line-height: 30px;
}
#score{
  width: 73px;
  height: 28px;
  padding-left: 64px;
  background: url(./images/score.png) no-repeat;
  float: left;
  font-size: 14px;
  font-weight: 700;
  font-style:italic;
  font-family: '微軟雅黑';
}
#form{
  float: right;
}
#form input{
  vertical-align: middle;
  margin-right: 5px;
}
#main{
  width: 540px;
  height: 500px;
  margin: 0 auto;
  position: relative;
  /*background: #71a000*/
 
}
#main div{
  width: 20px;
  height: 20px;
  position: absolute;
}
#main #home{
  width: 500px;
  height: 460px;
  left: 20px;
  top: 20px;
  position: relative;
  background: url(./images/background.jpg) no-repeat;
}
#main #home div{
  position: absolute;
}
#main div.wall{
  width: 540px;
  height: 20px;
  background: url("./images/div.jpg") repeat-x;
  position: absolute;
}
#main div.top{
  left:0px;
  top:0px;
}
 
#main div.bottom{
  left:0px;
  top:480px;
}
#main div.left{
  width: 20px;
  height: 500px;
  background: url(./images/div.jpg) repeat-y;
  left:0px;
  top:0px;
}
#main div.right{
  width: 20px;
  height: 500px;
  background: url(./images/div.jpg) repeat-y;
  left:520px;
  top:0px;
}
 
.l{
  -moz-transform:rotate(0deg);  
  -o-transform:rotate(0deg);
  -webkit-transform:rotate(0deg);
  transform:rotate(0deg);
  /* IE8+ - must be on one line, unfortunately */  
  -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=1, M12=0, M21=0, M22=1, SizingMethod='auto expand')";   
  /* IE6 and 7 */ 
  filter: progid:DXImageTransform.Microsoft.Matrix(      M11=1,      M12=0,      M21=0,      M22=1,      SizingMethod='auto expand');
}
.t{
  -moz-transform:  rotate(90deg);   -o-transform:   rotate(90deg);   -webkit-transform: rotate(90deg);   transform:     rotate(90deg);
  /* IE8+ - must be on one line, unfortunately */  -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=-1.8369701987210297e-16, M12=-1, M21=1, M22=-1.8369701987210297e-16, SizingMethod='auto expand')";   /* IE6 and 7 */  filter: progid:DXImageTransform.Microsoft.Matrix(      M11=-1.8369701987210297e-16,      M12=-1,      M21=1,      M22=-1.8369701987210297e-16,      SizingMethod='auto expand');
 
}
.r{
  -moz-transform:  rotate(180deg);   -o-transform:   rotate(180deg);   -webkit-transform: rotate(180deg);   transform:     rotate(180deg);
   /* IE8+ - must be on one line, unfortunately */  -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=-1, M12=1.2246467991473532e-16, M21=-1.2246467991473532e-16, M22=-1, SizingMethod='auto expand')";   /* IE6 and 7 */  filter: progid:DXImageTransform.Microsoft.Matrix(      M11=-1,      M12=1.2246467991473532e-16,      M21=-1.2246467991473532e-16,      M22=-1,      SizingMethod='auto expand');
 
}
.b{
  -moz-transform:  rotate(270deg);   -o-transform:   rotate(270deg);   -webkit-transform: rotate(270deg);   transform:     rotate(270deg);
  /* IE8+ - must be on one line, unfortunately */  -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=6.123233995736766e-17, M12=1, M21=-1, M22=6.123233995736766e-17, SizingMethod='auto expand')";   /* IE6 and 7 */  filter: progid:DXImageTransform.Microsoft.Matrix(      M11=6.123233995736766e-17,      M12=1,      M21=-1,      M22=6.123233995736766e-17,      SizingMethod='auto expand');
   
}

JS公共文件

var home = $('#home');
  var snakeArr = [];
  var direcation = 'l';
  var speed = 0;
  var timer = '';
  //460/20
  var rows = 23;
  var cols = 25;
  var die = false;      //用於判斷是否game over
  var food = [];
  var sorce = 0;       //得分的顯示
 

首先要想有snake就必須創造snake,

for( var i=0; i<4; i++ ){
    //var snakeDiv = document.createElement("div");
    //snakeDiv.style = 'background:url(./images/snake' + i + '.png) no-repeat;';
    var snakeDiv = $('<div style="background:url(./images/snake' + i + '.png) no-repeat;z-index:999"></div>');
    home.append(snakeDiv);
    snakeArr[i] = {r : 10, c : 10 + i, div : snakeDiv, d : direcation};
    setPosition(snakeArr[i]); 
  }

 有snake之後,自然就是移動了(move):

function move(){
    var timer = setInterval(function(){
    for( var i=snakeArr.length -1; i>0; i-- ){
      snakeArr[i].c = snakeArr[i-1].c;
      snakeArr[i].r = snakeArr[i-1].r;
      snakeArr[i].d = snakeArr[i-1].d;
      }
 
      switch(direcation){
      case 'l' :
        snakeArr[0].c--;
        snakeArr[0].d = 'l';
        break;
 
      case 'r' :
        snakeArr[0].c++;
        snakeArr[0].d = 'r';
        break;
 
      case 't' :
        snakeArr[0].r--;
        snakeArr[0].d = 't';
        break;
 
      case 'b' :
        snakeArr[0].r++;
        snakeArr[0].d = 'b';
        break;
    }
 
    //snake的方向控制
    $(window).keydown(function(event){
      switch(event.keyCode){
        case 37 :
          direcation = 'l';
          break;
 
        case 38 :
          direcation = 't';
          break;
 
        case 39 :
          direcation = 'r';
          break;
 
        case 40 :
          direcation = 'b';
          break;
      }
    });
 
      //snake事故
      //1. snake撞牆
      if( snakeArr[0].c < 0 || snakeArr[0].r < 0 || snakeArr[0].c >= cols || snakeArr[0].r >= rows ){
          clearInterval(timer);
          die = true;
          alert('GAME OVER');
      }
 
      //2. snake撞到自己
      for( var i=1; i<snakeArr.length; i++ ){
        if( snakeArr[0].c == snakeArr[i].c && snakeArr[0].r == snakeArr[i].r ){
           clearInterval(timer);
           die = true;
           alert('GAME OVER');
        }
      }
 
      //snake吃水果
      if( snakeArr[0].c == food[0].c && snakeArr[0].r == food[0].r ){
        food[0].div.css({background : 'url(./images/snake2.png) no-repeat'});
        snakeArr.splice(snakeArr.length - 1, 0, food[0]);
        food.shift();
        sorce += 10;
        $('#score').html(sorce);
      }
 
      //snake產生水果
      if( food.length == 0 ){
        createFood(); 
      }
 
 
      for(var i = 0; i < snakeArr.length; i++){
        setPosition(snakeArr[i]);
      }
    },speed);
 
}

食物的產生:

function createFood(){
    var r = parseInt(rows * Math.random());
    var c = parseInt(cols * Math.random());
    var casrsh = false;
     
    //2個水果出現的位置不能一樣
    while( food.length == 0 ){
      //判斷snake的位置,不能與snake相撞
      for( var i = 0; i < snakeArr.length; i++ ){
        if( r == snakeArr[i].r && c == snakeArr[i].c ){
          casrsh = true;
        }
      }
      //當位置不重疊的時候,產生水果
      if( !casrsh ){
        var i = parseInt(4 * Math.random());
        var foodDiv = $('<div style="background:url(./images/fruit'+ i +'.png);"></div>');
        home.append(foodDiv);
        food.push({r : r, c : c, div : foodDiv});
        setPosition(food[0]);
      }
    }
     
  } 

 還有一個重要的功能就是重新設置定位:

function setPosition(obj){
    obj.div.css({left : obj.c * 20, top : obj.r * 20}); 
    obj.div.removeClass().addClass(obj.d);
  }
  createFood();  //那頁面一被加載出來就顯示出食物! 

希望本文所述對大家學習javascript程序設計有所幫助。

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