这个游戏基本上是建立在JavaScript模块化的开发基础上进行封装的,对游戏里面需要使用到的游戏场景进行了封装,分别实现了Game,Sprite,enemy,player, base,Animation 等游戏类,后续代码还可以继续优化,最终实现的效果如下:
其他的所有核心代码已经开源:https://github.com/xiugangzhang/SuperMarioGame
在线预览游戏效果:
http://htmlpreview.github.io/?https://github.com/xiugangzhang/SuperMarioGame/blob/master/index.html
感兴趣的朋友可以对其进行继续优化,加上后续的其他功能!
其中游戏Game类代码如下:
// 完成Game类的封装
function Game(cfg) {
for (var attr in cfg) {
// 这里的this指的就是Game的对象
this[attr] = cfg[attr];
}
}
// 定义原型方法和属性
Game.prototype = {
constructor: Game,
// 游戏画布的初始化(这个是游戏画布的默认宽度和高度)
width: 640,
height: 480,
// 画布canvas和绘图句柄gc(在构造函数中已经完成了初始化)
canvas: null,
gc: null,
// 帧速率和时间间隔
FPS: 40,
sleep: 0,
// 游戏中的精灵
sprites: null,
// 游戏中的运动的背景
skyOffset: 0,
grassOffset: 0,
treeOffset: 0,
nearTreeoffset: 0,
TREE_VELOCITY: 20,
FAST_TREE_VELOCITY: 40,
SKY_VELOCITY: 8,
GRASS_VELOCITY: 75,
lastTime: 0,
lastUpdateFPS: 0,
lastUpdateTime: 0,
// 游戏场景的初始化(主要场景参数的初始化处理)
init: function () {
// 直接手动创建canvas元素
this.canvas = document.createElement("canvas");
this.canvas.width = this.width;
this.canvas.height = this.height;