Alias O(1)采样算法

参考

算法解析

  1. 假设游戏抽奖: 1星:80权重, 2星:60权重, 3星:40权重, 4星:20权重。
  2. 根据权重值,计算他们出现的概率。得到概率数组:distribution,同时概率对应的值数组为:values
    1
    2
    3
    let weights = [80, 60, 40, 20] // 权重数组
    let distribution = [0.4, 0.3, 0.2, 0.1] // 概率数组
    let values = [1, 2, 3, 4] // 对应值数组
  3. 根据概率数组,制表得prob,alisa 数组。
  4. 根据数组随机

代码示例

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/*****************************
*@file: AliasMethod
*@author: 陈吕唐
*@desc: Alias 采样算法 初始化O(n) 调用O(1)
*@date: 2025-03-21 17:44
*****************************/
export default class AliasMethod {


/**
* 概率数组 存放第i列事件的概率
*/
private prob: number[];

/**
* 别名数组 存放第i列不是事件i的另外一个事件的标号
*/
private alias: number[];


private values: any[];
/**
*
* @param distribution 概率分布权重数组
* @param values 对应数值数组
*/
constructor(distribution: number[], values: any[] = []) {
if (values.length <= 0) {
values = distribution;
}


let n = distribution.length;

this.prob = new Array(n);
this.alias = new Array(n);
this.values = values;

/**
* 权重和
*/
let sum = distribution.reduce((a, b) => a + b);

/**
* 概率数组
*/
let normalizedDistribution = distribution.map(p => p / sum);

/**
* 柱状表
*/
normalizedDistribution = normalizedDistribution.map(p => p * n);

/**
* 概率小于1的下标
*/
let small: number[] = [];

/**
* 概率大等于1的下标
*/
let large: number[] = [];

/**
* 初始化下标数组
*/
for (let i = 0; i < normalizedDistribution.length; i++) {
if (normalizedDistribution[i] < 1) {
small.push(i);
} else {
large.push(i);
}
}

//制表
while (small.length > 0 && large.length > 0) {
/**
* 概率小于1的下标
*/
let smallIndex = small.pop();
/**
* 概率大于等于1的下标
*/
let largeIndex = large.pop();

this.prob[smallIndex] = normalizedDistribution[smallIndex];
this.alias[smallIndex] = largeIndex;

normalizedDistribution[largeIndex] = normalizedDistribution[largeIndex] + normalizedDistribution[smallIndex] - 1;

if (normalizedDistribution[largeIndex] < 1) {
small.push(largeIndex);
}

if (normalizedDistribution[largeIndex] >= 1) {
large.push(largeIndex);
}
}

while (large.length > 0) {
this.prob[large.pop()] = 1;
}

while (small.length > 0) {
this.prob[small.pop()] = 1;
}
}

/**
*
* @returns 随机值
*/
public sample(): number {
let n = this.prob.length;
let idx = Math.floor(Math.random() * n);
return Math.random() < this.prob[idx] ? this.values[idx] : this.values[this.alias[idx]];
}
}

Cocos 项目结构

参考

Cocos Create 成功配置

空包成功运行版本

  • 3.8.5
  • 2.4.12
    简单的文本页面构建成功

游戏成功运行版本

  • 2.4.12

Java环境

  • JAVA 17
  • Gradle 8.0.2

Android Studio

  • SDK
    • API 21
    • API 26
    • API 27
    • API 28
  • Build Tools
    • 34.0.0
  • Cmake 3.22.1
  • NDK 23.2.8568313

Cocos 偏好设置

  • NDK 路径 D:\software\env\Sdk\ndk\23.2.8568313
  • SDK 路径 D:\software\env\Sdk
  • Cmake 路径 D:\software\env\Sdk\cmake\3.22.1\bin\cmake.exe

Cocos 发布设置

  • API level 26
  • ABI
    • arm64-v8a
    • armeabi-v7a

Cocos 项目结构

参考

