-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathscript.mjs
More file actions
369 lines (316 loc) · 9.84 KB
/
script.mjs
File metadata and controls
369 lines (316 loc) · 9.84 KB
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
const TRW_VERSION = '0.0.1';
import { DynamicElement } from './percentTemplate.mjs';
import { statePotentialUpdate } from './updateCode.mjs';
/**
* @typedef WeaponData
* @property {String} name
* @property {String} img
*/
let data = {};
/**
* Resets the state of the run
*/
function stateReset() {
const rstState = {
terrariaVersion: data.terrariaVersion,
trwVersion: TRW_VERSION,
currentStage: 0,
weaponBlacklist: {},
selectedWeapon: null,
enableStageClearPreviousWeapons: true,
sortWeapons: 'availabilityAndName',
openWeaponList: false
};
return rstState;
}
let state = stateReset();
function toggleStageClear() {
state.enableStageClearPreviousWeapons = !state.enableStageClearPreviousWeapons;
stateChanged();
}
function stateChanged() {
saveToLocal();
updateElements();
}
const currentStage = new DynamicElement();
const availWeapons = new DynamicElement();
const optWeaponList = new DynamicElement();
const optStageClear = new DynamicElement();
const randomWeaponPrompt = Object.assign(
new DynamicElement(null, {}, true),
{
/** @type {WeaponData} */
current: null
}
);
const selectedWeapon = new DynamicElement(null, {}, true);
const weaponList = {
/** @type {HTMLDivElement} */
element: null
}
function lexOrder(a1, a2) {
const l = Math.min(a1.length, a2.length);
for(let i = 0; i < l; ++i) {
if (a1[i] < a2[i]) {
return -1;
} else if (a1[i] > a2[i]) {
return 1;
}
}
if (a1.length < a2.length) {
return -1;
} else if (a1.length > a2.length) {
return 1;
} else {
return 0;
}
}
const SORTMODES = {
'name': {
label: 'Name',
cmpFn: (w1, w2) => lexOrder([w1.name], [w2.name])
},
'availability': {
label: 'Availability',
cmpFn: (w1, w2) => lexOrder([!!state.weaponBlacklist[w1.name]], [!!state.weaponBlacklist[w2.name]])
},
'availabilityAndName': {
label: 'Availability and Name',
cmpFn: (w1, w2) => lexOrder([!!state.weaponBlacklist[w1.name], w1.name], [!!state.weaponBlacklist[w2.name], w2.name])
}
};
/**
* Gets all available weapons at the specified stage with the specified blacklist
* @param {Number} [stageI] - The stage's index
* @param {Object<String, Boolean>} [blacklist] - The weapons' blacklist
* @returns {WeaponData[]} An array that contains all available weapons
*/
function getAvailableWeapons(stageI = 0, blacklist = state.weaponBlacklist) {
let weapons = [];
/** @type {String[]} */
const stages = data.stages;
stageI = Math.min(Math.max(stageI, 0), stages.length);
for (let i = 0; i <= stageI; i++) {
if (state.enableStageClearPreviousWeapons && stages[i].clearPreviousWeapons) {
weapons = [];
}
weapons.push(...stages[i].weapons);
}
return weapons.filter(w => !blacklist[w.name]);
}
/**
* Returns the name of the specified stage
* @param {Number} [stageI] - The stage's index
* @returns {String} The name of the specified stage
*/
function getStageName(stageI = 0) {
return data.stages[Math.min(Math.max(stageI, 0), data.stages.length - 1)].name;
}
/**
* Picks a random weapon that is available at the specified stage with the specified blacklist
* @param {Number} [stageI] - The stage's index
* @param {Object<String, Boolean>} [blacklist] - The weapons' blacklist
* @returns {WeaponData} The name of a randomly picked weapon
*/
function pickRandomWeapon(stageI = 0, blacklist = state.weaponBlacklist) {
const availWeapons = getAvailableWeapons(stageI, blacklist);
return availWeapons[Math.floor(Math.random() * availWeapons.length)];
}
/**
* Goes to the next stage
*/
function nextStage() {
if (state.currentStage < data.stages.length - 1) {
++state.currentStage;
stateChanged();
}
}
/**
* Goes back to the previous stage
*/
function previousStage() {
if (state.currentStage > 0) {
--state.currentStage;
stateChanged();
}
}
/**
* Creates a new HTML string from the specified weapon
* @param {WeaponData} weapon - The weapon to create the HTML string from
* @returns {String} The HTML for the specified weapon
*/
function createWeaponHTML(weapon) {
if (weapon === null || weapon === undefined) {
return "None";
}
return `<img class="weaponImage" src="${weapon.img === undefined ? "" : weapon.img}"> ${weapon.name}`;
}
/**
* Called when "getRandomWeapon" button is pressed
*/
function getRandomWeaponPressed() {
randomWeaponPrompt.parent.classList.remove("hidden");
const selWeapon = pickRandomWeapon(state.currentStage);
randomWeaponPrompt.current = selWeapon;
randomWeaponPrompt.update({ SELECTED_WEAPON: createWeaponHTML(selWeapon) });
}
/**
* Populates the list of weapons and creates all needed elements
*/
function populateWeaponList() {
weaponList.element.classList.toggle("hidden", !state.openWeaponList);
if (!state.openWeaponList) {
return;
}
while (weaponList.element.lastElementChild !== null) {
weaponList.element.removeChild(weaponList.element.lastElementChild);
}
const allWeapons = getAvailableWeapons(state.currentStage, { });
allWeapons.sort(SORTMODES[state.sortWeapons].cmpFn);
for (const weapon of allWeapons) {
const name = weapon.name;
const div = document.createElement("div");
const button = document.createElement("button");
button.id = `blacklistButton_${name}`;
button.classList.add("defaultButton", "weaponListButton", "left");
button.innerText = state.weaponBlacklist[name] ? "W" : "B";
const label = document.createElement("label");
label.innerHTML = `<span style="color: ${state.selectedWeapon !== null && state.selectedWeapon.name === name ? "blue" : state.weaponBlacklist[name] ? "red" : "white"}">${createWeaponHTML(weapon)}</span>`;
label.classList.add("defaultText", "weaponListLabel");
label.htmlFor = button.id;
button.addEventListener("click", (ev) => {
state.weaponBlacklist[name] = !state.weaponBlacklist[name];
stateChanged();
});
div.appendChild(button);
div.appendChild(label);
weaponList.element.appendChild(div);
};
}
/**
* Updates all elements on the page with the right information
*/
function updateElements() {
currentStage.update({ CURRENT_STAGE: `${getStageName(state.currentStage)} (${state.currentStage + 1}/${data.stages.length})` });
selectedWeapon.update({ CURRENT_WEAPON: createWeaponHTML(state.selectedWeapon) });
availWeapons.update({ WEAPON_COUNT: getAvailableWeapons(state.currentStage, state.weaponBlacklist).length });
optWeaponList.update({ ACTION: state.openWeaponList ? "Close" : "Open" });
optStageClear.update({ ACTION: state.enableStageClearPreviousWeapons ? "Disable" : "Enable" });
populateWeaponList();
}
/**
* Toggles weapon list's visibility
*/
function toggleWeaponList() {
state.openWeaponList = !state.openWeaponList;
stateChanged();
}
/**
* Accepts or rejects the currently random picked weapon
* @param {Boolean} accept - Whether or not to accept the weapon
* @param {Boolean} addToBlacklist - Whether or not to add the weapon to the blacklist
*/
function confirmRandomWeapon(accept = true, addToBlacklist = true) {
randomWeaponPrompt.parent.classList.add("hidden");
state.selectedWeapon = accept ? randomWeaponPrompt.current : null;
if (addToBlacklist) {
state.weaponBlacklist[randomWeaponPrompt.current.name] = true;
}
stateChanged();
}
function stateSave() {
return JSON.stringify(state);
}
/**
* Saves the current state to localStorage
*/
function saveToLocal() {
localStorage.clear(); // Needed?
localStorage.setItem("state", stateSave());
}
/**
* Saves the current state to localStorage
*/
function saveToFile() {
const blob = new Blob([stateSave()], {
type: "application/json"
});
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = "TerrariaRandomWeapon.save";
//document.body.appendChild(a);
a.click();
//document.body.removeChild(a);
URL.revokeObjectURL(a.href);
}
function stateLoad(str) {
const otherState = statePotentialUpdate(JSON.parse(str) || {});
state = Object.assign(
stateReset(),
otherState
);
stateChanged(); // Update datastore I guess???
}
/**
* Loads a saved state from localStorage
*/
function loadFromLocal() {
stateLoad(localStorage.getItem("state"));
}
function loadFromFile() {
const i = document.createElement("input");
i.type = "file";
i.accept = ".save"; //"application/json";
i.addEventListener("change", ev => {
const file = ev.target.files[0];
const reader = new FileReader();
// here we tell the reader what to do when it's done reading...
reader.addEventListener("load", readerEvent => {
stateLoad(readerEvent.target.result);
});
reader.readAsText(file, "UTF-8");
});
//document.body.appendChild(i);
i.click();
//document.body.removeChild(i);
}
window.addEventListener("load", async () => {
currentStage.element = document.getElementById("currentStage");
availWeapons.element = document.getElementById("availWeapons");
randomWeaponPrompt.element = document.getElementById("randomlySelectedWeapon");
selectedWeapon.element = document.getElementById("selectedWeapon");
weaponList.element = document.getElementById("weaponList");
optWeaponList.element = document.getElementById("optWeaponList");
optStageClear.element = document.getElementById("optStageClear");
data = await (await fetch("data.json")).json();
new DynamicElement(
document.getElementById("credits"),
{
DATA_PROVIDER: data.$meta.author,
TRW_VERSION: TRW_VERSION,
TERRARIA_VERSION: data.terrariaVersion
}
);
/*
document.body.onbeforeunload = (ev) => {
// Show unsaved state
if (isDirty) {
ev.preventDefault();
ev.returnValue = '';
return '';
}
};
*/
loadFromLocal();
// Exported functions for the page
window.trw = {
getRandomWeaponPressed,
nextStage,
previousStage,
toggleWeaponList,
toggleStageClear,
confirmRandomWeapon,
saveToFile,
loadFromFile,
};
});