原生JavaScript实现贪吃蛇(附源代码)
试玩链接:http://47.108.157.62:8080/csdn/snake.html
<script>
var timer = null;
var oMain = document.getElementById("main");
function Map(atom,xnum,ynum){
//地图,设置单位大小,及根据单位大小创建地图
this.atom = atom;
this.xnum = xnum;
this.ynum = ynum;
this.create = function(){
this.canvas = document.createElement("div");
this.canvas.style.cssText = "position: relative;top: 40px;border: 1px solid red;background: #F1F1F1;"
this.canvas.style.width = this.atom * this.xnum + "px";//画布宽
this.canvas.style.height = this.atom * this.ynum + "px";//画布高
main.appendChild(this.canvas);
}
}
function Food(map){
//食物
this.width = map.atom;
this.height = map.atom;
//实现随机背景色
this.bgColor = "rgb("+Math.floor(Math.random()*200)+","+Math.floor(Math.random()*200)+","+Math.floor(Math.random()*200)+")";
this.x = Math.floor(Math.random()*map.xnum);
this.y = Math.floor(Math.random()*map.ynum);
this.flag = document.createElement('div');
this.flag.style.width = this.width + 'px';
this.flag.style.height = this.height + 'px';
this.flag.style.backgroundColor = this.bgColor;
this