Cocos 热更新原理与过程

  1. 服务端和本地均保存完整版本的游戏资源。(前提)
  2. 本地向服务器发送请求,判断当前版本是否为最新。
  3. 对比本地和服务器的Manifest文件,判断的要更新的资源文件。
  4. 服务器端下载需要更新的资源文件。
  5. 修改游戏启动时候加载资源文件的位置,使用下载的最新资源。
  6. 重启游戏,使用最新的资源文件。

热更新相关文件

  • version_generator.js:Cocos 引擎提供的热更新工具,用于生成 Manifest 文件。
  • version.manifest:热更新版本信息文件,包含以下信息:
    • 当前版本号
    • 远程manifest文件地址
  • project.manifest:热更新项目信息文件,包含以下信息:
    • 当前版本号
    • 远程manifest文件地址
    • 热更新项目资源信息

热更新实现流程

  1. 构建发布对应平台的Native项目
  2. 下载version_generator.js
  3. 修改version_generator.js当中的热更新远程包地址,与对应平台构建出项目的位置
  4. 执行node version_generator.js -v 1.0.0命令生成对应版本的热更新包
  5. 将热更新包中的manifest文件放到项目中
  6. 将热更新包上传到到服务器端
  7. 修改服务器端获取版本号的接口

注意事项

  • 资源热更新只适用于原生发布版本
  • 要在main.js中修改热更新资源路径,不然第一次更新后成功,后面重新进入又是旧的资源。

代码示例与解析

生成热更新文件

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
// version_generator.js 热更新包生成脚本
// var fs = require('fs');
var fs = require('fs-extra');//先安装 npm install fs-extra
var path = require('path');
var crypto = require('crypto');

//热更新包远程地址(按照后端给的地址)
var remoteUrl = `https://xglxs.26joy.com/Upload/xyx/hotUpdate/remote-assets`;
var version = `1.0.0`;

var manifest = {
packageUrl: `${remoteUrl}${version}/`,
remoteManifestUrl: `${remoteUrl}${version}/project.manifest`,
remoteVersionUrl: `${remoteUrl}${version}/version.manifest`,
version: version,
assets: {},
searchPaths: []
};

//生成的manifest文件存放位置地址
var dest = './assets/';

//默认构建发布出的项目地址(按照发布的平台修改)
var src = './build/windows/assets/';

//热更新文件
var remoteDir = `./packages-hot-update/`;

// Parse arguments 解析参数
var i = 2;
while (i < process.argv.length) {
var arg = process.argv[i];

switch (arg) {
case '--url':
case '-u':
remoteUrl = process.argv[i + 1];
manifest.packageUrl = `${remoteUrl}${version}/`;
manifest.remoteManifestUrl = `${remoteUrl}${version}/project.manifest`;
manifest.remoteVersionUrl = `${remoteUrl}${version}/version.manifest`;
i += 2;
break;
case '--version':
case '-v':
version = process.argv[i + 1];
manifest.version = version;
manifest.packageUrl = `${remoteUrl}${version}/`;
manifest.remoteManifestUrl = `${remoteUrl}${version}/project.manifest`;
manifest.remoteVersionUrl = `${remoteUrl}${version}/version.manifest`;
i += 2;
break;
case '--src':
case '-s':
src = process.argv[i + 1];
i += 2;
break;
case '--dest':
case '-d':
dest = process.argv[i + 1];
i += 2;
break;
default:
i++;
break;
}
}


function readDir(dir, obj) {
var stat = fs.statSync(dir);
if (!stat.isDirectory()) {
return;
}
var subPaths = fs.readdirSync(dir), subpath, size, md5, compressed, relative;
for (var i = 0; i < subPaths.length; ++i) {
if (subPaths[i][0] === '.') {
continue;
}
subpath = path.join(dir, subPaths[i]);
stat = fs.statSync(subpath);
if (stat.isDirectory()) {
readDir(subpath, obj);
}
else if (stat.isFile()) {
// Size in Bytes
size = stat['size'];
md5 = crypto.createHash('md5').update(fs.readFileSync(subpath)).digest('hex');
compressed = path.extname(subpath).toLowerCase() === '.zip';

relative = path.relative(src, subpath);
relative = relative.replace(/\\/g, '/');
relative = encodeURI(relative);
obj[relative] = {
'size': size,
'md5': md5
};
if (compressed) {
obj[relative].compressed = true;
}
}
}
}

