微信小游戏开发入门
之前学习了微信小程序开发,现在准备换换口味,尝试一下小游戏开发。开发环境和工具基本是不用换的,只不过我会尝试用一下webstorm,据说很好用。(如何申请微信开发者账号,云开发等这里不做介绍)
开发准备:
- 微信开发者工具(webstorm)
- nodejs
知识储备(主要):
- js(ES5、ES6)
- canvas
小游戏体系结构认识
模块分解
- game.js 游戏全局入口,是必须要有的文件
- main.js 程序主类,主要用来初始化canvas和一些全局对象,各个精灵和帮绑定事件
- director.js 程序导演类,用来控制游戏逻辑和精灵的创建销毁,控制游戏主循环
- dataStore.js 存储游戏需要长期保存的变量和需要定时销毁的变量
- resources.js 游戏资源
- resourceLoader.js 资源加载,保证游戏是在加载图片结束后开始主循环
- spirit.js 游戏精灵的基类,背景,陆地,小鸟等等都是它的子类
- backGround.js 背景类,用来放幕布
内容实现
资源加载
- 首先实现资源类,将需要用到的资源统一加载 - 1 
 2
 3
 4
 5
 6
 7
 8- export const Resources = [ 
 ['background','res/background.png'],
 ['land','res/land.png'],
 ['pencilUp','res/pie_up.png'],
 ['pencilDown','res/pie_down.png'],
 ['birds','res/birds.png'],
 ['startButton','res/start_button.png']
 ];
- 然后实现资源加载类, - 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28- import {Resources} from "./Resources.js"; 
 export class ResourceLoader {
 constructor() {
 this.map = new Map(Resources)
 for(let [key,value] of this.map){
 const image = wx.createImage();
 image.src = value;
 this.map.set(key, image);
 }
 }
 onLoaded(callback) {
 let loadedCount = 0;
 for(let value of this.map.values()){
 value.onload = () => {
 loadedCount ++;
 if (loadedCount >= this.map.size){
 callback(this.map);
 }
 }
 }
 }
 static create(){
 return new ResourceLoader();
 }
 }- 首先引用之前的资源类,并将对应的图片拷贝到对应位置。在这个类中,有一个构造函数,用来创建对应的image对象并重新赋值给map. onLoaded函数用来确保所有资源已经加载完成。callback作用回调函数。 - 数据存储- 将游戏中,需要用到的各种变量统一存储,便于管理。我们创建DataStore类. - 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28- export class DataStore { 
 ctx = null;
 static getInstance(){
 if(!DataStore.instance){
 DataStore.instance = new DataStore();
 }
 return DataStore.instance;
 }
 constructor() {
 this.map = new Map();
 }
 put(key,value) {
 if (typeof value === 'function'){
 value = new value();
 }
 this.map.set(key,value);
 return this;
 }
 get(key) {
 return this.map.get(key);
 }
 destroy() {
 for (let value of this.map.values()){
 value = null;
 }
 }
 }- 首先我们需要有一个创建实例的函数getInstance,并且设置为静态方法,这样使用的时候就不必new一个对象出来 (js可以new对象 您呢?)。并且我们需要单例模式,所以需要判断是否已经创建。put函数用来set内容。并且如果传递的参数为类名(也即函数名),则创建一个对象. get方法就是来取得内容. - 未完待续….. 
 

