-
Notifications
You must be signed in to change notification settings - Fork 75
/
env.js
74 lines (68 loc) · 2.01 KB
/
env.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
var mergeObject = function(obj1, obj2) {
Object.keys(obj2).forEach(function(key) {
obj1[key] = obj2[key];
});
};
mergeObject(global, require('./models'));
var config = require('config');
global.$config = config;
var async = require('async');
var game = require('./sandbox');
var gameQueue = async.queue(function(task, callback) {
game(task.mapData, task.code1, task.code2, callback);
}, 1);
var jsonpack = require('jsonpack');
var crypto = require('crypto');
var md5 = function(value) {
return crypto.createHash('md5').update(value).digest('hex');
};
global.Game = function(mapId, code1, code2, options, callback) {
if (typeof options === 'function') {
callback = options;
options = null;
}
if (options && options.cache === false) {
Map.find(mapId).done(function(err, map) {
if (err) {
return callback(err);
}
if (!map) {
return callback(new Error('没有找到对应的地图'));
}
gameQueue.push({ mapData: map.parse(), code1: code1, code2: code2 }, callback);
});
return;
}
var code1Md5 = md5(code1);
var code2Md5 = md5(code2);
Result.find({ where: { MapId: mapId, code1: code1Md5, code2: code2Md5 } }).done(function(err, result) {
if (err) {
return callback(err);
}
if (result) {
return callback(null, jsonpack.unpack(result.data), result.data, result);
}
Map.find(mapId).done(function(err, map) {
if (err) {
return callback(err);
}
if (!map) {
return callback(new Error('没有找到对应的地图'));
}
gameQueue.push({ mapData: map.parse(), code1: code1, code2: code2 }, function(err, replay) {
if (err) {
return callback(err);
}
var packedResult = jsonpack.pack(replay);
Result.create({
code1: code1Md5,
code2: code2Md5,
data: packedResult,
MapId: mapId
}).done(function(err, result) {
callback(err, replay, packedResult, result);
});
});
});
});
};