var mkdirSync = function (path) {
try {
fs.mkdirSync(path);
} catch (e) {
if (e.code != 'EEXIST') throw e;
}
}

// Iterate assets and src folder
readDir(path.join(src, 'src'), manifest.assets);
readDir(path.join(src, 'assets'), manifest.assets);

var destManifest = path.join(dest, 'project.manifest');
var destVersion = path.join(dest, 'version.manifest');

mkdirSync(dest);

var copyDir = `${remoteDir}remote-assets${version}/`;

fs.copy(path.join(src, 'src'), path.join(copyDir, 'src'), (err) => {
if (err) throw err;
console.log('src successfully copy');
});

fs.copy(path.join(src, 'assets'), path.join(copyDir, 'assets'), (err) => {
if (err) throw err;
console.log('assets successfully copy');
});

fs.writeFile(destManifest, JSON.stringify(manifest), (err) => {
if (err) throw err;
console.log('Manifest successfully generated');

fs.copyFile(destManifest, path.join(copyDir, `project.manifest`), (err) => {
if (err) throw err;
console.log('Manifest successfully copy');
});
});

delete manifest.assets;
delete manifest.searchPaths;
fs.writeFile(destVersion, JSON.stringify(manifest), (err) => {
if (err) throw err;
console.log('Version successfully generated');
fs.copyFile(destVersion, path.join(copyDir, `version.manifest`), (err) => {
if (err) throw err;
console.log('Version successfully copy');
});
});

/**
* 检查main.js (不怎么必要)
*/
var mainPath = path.join(src, `main.js`)
var mainIs = fs.existsSync(mainPath);
if (mainIs) {
var content = fs.readFileSync(mainPath).toString();
if (content.indexOf(`jsb.fileUtils.setSearchPaths`) != -1) {
console.log("main.js check successfully");
}

var add = `!function(){if("object"==typeof window.jsb){var e=localStorage.getItem("HotUpdateSearchPaths");if(e){var i=JSON.parse(e);jsb.fileUtils.setSearchPaths(i);var s=[],t=i[0]||"",l=t+"_temp/",r=l.length;jsb.fileUtils.isDirectoryExist(l)&&!jsb.fileUtils.isFileExist(l+"project.manifest.temp")&&(jsb.fileUtils.listFilesRecursively(l,s),s.forEach(e=>{var i=e.substr(r),s=t+i;"/"===e[e.length]?jsb.fileUtils.createDirectory(s):(jsb.fileUtils.isFileExist(s)&&jsb.fileUtils.removeFile(s),jsb.fileUtils.renameFile(e,s))}),jsb.fileUtils.removeDirectory(l))}}}();`
content = add + content;
fs.writeFile(mainPath, content, (err) => {
if (err) throw err;
console.log("main.js write successfully");
});
} else {
console.warn("Warn: main.js 文件不存在");
}

