的小游戏,js贪吃蛇游戏达成思路和源码
分类:计算机网络

贪吃蛇儿时的追忆,前几日恰恰学习到那了,就正好做了多个,也是学习了吧,要求调节的学识:

js贪吃蛇游戏达成思路和源码,js贪吃蛇思路源码

本文实例为大家大饱眼福了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:0</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>

效果图:

图片 1

思路:

function newgame(){
  重置蛇和分数的数据;
  清除interval;
  初始化画布;
  画一条蛇;
  放置食物;
  使用定时器(setInterval)使蛇移动(move函数);
}
function move(){
  根据方向改变蛇头下一格将要到达的位置;
  判断游戏是否结束,以及显示结束的原因(包含输赢);
  蛇移动一格(moveIn函数);
}
对键盘的方向键作监控,当改变方向时,修改全局变量DIR的值(用于存储方向);
function moveIn(){
  在蛇头的前一格增加一格作为新的蛇头,并将蛇头的坐标作为第一个元素加入到代表蛇的数组中;
  if(没吃到食物){
    删除一格蛇尾,在画布中做相应改变;
  }
}

亟需留神的是,假如急需在JS中设定canvas中的宽度和可观,和装置任何CSS属性略有区别。

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

作者还为我们盘算了理想的专项论题:javascript杰出小游戏汇总

上述就是本文的全部内容,希望对大家学习javascript程序设计有所支持。

  1、JS函数的熟识通晓,

您大概感兴趣的作品:

  • javascript 完结的多浏览器帮助的贪吃蛇webgame
  • javascript 贪吃蛇达成代码
  • javascript 贪吃蛇(详细注释版)
  • JS写的贪吃蛇游戏(个人演习)
  • javascript贪吃蛇完整版(源码)
  • javascript兑现轻易的贪吃蛇游戏
  • 原生js实现的贪吃蛇网页版游戏全部实例
  • javascript编写贪吃蛇游戏
  • js贪吃蛇网页版游戏特效代码分享(挑衅十关)
  • js编写“贪吃蛇”的小游戏

本文实例为我们享用了js贪吃蛇游戏的有关代码,供大家参照他事他说加以考察,具体内容如下 !DOCTYPE html...

  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经典小游戏汇总

愿意本文所述对大家学习javascript程序设计有所帮忙。

你或者感兴趣的篇章:

  • JS写的贪吃蛇游戏(个人演习)
  • javascript贪吃蛇完整版(源码)
  • javascript 贪吃蛇达成代码
  • js贪吃蛇游戏达成思路和源码
  • javascript贯彻轻巧的贪吃蛇游戏
  • javascript 贪吃蛇(详细注释版)
  • 原生js实现的贪吃蛇网页版游戏全部实例
  • javascript 完成的多浏览器扶助的贪吃蛇webgame
  • javascript编写贪吃蛇游戏
  • 20行js代码达成的贪吃蛇小游戏

本文由正版必中一肖图发布于计算机网络,转载请注明出处:的小游戏,js贪吃蛇游戏达成思路和源码

上一篇:函数详解以及jQuery中position函数的应用 下一篇:没有了
猜你喜欢
热门排行
精彩图文