-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathUltimateBattleDescriptor.js
124 lines (105 loc) · 2.52 KB
/
UltimateBattleDescriptor.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
'use strict';
import AiDefinition from "./AiDefinition.js";
import Ajv from 'ajv';
import schema from '../schema/ubd-schema-v4.json';
class UltimateBattleDescriptor {
constructor() {
this._version = 4;
this._aiList = [];
this._rngSeed = (new Date()).getTime();
this._teamMode = false;
this._timeLimit = 0;
}
addAiDefinition(ai) {
this._aiList.push(ai);
}
setTeamMode(v) {
this._teamMode = v;
}
getTeamMode() {
return this._teamMode;
}
setRngSeed(seed) {
this._rngSeed = seed;
}
getVersion() {
return this._version;
}
getAiList() {
return this._aiList;
}
setTimeLimit(limit) {
this._timeLimit = limit;
}
getTimeLimit() {
return this._timeLimit;
}
getRngSeed() {
return this._rngSeed;
}
encode() {
let json = {
version: this._version,
rngSeed: this._rngSeed,
teamMode: this._teamMode,
timeLimit: this._timeLimit,
aiList: []
};
let count;
for(let ai of this._aiList) {
count = ai.count || 1;
for(let i=0; i< count; i++) {
json.aiList.push(ai.toJSON());
}
}
let raw = JSON.stringify(json);
return raw;
}
decode(data, unsecureMode) {
let json;
try {
json = JSON.parse(data);
} catch(err) {
throw new Error(`Cannot parse UBD file! ${err}`);
}
if(this._version !=json.version) {
throw new Error(`Version of UBD does not match. Version ${json.version} is not supported. Please convert to version ${this._version}`);
}
this.validateJsonData(json);
this._rngSeed = json.rngSeed;
this._teamMode = json.teamMode;
this._timeLimit = json.timeLimit;
let ai;
for(let aiJson of json.aiList) {
ai = new AiDefinition();
if(!unsecureMode) {
aiJson.useSandbox = true;
aiJson.executionLimit = 100;
aiJson.initData = null;
}
ai.fromJSON(aiJson);
this._aiList.push(ai);
}
}
validateJsonData(json) {
var ajv = new Ajv();
var validate = ajv.compile(schema);
var valid = validate(json);
if (!valid) {
throw new Error("UBD validation failed - " + validate.errors[0].message);
}
}
clone() {
let result = new UltimateBattleDescriptor();
result.setRngSeed(this.getRngSeed());
result.setTeamMode(this.getTeamMode());
let aiList = this.getAiList();
let aiClone;
for(let ai of aiList) {
aiClone = ai.clone();
result.addAiDefinition(aiClone);
}
return result;
}
}
export default UltimateBattleDescriptor;