热更新功能类

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
// HotUpdate.ts 自定义热更新功能实现类
/*****************************
*@file: HotUpdate
*@author: 陈吕唐
*@desc: 热更新组件 node version_generator.js -v 1.0.0
*@date: 2022-01-22 15:45
*****************************/
/****************************
* 使用
* 1. 构建项目
* 2. 修改 version_generator 相关参数 remoteUrl src dest
* 3. node version_generator.js -v 1.0.0 执行生成 .manifest 文件
* 4. 将.manifest 和 src 下的 assets src 资源文件放到 远程remoteUrl
* 5. 修改main.js 在编辑器代码前添加 !function(){if("object"==typeof window.native){var e=localStorage.getItem("HotUpdateSearchPaths");if(e){var i=JSON.parse(e);native.fileUtils.setSearchPaths(i);var s=[],t=i[0]||"",l=t+"_temp/",r=l.length;native.fileUtils.isDirectoryExist(l)&&!native.fileUtils.isFileExist(l+"project.manifest.temp")&&(native.fileUtils.listFilesRecursively(l,s),s.forEach(e=>{var i=e.substr(r),s=t+i;"/"===e[e.length]?native.fileUtils.createDirectory(s):(native.fileUtils.isFileExist(s)&&native.fileUtils.removeFile(s),native.fileUtils.renameFile(e,s))}),native.fileUtils.removeDirectory(l))}}}();
* 不添加这代码的话,热更新成功后,关闭应用重新打开又是旧的代码
* ***************************/
/****************************
*
*
****************************/

