整理来自大四初学 JavaScript 写的贪吃蛇源码 。
// 页面加载完毕运行游戏
window.onload = function(){
GameControl.init();
};
// 游戏基本配置参数
var GameConfiguration = {
};
// 游戏控制器
var GameControl = {
init : function(){ //游戏初始化
GameConfiguration = {
GameStart : false, // 游戏是否已经开始
width : 500, // 游戏区域总宽度
height : 500, // 游戏区域总高度
time :null, // 蛇自动行走计时器
snakelength : null,// 蛇当前长度
frequency : 1, // 控制点击蛇转换方向频率
speed : 1000, // 蛇每移动的时间
newcol : null, // 新生成方块的列
newrow : null, // 新生成方块的行
NewRandowSqure : null, // 新随机生成的方块
NewMap : null, // 地图类
NewSnake : null, // 蛇类
score : 0, // 分数
addspeed : null // 自动增加速度
}
// 实例化地图类并绘画出来
GameConfiguration.NewMap = new map(GameConfiguration.width,GameConfiguration.height);
GameConfiguration.NewMap.draw();
// 实例化蛇并绘画出来
GameConfiguration.NewSnake = new snake();
GameConfiguration.NewSnake.draw();
// 监听键盘事件
document.onkeydown = function(e){
// 蛇移动监听事件
GameConfiguration.NewSnake.listenkeyboard(e.keyCode);
}
// 随机生成一个方块,并且不能与当前蛇身体各方块坐标重合
setColAndRow(GameConfiguration.NewSnake);
GameConfiguration.NewRandowSqure = new randowSqure();
GameConfiguration.NewRandowSqure.draw();
},
gameover : function(){
clearInterval(GameConfiguration.time);
clearInterval(GameConfiguration.addspeed);
document.onkeydown = null;
GameConfiguration.NewSnake.destory();
GameConfiguration.NewMap.destory();
this.init();
}
}
// 地图类
var map = function(width,height){
this.width = width;
this.height = height;
this.ele = null;
this.draw = function(){
if(this.ele == null){
this.ele = document.createElement('div');
this.ele.id = 'main';
this.ele.setAttribute('style','position: relative;margin:auto;overflow: hidden;');
this.ele.style.width = this.width +'px';
this.ele.style.height = this.height +'px';
document.body.app