-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfuncs.js
More file actions
399 lines (375 loc) · 11.6 KB
/
funcs.js
File metadata and controls
399 lines (375 loc) · 11.6 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
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
//start general
class Vec {
constructor(x, y) {
this.x = x;
(y == undefined) ? this.y = x : this.y = y;
}
plus(another) {
this.x = this.x + another.x; this.y = this.y + another.y;
}
factor(n) {
return new Vec(this.x * n, this.y * n)
}
}
function setPosition(sprite, where, str = '%') {
sprite.style.left = where.x + str; sprite.style.top = where.y + str;
}
function setRotation(sprite, angle) {
sprite.style.transform = `rotate(${angle}deg)`;
}
function setBackground(sprite, src) {
sprite.style.backgroundImage = `url(${src})`
}
function touching(rect1, rect2) {
if (rect1.right > rect2.left
&& rect1.left < rect2.right) {
// rect1 is intersecting rect2 on x axis
// But they could be at different heights
if (rect1.top < rect2.bottom
&& rect1.bottom > rect2.top) {
// rect1 is intersecting rect2 on y axis as well
// Collision detected
return true;
}
}; return false;
};
function d(dom) {
let f = parseFloat;
return new DOMRect(f(dom.style.left), f(dom.style.top)
, f(dom.style.width), f(dom.style.height))
};
/*for shoot before but can be used for others*/function restart(msg, run = reset, styles, prompt = 'restart') {
//this can also be used for pausing
let msgbox = make();
msgbox.id = 'restarter';
msgbox.innerHTML = msg;
document.body.appendChild(msgbox)
let button = make('button')
button.textContent = prompt; msgbox.appendChild(button)
button.before(' click button to restart: ')
if (styles) manyStyles(msg, styles)
button.onclick = run
button.addEventListener('click', () => { msgbox.remove() })
}
/*this one too*/function loadSounds(folder = '../../Vs Projects/sound/Wav/', _ = '.wav',
sources = ['mouse_click', 'monster_minigun', 'shotgun',
'monster_hit', 'mouse_error', 'explosion', 'male_death',
'bomb_activate', 'energy_on', 'big_explosion', 'Rip']) {
sound = [];
for (let i = 0; i < sources.length; i++) {
sound[i] = new Audio;
sound[i].src = folder + sources[i] + _
}
}
function sameChild(first, second) {
for (let i = 0; i < first.length; i++) {
if (first[i] == second[i]) return true
}
return false
}
function sameArray(first, second) {
if (first.length != second.length) return false;
for (let i = 0; i < first.length; i++) {
if (first[i] != second[i]) return false;
}
return true
}
function showAndHide(text = 'Ouch', time) {
//do that it will check if info exists, create if it doesn't and style it;
info.textContent = text;
info.style.opacity = 1;
setTimeout(() => info.style.opacity = 0, time)
}
function repeat(n, f) {
for (let i = 0; i < n; i++) {
f()
}
}
function identical(A1, A2) {
for (let i of A1) {
if (A2.indexOf(i) == -1) return false
}
return true;
}
function manyStyles(node, a = {}) {
for (let x in node.style) {
if (x in a) {
node.style[x] = a[x];
}
}
}
function anyStyles(node, a = {}) {
for (let x in a) {
node.style.setProperty(x, a[x])
}
}
/*was for matrix.html*/function stopSign() {
if (['-', '+', ''].includes(event.key)) {
event.preventDefault()
}
}
/*was for matrix.html*/function changeSign() {
event.target.textContent = (event.target.textContent == '+') ? '-' : '+'
}
function sum(array) {
let s = 0;
array.forEach(i => s += i);
return s;
}
function noSound(where, pos = 'absolute') {
let mute = make('input');
mute.id = 'mute'; mute.type = 'checkbox';
where.appendChild(mute); mute.style.position = pos;
mute.onchange = () => sound.forEach(i => i.volume = mute.checked + 0);
mute.before('Play sound '); mute.checked = true;
}
function startAgainWithoutRefresh() { }
function collapser() { }
//for phone
touch = {
'↖': [0, 3],
'↑': 0,
'↗': [0, 1],
'←': 3,
'→': 1,
'↙': [2, 3],
'↓': 2,
'↘': [1, 2],
}
tX = 0; tY = 0;
pad = window['pad']
//i did it for block breaker
function goToScreen(screenName, t = '', container = document.body, selected = window['selected']) {
Array.from(container.children).forEach(i => {
let det = (i.id == screenName);
i.selected = det;
if (det) {
i.incase = t;
i.style.display = '';
i.back = selected;
i.selected = det;
selected = i;
// return
} else { i.style.display = 'none' }
})
}
function position(div, x, y, _ = 'px') {
div.style.transform = `translate(${x + _}, ${y + _})`
}
function copy(array, fill) {
let ans = [];
array.forEach(i => {
if (i instanceof Array) {
let j = copy(i, fill);
ans.push(j);
} else { ans.push(fill ? fill : i) }
});
return ans;
}
function clearArray(array) {
array.forEach(i => {
if (i instanceof Array) {
clearArray(i);
}
});
array.length = 0;
}
function make(name = "div", attrs = {}) {
const dom = document.createElement(name);
for (const attr in attrs) dom[attr] = attrs[attr];
return dom;
}
let makeSVG = (name) => document.createElementNS('http://www.w3.org/2000/svg', name)
, get = (id) => document.getElementById(id)
, getE = (selector, value) => document.querySelector(`[${selector}=${value}]`)
, getS = (query) => document.querySelector(query)
, getAll = (query) => [...document.querySelectorAll(query)]
, identify = () => getAll('[id]').forEach(i => window[i.id] = i)
, add = (what, to = document.body) => to.appendChild(what)
, bx = (who) => who.getBoundingClientRect()
, show = (what) => what.style.display = ""
, hide = (what) => what.style.display = "none"
, domAt = (x, y) => document.elementFromPoint(x, y)
, reclass = (dom, className, remove = 0) => dom.classList[remove ? "remove" : "add"](className)
, hasClass = (dom, className) => dom.classList.contains(className);
// still DOM functions
function switchScreen(screenID) {
getAll("body>div").forEach(div => { if (div.id) div.style.display = "none" });
get(screenID).style.display = "";
};
// events framework
function configureEvents(events) {
for (let type in events) {
for (let handler of events[type]) {
window.addEventListener(type, handler);
}
}
}
// initialize the loading element, that blocks the screen and all
function loader() {
let loading;
(loading = make()).id = "LOADING";
showLoading = (text = "") => add(loading).style.setProperty("--content", `"${text}"`);
hideLoading = () => loading.remove();
isPageLoading = () => loading.isConnected;
const N = 10;
for (let n = 0; n < N; n++) {
let c;
(c = make()).id = 'c' + n;
c.style.animationDelay = n / N + 's';
// use other numbers apart from .1 to see effects;
// will have to change animation-duration and dimensions too
loading.append(c);
};
};
// math
// not inclusive of the last one (a is the little one)
function randBtw(a, b) {
return a + parseInt((b - a) * Math.random());
};
// others for data handling
let choice = (array) => array[randBtw(0, array.length)]
, jsonStr = (obj) => JSON.stringify(obj)
, jsonObj = (str) => JSON.parse(str)
, copyObj = (obj) => jsonObj(jsonStr(obj))
, logTurn = (obj) => (console.log(obj), obj)
, transfer = (object, from, to) => to.push(from.splice(from.indexOf(object), 1)[0])
, remove = (what, from) => from.splice(from.indexOf(what), 1)
, local = (item, value) => value ? localStorage.setItem(item, value) : localStorage[item];
function populate(n, val = "") {
let result = [];
for (let i = 0; i < n; i++) {
result.push(val);
};
return result;
}
// Fetch API POST usage
function getFromServer(url, body) {
return fetch(url, {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRFToken': getS(`[name=csrfmiddlewaretoken]`).value
},
body: JSON.stringify(body)
});
};
// speechSynthesis
// get voice from voice name
function getVoice(name) {
return speechSynthesis.getVoices().find(i => i.name == name);
};
function isPhone() {
return navigator.userAgentData.mobile;
}
//start math
function randP1() {
n = Math.random();
while (n < 0.5) n *= 2;
return n;
}
function random(n) {
return parseInt(n * Math.random())
}
function sin(deg) {
deg = deg * Math.PI / 180;
return Math.sin(deg);
}
function cos(deg) {
deg = deg * Math.PI / 180;
return Math.cos(deg);
}
tan = (x) => sin(x) / cos(x);
atan = (y, x = 1) => Math.atan2(y, x) * (180 / Math.PI);
['asin', 'acos'].forEach(a => window[a] = (x) => Math[a](x) * (180 / Math.PI));
//end math
//end general
//start shoot.html
function setSize(sprite, size, _ = '%') {
sprite.style.width = size.x + _; sprite.style.height = size.y + _;
}
function handleInputsImproved(player) {
addEventListener('keydown', event => {
key = event.key;
if (player.controls.slice(0, 4).includes(key)) {
player.dirs[player.controls.indexOf(key)] = .2;
}
else if (player.controls[5].includes(key)) {
let add = 5 * (player.controls[5].indexOf(key) - 1);
player.rotate = false;
player.angle += add;
setRotation(player.you, player.angle);
}
})
addEventListener('keyup', event => {
key = event.key;
if (player.controls.slice(0, 4).includes(key)) {
player.dirs[player.controls.indexOf(key)] = 0;
}
else if (player.controls[5].includes(key)) {
player.rotate = true;
}
else if (player.controls[4].includes(key)) {
player.shoot();
}
})
}
function modeDif() {
let mode, difficulty, level;
for (let button of getAll("[name='mode']")) {
if (button.checked) { mode = button.value; break }
}
difficulty = getS("[type='range']").value;
level = { mode: mode, difficulty: difficulty }
return level;
}
function loadKeys(player, name) {
player.controls = []
player.you.style.background = player.hold = document.getElementById(name).children[7].children[0].value;
let source = document.getElementById(name).children;
for (let i = 0; i < 5; i++) {
player.controls[i] = source[i].value ? source[i].value : source[i].className;
}
player.controls[5] = (source[6].value + source[5].value) ? source[6].value + ' ' + source[5].value : source[6].className + ' ' + source[5].className;
handleInputsImproved(player);
}
function loadThem(n, target) {
let enemies = []
for (let i = 0; i < n; i++) {
enemies.push(new Enemy(new Vec(random(100), random(100)), 0));
}
for (let i = 0; i < enemies.length; i++) {
if (i % 2 == 0) {
enemies[i].target = target;
enemies[i].yourHead.style.background = target.you.style.background;
}
}
return enemies;
}
function load() {
location.reload();
}
function refresh(what) {
let boom = endOfGame(); clearInterval(gameOver);
setTimeout(() => {
alert(what); document.location.href = document.location.href
}, boom)
}
function endOfGame() {
sound[7].play();
setTimeout(() => {
sound[9].play();
}, sound[7].duration * 1000)
return (sound[7].duration + sound[9].duration) * 1000;
}
//end shoot.html
//start combat
function drawBox(pic) {
let newBox = make();
newBox.style.width = newBox.style.height = `${scale}`;
setBackground(newBox, `../../images/${pic}.png`);
container.appendChild(newBox);
return newBox;
}
//end combat