import { game, native, sys } from 'cc';
export default class HotUpdate {
/****************************************************************************************************************
*Readonly 常量
****************************************************************************************************************/
/**
* 热更新资源存储路径
*/
private readonly STORAGE_PATH = `remotePath/`;

/**
* 热更新搜索路径
*/
private readonly HOT_UP_DATE_SEARCH_PATHS = `HotUpdateSearchPaths`;
/****************************************************************************************************************
*Property 定义变量
****************************************************************************************************************/
/**
* 热更新管理器
*/
private assetManger: native.AssetsManager = null;


/**
* 下载失败重试次数
*/
protected againDownFailAssetNumber: number = 3;

/**
* 热更新配置文件地址
*/
protected nativeUrl: string = undefined!;

/**
* 远程版本
*/
protected remoteVersion: string = "1.0.0";
/***************************************************************
* 热更新回调方法
***************************************************************/
/**
* 更新完成
*/
public completeFunc: () => void = undefined!;

/**
* 更新失败
*/
public updateFailFunc: (event: string) => void = undefined!;

/**
* 更新中
*/
public updatingFunc: (event: native.EventAssetsManager) => void = undefined!;

/**
* 为大版本更新
*/
public bigUpdateFunc: () => void = undefined!;
/****************************************************************************************************************
* Lifecycle 生命周期相关方法
****************************************************************************************************************/
/**
*
* @param nativeUrl 热更新文件地址:project.manifest文件资源(类型:Asset) 资源的地址 manifest.nativeUrl
* @param remoteVersion 远程版本:从后端接口获取
*/
constructor(nativeUrl: string, remoteVersion: string) {
this.nativeUrl = nativeUrl;
this.remoteVersion = remoteVersion;
this.initHotUpdate();
}
/****************************************************************************************************************
* Public 公有方法
****************************************************************************************************************/
/****************************************************************************************************************
* Project 公有方法
****************************************************************************************************************/
/**
* 检查更新
*/
public checkUpdate() {
if (this.isHotUpdate()) {
this.checkUpdateByRemote();
} else {
this.checkUpdateComplete();
}
}

/**
* 获取本地版本号
* @returns 当前manifest文件中的版本号,热更新不可用情况下返回默认版本号
*/
public getLocalVersion(defaultVersion: string = `1.0.0`): string {
if (this.isHotUpdate()) {
defaultVersion = this.manifest.version;
}
return defaultVersion;
}
/****************************************************************************************************************
* private 私有方法
****************************************************************************************************************/
/**
* 检查更新
*/
private async checkUpdateByRemote() {
let localVersion = this.manifest.version;
let remoteVersion = this.remoteVersion;

/**
* 检查是否为大版本更新,需要用户重新下载。
*/
if (this.versionBigUpdate(localVersion, remoteVersion)) {
this.checkBigUpdate();
return;
}

/**
* 对比本地版本与远程版本
*/
let check = this.versionCompareHandle(localVersion, remoteVersion);
if (check < 0) {

this.manifest = this.updateManifestRemoteUrl(this.manifest, remoteVersion);
await new Promise<void>((resolve, reject) => { setTimeout(() => { resolve() }, 1000) })
if (this.manifest) {
this.assetManger.loadLocalManifest(this.manifestFilePath);
this.assetManger.setEventCallback(this.checkUpdateEvent.bind(this));
this.assetManger.checkUpdate();
} else {
this.checkUpdateFail(`写入Manifest失败`);
}
} else {
this.checkUpdateComplete();
}
}


/**
* 监听版本检查相关事件
* @param event
*/
private checkUpdateEvent(event: native.EventAssetsManager) {
switch (event.getEventCode()) {
case native.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST:
case native.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST:
case native.EventAssetsManager.ERROR_PARSE_MANIFEST:
this.checkUpdateFail(event.getMessage());
break;
case native.EventAssetsManager.NEW_VERSION_FOUND:
this.checkUpNew();
break;
case native.EventAssetsManager.ALREADY_UP_TO_DATE:
//已更新到最新版本
this.checkUpdateComplete();
break;
default:
break;
}
}

/**
* 监听热更新事件
* @param event
*/
private hotUpdateEvent(event: native.EventAssetsManager) {
switch (event.getEventCode()) {
case native.EventAssetsManager.UPDATE_PROGRESSION:
//更新中 更新进度
this.updating(event)
break;
case native.EventAssetsManager.UPDATE_FAILED:
this.updateFailAgain(event);
break;
case native.EventAssetsManager.UPDATE_FINISHED:
//更新完成
this.updateGameComplete();
break;
default:
break;
}
}
/****************************************************
* Init
***************************************************/
/**
* 在热更新位置创建和初始一样的备份
* @param path 文件位置
* @param defaultAssets 用于备份的资源
*/
private initManifestFilePath(path: string = this.manifestFilePath, nativeUrl: string = this.nativeUrl) {
if (!native.fileUtils.isDirectoryExist(this.storagePath)) {
native.fileUtils.createDirectory(this.storagePath);
}
/**
* 创建热更新位置的Project
*/
let read = native.fileUtils.getStringFromFile(nativeUrl);
return native.fileUtils.writeStringToFile(read, path);
}

/**
* 初始热更新管理器
* @param assetsNativeUrl
* @returns
*/
private initHotUpdate(): void {
if (!this.isHotUpdate()) {
return;
}

/**
* 热更新文件存放地址(一定要能写入地址,不然下载资源失败)
*/

this.assetManger = new native.AssetsManager(``, this.storagePath, this.versionCompareHandle);
this.assetManger.setVerifyCallback(this.assetsVerify.bind(this))
}
/****************************************************
* 热更新管理器事件处理
***************************************************/
/**
* 检测到新版本处理
*/
private checkUpNew() {
//发现有新版本
this.assetManger.setEventCallback(this.hotUpdateEvent.bind(this));
this.assetManger.update();
}

/**
* 更新失败处理(下载失败重试)
*/
private updateFailAgain(event: native.EventAssetsManager) {
if (this.againDownFailAssetNumber > 0) {
this.assetManger.downloadFailedAssets();
this.againDownFailAssetNumber--;
} else {
this.checkUpdateFail(event.getMessage());
}
}


/**
* 热更新游戏完成(重启游戏)
*/
private updateGameComplete() {
let paths: string[] = this.assetManger.getLocalManifest().getSearchPaths();

if (paths && paths.length > 0) {
localStorage.setItem(this.HOT_UP_DATE_SEARCH_PATHS, JSON.stringify(paths));
}

setTimeout(() => {
game.restart();
}, 3000)
}
/****************************************
* 更新结果处理
****************************************/
/**
* 更新中
*/
private updating(event: native.EventAssetsManager) {
if (this.updatingFunc) {
this.updatingFunc(event);
}
}
/**
* 更新失败
* @param event
*/
private checkUpdateFail(event: string) {
if (this.updateFailFunc) {
this.updateFailFunc(event)
}
}


/**
* 检查更新结果为大版本更新需要重新下载游戏
*/
private checkBigUpdate() {
if (this.bigUpdateFunc) {
this.bigUpdateFunc();
}
}

/**
* 检查更新完成,进入游戏
*/
private checkUpdateComplete() {
if (this.completeFunc) {
this.completeFunc();
}
}
/****************************************
* Utils
***************************************/
/**
* 判断的热更新是否可用
* @returns
*/
private isHotUpdate(): boolean {

/**
* 热更新只有Native平台可用
*/
return sys.isNative;
}
/**
* 是否为大版本更新,需要重新下载安装包
* @param versionA 当前版本
* @param versionB 远程版本
* @returns true 是大版本需要重新下载 false 只需要热更新就好了
*/
protected versionBigUpdate(versionA: string, versionB: string): boolean {
let vA = versionA.split('.');
let vB = versionB.split('.');

let a = parseInt(vA[0]);
let b = parseInt(vB[0]);

return a < b;
}

/**
* 资源验证
* @param path
* @param assets
*/
protected assetsVerify(path: string, assets: native.ManifestAsset): boolean {
return true;
}

/**
*
* @param versionA 本地版本
* @param versionB 远程版本
* @returns
*/
private versionCompareHandle(versionA: string, versionB: string): number {
// //`当前版本 : ${versionA} , 远程版本 : ${versionB}`);
let vA = versionA.split('.');
let vB = versionB.split('.');
for (let i = 0; i < vA.length && i < vB.length; ++i) {
let a = parseInt(vA[i]);
let b = parseInt(vB[i]);
if (a === b) {
continue;
}
else {
return a - b;
}
}
if (vB.length > vA.length) {
return -1;
}
return 0;
}


/**
* 修改manifest远程资源路径(本方法未写入文件)
* @param manifest 资源
* @param version 版本
* @returns
*/
private updateManifestRemoteUrl(manifest: Manifest, version: string): Manifest {
let beforePackageUrl: string = manifest.packageUrl;

/**
* 远程地址字符串去除版本
*/
let latestDir = "remote-assets";
let position = beforePackageUrl.lastIndexOf(latestDir);
if (position > 0) {
beforePackageUrl = beforePackageUrl.substring(0, position + latestDir.length);
}
if (beforePackageUrl[beforePackageUrl.length - 1] == "/") {
beforePackageUrl = beforePackageUrl.substring(0, beforePackageUrl.length - 1);
}

/**
* 加上新的版本字符串
*/
let afterPackageUrl = `${beforePackageUrl}${version}/`;

/**
* 修改manifest
*/
manifest.packageUrl = afterPackageUrl;
manifest.remoteManifestUrl = afterPackageUrl + "project.manifest";
manifest.remoteVersionUrl = afterPackageUrl + "version.manifest";

return manifest;
}
/****************************************************************************************************************
* Property Get && Set 属性的 get && set 函数
****************************************************************************************************************/
/**
* 热更新资源存放位置
*/
private get storagePath(): string {
/**
* 热更新文件存放地址(一定要能写入地址,不然下载资源失败)
*/
return native.fileUtils.getWritablePath() + `/${this.STORAGE_PATH}`;;
}

/**
* 实际读取的热更新配置文件地址
*/
private get manifestFilePath(): string {
return `${this.storagePath}project.manifest`;
}

/**
* 热更新文件
*/
private get manifest(): Manifest {
let manifest: Manifest = undefined!;

/**
* 文件位置
*/
let localFilePath = this.manifestFilePath

if (!native.fileUtils.isFileExist(localFilePath)) {
this.initManifestFilePath();
}

manifest = JSON.parse(native.fileUtils.getStringFromFile(localFilePath));
return manifest;
}

private set manifest(value: Manifest) {
/**
* 文件位置
*/
let localFilePath = this.manifestFilePath;

/**
* 写入的Json字符串
*/
let writeString = JSON.stringify(value);

native.fileUtils.writeStringToFile(writeString, localFilePath)
}
}

