来自 系统操作 2019-09-04 19:50 的文章
当前位置: 六合联盟网 > 系统操作 > 正文

js贪吃蛇网页版游戏特效代码分享,js贪吃蛇思路

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程序设计有所帮助。

图片 2

您可能感兴趣的文章:

  • javascript 实现的多浏览器支持的贪吃蛇webgame
  • javascript 贪吃蛇实现代码
  • javascript 贪吃蛇(详细注释版)
  • JS写的贪吃蛇游戏(个人练习)
  • javascript贪吃蛇完整版(源码)
  • javascript实现简单的贪吃蛇游戏
  • 原生js实现的贪吃蛇网页版游戏完整实例
  • javascript编写贪吃蛇游戏
  • js贪吃蛇网页版游戏特效代码分享(挑战十关)
  • js编写“贪吃蛇”的小游戏

本文实例为大家分享了js贪吃蛇游戏的相关代码,供大家参考,具体内容如下 !DOCTYPE html...

小提示:浏览器中如果不能正常运行,可以尝试切换浏览模式。
为大家分享的js贪吃蛇网页版游戏特效代码如下

<body><title>js贪吃蛇网页版游戏特效</title></body>
<script> 
 Star = {
 init:function(){
  var bigDiv = this.appendEle(this.addStyle(this.creatEle(),
  {w:'900',h:'600',p:'absolute',t:10,l:500}));
  for(var i = 0; i<600/30;i++){
  Star.data.arrayAll[i] = [];
  for(var j = 0; j<900/30; j++){
   div = this.addStyle(this.creatEle(),{w:(!+[1,] ? 30 :28),h:(!+[1,] ? 30 :28),f:'left',border:'1px solid #666'});
   div.setAttribute('number', i*30+j)
   this.appendEle(div,bigDiv)
   Star.data.arrayAll[i][j] = div;
  }
  }
  bigDiv = this.appendEle(this.addStyle(this.creatEle(),
  {w:'900',h:'600',p:'absolute',t:10,l:500}));


  this.pushEleInSelect(Star.data.arrayAll[9][15],Star.data.arrayAll[9][14],Star.data.arrayAll[9][13])
  this.keyBoard.apply(this,arguments);
  this.appearPoint();
  this.leftGo();
 },
 appearPoint:function(){
  var arrayIn = [];
  var number;
  for(var i = 0; i<600; i++){
  if(!this.hasInArray(Star.data.arrayAll[parseInt(i/30)][i%30].getAttribute('number'),Star.data.arraySelect)){
   arrayIn.push(Star.data.arrayAll[i])
  }
  }
  Star.data.foodNumber = number = parseInt(Math.random()*arrayIn.length);
  this.giveColor(number)
 },
 giveColor:function(number){
  var div = Star.data.arrayAll[parseInt(number/30)][number%30];
  Star.timeInterval.timeB = setInterval(function(){
  if(div.className == 'shanshuo'){
   div.className = ''
   div.style.backgroundColor = '#fff'
  }
  else{
   div.className = 'shanshuo';
   div.style.backgroundColor = '#f00'
  }
  },500)
 },
 disappearColor:function(){
  clearInterval(Star.timeInterval.timeB);
  Star.data.arrayAll[parseInt(Star.data.foodNumber/30)][Star.data.foodNumber%30].style.backgroundColor = '#f00';
 },
 hasInArray:function(number,array){
  for(var i in array){
  if(array[i] instanceof Array){
   if(this.hasInArray(number,array[i])){
   return true;
   }
  }
  if(array[i].getAttribute && array[i].getAttribute('number') == number) return true;
  }
  return false;
 },
 keyBoard:function(){
  var self = this;
  document.onkeydown = function(e){
  e = e? e : window.event;
  switch(e.keyCode){
   case 37: if(Star.keycode == 37 || Star.keycode == 39){return;}; self.leftGo(); break;
   case 38: if(Star.keycode == 38 || Star.keycode == 40){return;}; self.upGo();break;
   case 39: if(Star.keycode == 37 || Star.keycode == 39){return;}; self.rightGo();break;
   case 40: if(Star.keycode == 38 || Star.keycode == 40){return;}; self.downGo();break;
  }
  }
 },
 leftGo:function(){
  var div, number , self = this;
  Star.keycode = 37;
  clearInterval(Star.timeInterval.timeA)
  Star.timeInterval.timeA = setInterval(function(){
  number = Star.data.arraySelect[0].getAttribute('number');
  if(number%30<=0 || self.hasInArray(number-1,Star.data.arraySelect)){
   self.guanle();
  }
  else{
   if(Star.data.foodNumber == number-1){
   self.pushEleInSelect(Star.data.arrayAll[parseInt(Star.data.foodNumber/30)][Star.data.foodNumber%30]);
   self.disappearColor();
   self.appearPoint();
   }
   else{
   div = Star.data.arraySelect.pop();
   div.style.background = '#fff';

   self.pushEleInSelect(Star.data.arrayAll[parseInt(number/30)][number%30-1]);
   }
  }
  },Star.timeInterval.speed)
 },
 upGo:function(){
  var div, number , self = this;
  Star.keycode = 38;
  clearInterval(Star.timeInterval.timeA)
  Star.timeInterval.timeA = setInterval(function(){
  number = parseInt(Star.data.arraySelect[0].getAttribute('number'));

  if(parseInt(number/30)<=0 || self.hasInArray(number-30,Star.data.arraySelect)){
   self.guanle();
  }
  else{
   if(Star.data.foodNumber == number-30){
   self.pushEleInSelect(Star.data.arrayAll[parseInt(Star.data.foodNumber/30)][Star.data.foodNumber%30]);
   self.disappearColor();
   self.appearPoint();
   }
   else{
   div = Star.data.arraySelect.pop();
   div.style.background = '#fff';
   self.pushEleInSelect(Star.data.arrayAll[parseInt(number/30)-1][number%30]);
   }
  }
  },Star.timeInterval.speed)
 },
 rightGo:function(){
  var div, number , self = this;
  Star.keycode = 39;
  clearInterval(Star.timeInterval.timeA)
  Star.timeInterval.timeA = setInterval(function(){
  number = parseInt(Star.data.arraySelect[0].getAttribute('number'));
  if(parseInt(number%30)>=29 || self.hasInArray(number+1,Star.data.arraySelect)){
   self.guanle();
  }
  else{
   if(Star.data.foodNumber == number+1){
   self.pushEleInSelect(Star.data.arrayAll[parseInt(Star.data.foodNumber/30)][Star.data.foodNumber%30]);
   self.disappearColor();
   self.appearPoint();
   }
   else{
   div = Star.data.arraySelect.pop();
   div.style.background = '#fff';
   self.pushEleInSelect(Star.data.arrayAll[parseInt(number/30)][number%30+1]);
   }
  }
  },Star.timeInterval.speed)
 },
 downGo:function(){
  var div, number , self = this;
  Star.keycode = 40;
  clearInterval(Star.timeInterval.timeA)
  Star.timeInterval.timeA = setInterval(function(){
  number = parseInt(Star.data.arraySelect[0].getAttribute('number'));
  if(parseInt(number/30)>=19 || self.hasInArray(number+30,Star.data.arraySelect)){
   self.guanle();
  }
  else{
   if(Star.data.foodNumber == number+30){
   self.pushEleInSelect(Star.data.arrayAll[parseInt(Star.data.foodNumber/30)][Star.data.foodNumber%30]);
   self.disappearColor();
   self.appearPoint();
   }
   else{
   div = Star.data.arraySelect.pop();
   div.style.background = '#fff';
   self.pushEleInSelect(Star.data.arrayAll[parseInt(number/30)+1][number%30]);
   }
  }
  },Star.timeInterval.speed)
 },
 guanle:function(){
  alert('撞墙了,总分:' + (Star.data.arraySelect.length-3) * parseInt(1000 / Star.timeInterval.speed));
  location.reload();
 },
 creatEle:function(tag){
  var tagName = tag || 'DIV'
  return document.createElement(tagName)
 },
 appendEle:function(ele,father){
  var father = father || document.body || document.documentElement
  father.appendChild(ele)
  return ele;
 },
 addStyle:function(ele,css){
  for(var i in css){
  switch(i){
   case 'b' : ele.style.background = css[i];  break;
   case 'l' : ele.style.left  = css[i]+'px'; break;
   case 'r' : ele.style.right  = css[i]+'px'; break;
   case 't' : ele.style.top  = css[i]+'px'; break;
   case 'd' : ele.style.down  = css[i]+'px'; break;
   case 'p' : ele.style.position = css[i];  break;
   case 'w' : ele.style.width  = css[i]+'px'; break;
   case 'h' : ele.style.height  = css[i]+'px'; break;
   case 'f' : ele.style.cssFloat = css[i]; ele.style.styleFloat = css[i];  break;
   default : ele.style[i]   = css[i];  break;
  }
  }
  return ele;
 },
 pushEleInSelect:function(){
  for(var i = 0; i<arguments.length; i++){
  Star.data.arraySelect = [arguments[i]].concat(Star.data.arraySelect)
  this.addStyle(arguments[i],{b:'#f00'})
  }
 }
 }
 Star.data={
 arrayAll : [],
 arraySelect:[],
 newPoint:null,
 foodNumber:0
 }
 Star.timeInterval={
 timeA:null,
 timeB:null
 }
 Star.keycode = 0;


 window.onload = function(){
 var select = Star.creatEle('select');
 var optionDefault = Star.creatEle('option');
 optionDefault.innerHTML = '请选择关卡'
 Star.appendEle(optionDefault,select)
 Star.addStyle(select,{w:200,h:30,p:'absolute',left:'40%',top:'40%'})
 for(var i = 0 ; i <10 ; i++){
  var option = Star.creatEle('option');
  option.innerHTML = '第' + (i+1) + '关'
  Star.appendEle(option,select);
 }
 Star.appendEle(select)
 select.onchange = function(){
  selectValue = select.options[select.selectedIndex].value || select.options[select.selectedIndex].innerHTML
  var number = selectValue.match(/d+/)[0]
  Star.timeInterval.speed = parseInt(200/number);
  Star.addStyle(select,{display:'none'});
  Star.init();
 }
 }

</script>

以上就是为大家分享的js贪吃蛇网页版游戏特效代码,希望大家可以喜欢。

您可能感兴趣的文章:

  • js贪吃蛇游戏实现思路和源码
  • js编写“贪吃蛇”的小游戏
  • javascript编写贪吃蛇游戏
  • 原生js实现的贪吃蛇网页版游戏完整实例
  • javascript实现简单的贪吃蛇游戏
  • javascript贪吃蛇完整版(源码)
  • JS写的贪吃蛇游戏(个人练习)
  • javascript 贪吃蛇(详细注释版)
  • javascript 贪吃蛇实现代码
  • 纯js和css完成贪吃蛇小游戏demo

本文由六合联盟网发布于系统操作,转载请注明出处:js贪吃蛇网页版游戏特效代码分享,js贪吃蛇思路

关键词: