-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDOMObject.js
103 lines (91 loc) · 2.62 KB
/
DOMObject.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
/**
* A class that represents a
*/
class DOMObject {
speed = 100;
element;
constructor(domId, height, width) {
this.domId = domId;
this.height = height;
this.width = width;
// document.addEventListener("DOMContentLoaded", () => {
window.onload = () => {
this.element = document.getElementById(domId);
};
}
/**
* Set width of player brick
* @param {string} width in pixels
*/
setWidth(width) {
this.width = width;
this.element.style.width = width;
}
/**
* Height of the player brick
* @param {string} height in pixels/%/other
*/
setHeight(height) {
this.height = height;
this.element.style.height = width;
}
/**
* Retrieves the current element created
* @returns dom element
*/
getDomElement() {
return document.getElementById(this.domId);
}
/**
* Set the speed in which the players brick moves up/down
* @param {number} speed in pixels per brick movement
*/
setSpeed(speed) {
this.speed = speed;
}
getSpeed() {
return this.speed;
}
/**
* Moves player with index up an MOVE_PIXEL_COUNT amount of pixels
* @param {number} index player index: 0 for player 1 and index 1 for player 2
* @returns
*/
moveUp(index) {
let playerBrick = document.getElementsByClassName("brick")[index];
const currentPosition = parseInt(window.getComputedStyle(playerBrick).top);
if (currentPosition <= 0) {
return;
}
if (currentPosition - MOVE_PIXEL_COUNT <= 0) {
playerBrick.style.top = 0 + "px";
return;
}
// - because in the HTML coordinate system + is downwards and - is upwards
requestAnimationFrame(() => {
playerBrick.style.top = currentPosition - MOVE_PIXEL_COUNT + "px";
});
}
/**
* Moves the player brick element down a number of pixels
* @param {number} index 0 for player 1 and index 1 for player 2
* @returns void when movement should be cancelled
*/
moveDown(index) {
const playerBrick = document.getElementsByClassName("brick")[index];
const currentPosition = parseInt(window.getComputedStyle(playerBrick).top);
const gameCanvas = playerBrick.parentElement; // Assuming the gameCanvas is the direct parent
if (
currentPosition + playerBrick.clientHeight + MOVE_PIXEL_COUNT >
gameCanvas.clientHeight
) {
playerBrick.style.top =
gameCanvas.clientHeight - playerBrick.clientHeight + "px";
return;
}
// + because in the HTML coordinate system + is downwards and - is upwards
requestAnimationFrame(() => {
playerBrick.style.top = currentPosition + MOVE_PIXEL_COUNT + "px";
});
}
}