/**
* 热更新配置文件结构
*/
interface Manifest {
packageUrl: string;
/**
* 远程manifest文件地址
*/
remoteManifestUrl: string;
remoteVersionUrl: string;
/**
* 版本号
*/
version: string;
}

功能类使用

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import HotUpdate from '../../libs/HotUpdate';

@property({ type: Label, tooltip: `显示热更新进程文本` })
private updateLabel: Label = undefined;

@property({ type: Asset, tooltip: `热更新文件(project.manifest引用)` })
private manifest: Asset = undefined!;


private initHot() {
//远程版本,实际上应该上后端接口异步获取
let remoteVersion = '1.0.1';

let path = this.manifest.nativeUrl;

//创建热更新对象
let hot = new HotUpdate(path, remoteVersion);

//绑定热更新回调
hot.completeFunc = this.complete.bind(this);
hot.updatingFunc = this.updating.bind(this);
hot.updateFailFunc = this.hotFail.bind(this);

//显示当前版本
this.versionLabel.string = hot.getLocalVersion();

//检查更新
hot.checkUpdate();
}
/*******************************
* 热更新方法回调
*******************************/
private hotFail(error: string) {
this.updateLabel.string = `热更新失败:${error}`;
}

private updating(evet: jsb.EventAssetsManager) {
this.updateLabel.string = `更新中${evet.getMessage()}`;
}

