-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwater.js
More file actions
75 lines (68 loc) · 2.72 KB
/
water.js
File metadata and controls
75 lines (68 loc) · 2.72 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
const BOTTLE_HEIGHT = 40
const VISCOSITY = 10
function get_height(water) {
const dot_index = water.style.height.indexOf(".")
if (dot_index < 0) {
return parseInt(water.style.height.slice(0, -2)) * 2
}
return Math.floor(parseInt(water.style.height.slice(0, dot_index) + water.style.height.slice(dot_index+1, -2)) / 5)
}
function add_height(water, amount, transition) {
const height = (get_height(water) || 0) + amount
const initial_style = water.style.height || "0"
water.style.height = Math.floor(height / 2) + "." + (height * 5) % 10 + "em"
if (transition && !(localStorage.getItem("water-disable-transitions") == "true")) {
water.animate({height: [initial_style, water.style.height]}, Math.abs(amount * VISCOSITY))
}
}
function get_bottle_space(bottle) {
let bottle_space = BOTTLE_HEIGHT;
for (const water of bottle.children) {
bottle_space -= get_height(water)
}
return bottle_space
}
function add_water(bottle, color, amount, transition) {
if (bottle.lastChild && bottle.lastChild.style.backgroundColor == color) {
add_height(bottle.lastChild, amount, transition)
return
}
let fluid = document.createElement("div")
fluid.classList.add("water")
fluid.style.backgroundColor = color
add_height(fluid, amount, transition)
bottle.appendChild(fluid)
}
function remove_water(bottle, amount, transition) {
if (amount < get_height(bottle.lastChild)) {
add_height(bottle.lastChild, -amount, transition)
} else {
const water = bottle.lastChild
const rect = water.getBoundingClientRect()
bottle.removeChild(water)
if (transition && !(localStorage.getItem("water-disable-transitions") == "true")) {
const game = document.getElementById("game")
water.classList.add("detached")
if (bottle.children.length == 0) {
water.classList.add("bottom")
}
game.prepend(water)
const game_rect = game.getBoundingClientRect()
water.style.left = rect.x + "px"
water.style.bottom = game_rect.y + game_rect.height - rect.y - rect.height + "px"
water.animate({height: [water.style.height, 0]}, Math.abs(amount * VISCOSITY))
water.animate({transform: ["translateY(0)", "translateY(2.04em)"], easing: "ease"}, 300)
water.style.height = 0
setTimeout(()=>{game.removeChild(water)}, Math.abs(amount * VISCOSITY))
}
}
}
function add_bottle(color) {
const bottle = document.createElement("div")
bottle.classList.add("bottle")
bottle.addEventListener("click", select_bottle)
if (color) {
add_water(bottle, color, BOTTLE_HEIGHT)
}
return bottle
}