介绍
本篇文章给大家分享的是有关使用原生js做一个贪吃蛇游戏,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
原生JavaScript实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下
<强>代码:强>
& lt; script> var计时器=零; var oMain=. getelementbyid (“main"); 函数映射(atom、xnum ynum){//地图,设置单位大小,及根据单位大小创建地图 这一点。原子=原子; 这一点。xnum=xnum; 这一点。ynum=ynum; 这一点。创建=function () { 这一点。帆布=document.createElement (“div"); this.canvas.style。cssText=拔恢?相对;最高:40 px;边界:1 px固体红色;背景:# F1F1F1;“ this.canvas.style。宽度=T?。xnum +“px"//画布宽 this.canvas.style。身高=T?。ynum +“px"//画布高 main.appendChild (this.canvas); } } 功能食品(地图){//食物 这一点。宽度=map.atom; 这一点。身高=map.atom;//实现随机背景色 这一点。背景=皉gb (“+ Math.floor (math . random () * 200) +“,“+ Math.floor (math . random () * 200) +“,“+ Math.floor (math . random () * 200) +“)“; 这一点。x=Math.floor (math . random () * map.xnum); 这一点。y=Math.floor (math . random () * map.ynum); 这一点。国旗=document.createElement (& # 39; div # 39;); this.flag.style。宽度=?矶? & # 39;px # 39;; this.flag.style。身高=I砀? & # 39;px # 39;; this.flag.style。写成backgroundColor=this.bgColor; this.flag.style。borderRadius=& # 39; 50% & # 39;; this.flag.style。位置=癮bsolute"; this.flag.style。离开了= *。宽度+ & # 39;px # 39;; this.flag.style。=这。y *。身高+ & # 39;px # 39;; map.canvas.appendChild (this.flag); }//重新开始 函数重新启动(地图、蛇){ (var=0;i0;我(){ this.body[我]。x=this.body(张)方式; this.body[我]。y=this.body .y(张) } 开关(this.direction) { 例“left": this.body [0]。x -=1;断裂; 例“right": this.body [0]。x +=1;断裂; 例“up": this.body [0]。y -=1;断裂; 例“down": this.body [0]。y +=1;断裂; }//吃食物 如果(this.body [0]。x==食物。x和,this.body [0]。y==food.y) { this.body。推动({x: null, y: null,国旗:零}); map.canvas.removeChild (food.flag); 食物=new(图); }//判断游戏结束 如果(this.body [0] .x<0 | | this.body [0] .x>地图。xnum-1 | | this.body [0] .y<0 | | this.body [0] .y> map.ynum-1) { clearInterval(计时器); 警报(“游戏结束了!“); 重启(地图,这个); 返回错误; } (var=4;i 使用原生js做一个贪吃蛇游戏