private complete() {
this.updateLabel.string = `已经是最新版本`;
}

Cocos 项目结构

参考

Asset Bundle 介绍

  1. v2.4 开始,Creator 正式支持 Asset Bundle 功能。
  2. 开发者按需求将资源划分在多个 Asset Bundle 中。
  3. 游戏运行过程中,按需求加载不同的 Asset Bundle,以减少启动时需要加载的资源数量,从而减少首次下载和加载游戏时所需的时间。
  4. Asset Bundle 可以按需求随意放置,比如可以放在远程服务器、本地、或者小游戏平台的分包中。也可以跨项目复用,用于加载子项目中的 Asset Bundle。

Asset Bundle 的构造

  • 代码:文件夹中的所有代码会根据发布平台合并成一个index.jsgame.js的入口脚本文件,并从主包中剔除。
  • 资源:文件夹中的所有资源以及文件夹外的相关依赖资源都会放到importnative目录下。
  • 资源配置:所有资源的配置信息包括路径、类型、版本信息都会被合并成一个config.json文件。

内置 Asset Bundle

  • internal:存放所有内置资源以及其依赖资源
    • 优先级: 11
    • 简单的讲就是放引擎自己的代码,和引擎自带的资源。
  • start-scene:如果在 构建发布 面板中勾选了 初始场景分包,则首场景将会被构建到 start-scene 中。
    • 优先级: 9
    • 简单的讲就是放游戏初始场景用到的资源。
  • resources:存放resources目录下的所有资源以及其依赖资源
    • 优先级: 8
  • main:
    • 优先级: 7
    • 存放所有在构建发布面板的参与构建场景中勾选的场景以及其依赖资源。

Bundle 使用流程

  1. 根据分包名称加载分包。
  • cc.assetManager.loadBundle(bundleName, callback)
  • 这里的加载实际上应该叫:加载分包信息,就是加载config.json文件了解分包信息。

1.

Cocos 启动时资源加载流程

  1. 运行main.js
  2. 读取setting.js文件当前的分包信息
  • setting.js文件记录了游戏中有那些分包,
  1. 加载内置分包
  • 就是加载上面内置分包的config.json
  1. 内置分包加载完成后,加载初始场景资源。

注意:

  1. 有些平台不允许加载远程的脚本文件,例如微信小游戏,在这些平台上,Creator 会将 Asset Bundle 的代码拷贝到 src/scripts 目录下,从而保证正常加载。
  2. 不同 Asset Bundle 中的脚本建议最好不要互相引用,否则可能会导致在运行时找不到对应脚本。如果需要引用某些类或变量,可以将该类和变量暴露在一个你自己的全局命名空间中,从而实现共享。

