怎么使用原生JS实现贪吃蛇小游戏

  介绍

小编给大家分享一下怎么使用原生JS实现贪吃蛇小游戏,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获、下面让我们一起去了解一下吧!

具体内容如下

思路:在页面上添加一个地图,以提供边界,在地图中随机出现食物,给蛇身设置一个初始长度,用键盘方向键控制蛇的走向,当蛇触碰到食物时(既坐标重复时),增加蛇身长度,碰到墙壁或自身时,程序停止,游戏结束。

HTML结构:

& lt; body>   ,& lt; div  id=癿ap"祝辞& lt;/div>   & lt;/body>

CSS样式:

& lt; style>   ,#{地图   ,,宽度:600 px;   ,,身高:300 px;   ,,背景:# ccc;   边境才能:5 px  solid 黑人;   保证金才能:0,汽车;   位置:,才能相对;}   & lt;/style>

js实现功能:

& lt; script>   ,class 地图{//地图   构造函数才能(){   ,,this.mapEle =, . getelementbyid (“map");   ,,this.w =, this.mapEle.offsetWidth;   ,,this.h =, this.mapEle.offsetHeight;   ,,}   ,}   ,class 食物{//食物   构造函数才能(){   ,,this.w =, 20;   ,,this.h =, 20;   ,,this.x =, 0;   ,,this.y =, 0;   ,,this.c =,“orange";   ,,this.createEle ();   ,,},   createEle才能(){   ,,this.foodEle =, document.createElement (“div");   ,,this.foodEle.style.cssText =,“宽度:$ {this.w} px;高度:$ {this.h} px;背景:$ {this.c};位置:绝对的,左:$ {this.x  *, this.w} px;: $ {this.y  *, this.h} px; border - radius:, 40%;”;   ,,m.mapEle.appendChild (this.foodEle);   ,,}   randomPos才能(){   ,,this.x =,随机(0,(m.w-this.w),/, this.w);   ,,this.y =,随机(0,(m.h-this.h),/, this.h);   ,,this.foodEle.style.left =, this.x  *, this.w  +,“px";   ,,this.foodEle.style.top =, this.y  *, this.h  +,“px";   ,,}   ,}   ,class 蛇{//身体   构造函数才能(){   ,,this.w =, 20;   ,,this.h =, 20;   ,,this.body =, [{   ,,,,避署:null, x: 4, y: 3 c: randomColor ()   ,,},{   ,,,避署:null, x: 3 y: 3 c: randomColor ()   ,,},{   ,,,避署:null, x: 2, y: 3 c: randomColor ()   ,,}];   ,,this.d =,“right",,//设置默认行走方向   ,,this.createEle ();   ,,}   createEle才能(){   ,,(var 我=0;i 0;我——){   ,,,this.body[我].x =, this.body(张)方式;   ,,,this.body[我].y =, this.body .y(张);   ,,}   ,,开关(this.d) {   ,,,case “left": this.body [0] .x  -=, 1;断裂;   ,,,case “right": this.body [0] .x  +=, 1;断裂;   ,,,case “top": this.body [0] .y  -=, 1;断裂;   ,,,case “bottom": this.body [0] .y  +=, 1;断裂;   ,,}   ,,如果(this.body [0] .x  & lt;, 0, | |, this.body [0] .y  & lt;, 0, | |, this.body [0] .x 祝辞,((m.w-this.w),/, this.w), | |, this.body [0] .y 祝辞,((m.h-this.h),/, this.h)) {   ,,,警报(“撞墙了“);   ,,,返回;   ,,}   ,,如果(this.body [0] .x ===, f.x ,,, this.body [0] .y ===, f.y) {   ,,,this.body.push({避署:null, x: this.body this.body.length-1。x, y: this.body this.body.length-1 .y, c: randomColor ()});   ,,,f.randomPos ();   ,,}   ,,(var  i=1; i< this.body.length;我+ +){   ,,,如果(this.body [0] .x ==, this.body[我].x ,,, this.body [0] .y ==, this.body[我].y) {   ,,,,警报(“撞到自己了“);   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null

怎么使用原生JS实现贪吃蛇小游戏