| #game{ width: 700px; height: 600px; position: relative; left: 50%; top: 40px; margin: 0 0 0 -350px; background: linear-gradient(-180deg, #040024 0%, #07165C 97%); } .game-ui{ display: none; padding: 55px; box-sizing: border-box; height: 100%; } [data-status="start"] .game-intro { display: block; padding-top: 180px; background: url(./img/bg.png) no-repeat 430px 180px; background-size: 200px; } [data-status="playing"] .game-info { display: block; position: absolute; top:0; left:0; padding:20px; } [data-status="failed"] .game-failed, [data-status="success"] .game-success, [data-status="all-success"] .game-all-success, [data-status="stop"] .game-stop{ display: block; padding-top: 180px; background: url(./img/bg-end.png) no-repeat 380px 190px; background-size: 250px; } |
面向对象

整个游戏可以把怪兽(Enemy)、飞机(Plane)、子弹(Bullet)都当作对象,另外还有配置对象(CONFIG)和控制游戏逻辑的游戏对象(GAME)。
游戏相关配置
| /** * 游戏相关配置 * @type {Object} */ var CONFIG = { status: 'start', // 游戏开始默认为开始中 level: 1, // 游戏默认等级 totalLevel: 6, // 总共6关 numPerLine: 7, // 游戏默认每行多少个怪兽 canvasPadding: 30, // 默认画布的间隔 bulletSize: 10, // 默认子弹长度 bulletSpeed: 10, // 默认子弹的移动速度 enemySpeed: 2, // 默认敌人移动距离 enemySize: 50, // 默认敌人的尺寸 enemyGap: 10, // 默认敌人之间的间距 enemyIcon: './img/enemy.png', // 怪兽的图像 enemyBoomIcon: './img/boom.png', // 怪兽死亡的图像 enemyDirection: 'right', // 默认敌人一开始往右移动 planeSpeed: 5, // 默认飞机每一步移动的距离 planeSize: { width: 60, height: 100 }, // 默认飞机的尺寸, planeIcon: './img/plane.png' }; |
定义父类
因为怪兽(Enemy)、飞机(Plane)、子弹(Bullet)都有相同的 x, y, size, speed 属性和 move() 方法,所以可以定义一个父类 Element,通过子类继承父类的方式实现。
| /*父类:包含x y speed move() draw()*/ var Element = function (opts) { this.opts = opts || {}; //设置坐标、尺寸、速度 this.x = opts.x; this.y = opts.y; this.size = opts.size; this.speed = opts.speed; }; Element.prototype.move = function (x, y) { var addX = x || 0; var addY = y || 0; this.x += addX; this.y += addY; }; //继承原型的函数 function inheritPrototype(subType, superType) { var proto = Object.create(superType.prototype); proto.constructor = subType; subType.prototype = proto; } |









