javascript:用原生js模拟贪吃蛇游戏练习

 本次练习所有的代码:可以直接复制全部然后运行看效果~

 View Code

如下图:单个方块表示食物,三个方块连接一起表示小蛇,其中紫色方块是蛇头,虽然看起来简单,做起来也需要不少的步骤,我们先分析一下思路~

 

首先,创建一个地图~然后坐标随机显示食物方块,每次食物被小蛇“吃掉”的时候重新初始化;

然后,设置固定位置显示小蛇方块,设置定时器,让小蛇动起来,判断小蛇是否“吃掉”食物,是则初始化食物,复制蛇身最后一个方块加到小蛇身体最后~判断小蛇是否“撞墙”,是则提示游戏提示。

那么具体步骤现在开始~

设置食物方块的自调用函数

  • 设置方块的构造函数,同时设置一个变量准备存储每个小方块食物:
复制代码
(function () {     var elements = [];         function Food(x, y, width, height, color) {       this.x = x || 0;       this.y = y || 0;       this.width = width || 20;       this.height = height || 20;       this.color = color || "green";     }
//把Food暴露给window,外部可以访问
window.Food = Food;
}());
复制代码
  • 初始化食物,赋值并且在地图上显示出来,注意:记得把食物加到一开始设置的变量中 var elements = [ ];
复制代码
Food.prototype.init = function (map) {       remove();        var div = document.createElement("div");       map.appendChild(div);       div.style.width = this.width + "px";       div.style.height = this.height + "px";       div.style.backgroundColor = this.color;       div.style.position = "absolute";       this.x = parseInt(Math.random() * (map.offsetWidth / this.width)) * this.width;       this.y = parseInt(Math.random() * (map.offsetHeight / this.height)) * this.height;       div.style.left = this.x + "px";       div.style.top = this.y + "px";        //把div加入到数组elements中       elements.push(div);     };
复制代码
  • 设置初始化食物的第一个步骤,先在地图上删除这个食物:
复制代码
 function remove() {       for (var i = 0; i < elements.length; i++) {         var ele = elements[i];         ele.parentNode.removeChild(ele);         elements.splice(i, 1);       }     }
复制代码

设置小蛇的自调用函数

  • 设置方块的构造函数,同时设置一个变量准备存储每个小蛇的单个身体:
复制代码
(function () {     var elements = [];  function Snake(width, height, direction) {       this.width = width || 20;       this.height = height || 20;       this.body = [         {x: 3, y: 2, color: "red"},//头         {x: 2, y: 2, color: "orange"},//身体         {x: 1, y: 2, color: "orange"}//身体       ];       //方向       this.direction = direction || "right";     }
//把Snake暴露给window,外部可以访问
window.Snake = Snake;
}());
复制代码
  • 设置小蛇初始化的函数
关键字:
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信