JavaScript 实现各种小游戏源码 !js贪吃蛇源码

整理来自大四初学 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
  • 8
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值