CocosCreate JS层与原生层交互

参考

JsbBridgeWrapper是什么?

JsbBridgeWrapper 是封装在 JsbBridge 之上的事件派发机制,相对于 JsbBridge 而言它更方便易用。
开发者不需要手动去实现一套消息收发机制就可以进行多事件的触发。但它不具有多线程稳定性或者是 100% 安全。
如果遇到复杂需求场景,仍然建议自己实现对应的事件派发。

JsbBridge使用示例

  • Cocos Creator 3.8.3
游戏端代码示例
1
2
3
4
5
6
7
# 发送事件和相关参数
native.bridge.sendToNative("login", "{account: '123', password: '123'}");

# 监听Native事件
native.bridge.onNative = (arg0: string, arg1: string) => {
console.log("native.bridge.onNative", arg0, arg1);
}

通过sendToNative方法向Native发送消息,通过onNative方法监听Native的消息。一般arg0为事件名称,arg1为事件参数。

Android端代码示例
1
2
3
4
5
6
7
8
9
10
11
import com.cocos.lib.JsbBridge;

JsbBridge.setCallback(new JsbBridge.ICallback() {
@Override
public void onScript(String arg0, String arg1) {
Log.d("JsbBridge", "onScript: " + arg0 + " " + arg1);

//返回数据给游戏端
JsbBridge.sendToScript("onLogin","{code:0,msg:'登录成功'}");
}
});

mysql权限管理

参考

mysql的数据级别

  • 全局:作用于整个mysql服务器,就是你安装的这个mysql服务都有效。
  • 数据库:作用于某个数据库,比如test数据库。
  • 数据库对象:某个数据库中的某个对象,比如某个表、某个视图、某个存储过程等。

权限详细解析

  • SELECT:查询数据,select权限在执行update/delete语句中含有where条件的情况下也是需要的。
  • INSERT:插入数据,执行insert语句的时候需要。
  • UPDATE:更新数据,执行update语句的时候需要。
  • DELETE:删除数据,执行delete语句的时候需要。代表允许删除行数据的权限。
  • DROP:删除数据库、表、视图的权限,包括truncate table命令。
  • CREATE:允许创建新的数据库和表的权限。
  • ALTER:代表允许修改表结构的权限,但必须要求有create和insert权限配合。如果是rename表名,则要求有alter和drop原表, create和insert新表的权限
  • Grant option:允许用户授权给其他用户。重新付给管理员的时候需要加上这个权限。

数据库建表规范

参考

命名规范

  • 基础规则:

    • 禁用保留字: 如desc、range、match、delayed等,请参考MySQL官方保留字。
      正例:表达逻辑删除的字段名is_deleted,1表示删除,0表示未删除。
    • 使用小写字母或数字: 禁止出现数字开头,禁止两个下划线中间只
      出现数字。
      正例:aliyun_admin,rdc_config,level3_name
      反例:AliyunAdmin,rdcConfig,level_3_name
    • 是与否概念: ,必须使用is_xxx的方式命名,数据类型是unsigned tinyint
      ( 1表示是,0表示否)。
  • 表名

    • 不使用复数: 表名应该仅仅表示表里面的实体内容,不应该表示实体数量,对应于DO类名也是单数
      形式,符合表达习惯。
    • 命名规范: 表的命名最好是加上“业务名称_表的作用”。正例:alipay_task / force_project / trade_config
  • 字段名

    • 索引: 主键索引名为pk_字段名;唯一索引名为uk_字段名;普通索引名则为idx_字段名。
      说明:pk_ 即primary key;uk_ 即 unique key;idx_ 即index的简称。

表规范

  • 必备字段: 表必备三字段:id, gmt_create, gmt_modified。
    说明:其中id必为主键,类型为unsigned bigint、单表时自增、步长为1。gmt_create, gmt_modified 的类型均为date_time类型,前者现在时表示主动创建,后者过去分词表示被动更新。