1 let playField = {
2 width: 300,
3 height: 200
4 };
5 let score = 0;
6 let maxScore = 0;
7 let bubbles = [];
8 let interval;
9 let button = document.getElementById("start");
10 let scoreDiv = document.getElementById("score");
11 let field = document.getElementById("field");
12
13 function startGame()
14 {
15 showButton(false);
16
17 let time = 1000;
18 interval = setInterval(createBubble, time);
19
20 score = 0;
21 maxScore = 0;
22 updateScore();
23 animate();
24 }
25
26 function showButton(show)
27 {
28
29 if (show)
30 {
31 button.style.display = "block";
32 }
33 else
34 {
35 button.style.display = "none";
36 }
37 }
38
39 function createBubble()
40 {
41 let bubble = document.createElement("div");
42 field.appendChild(bubble);
43
44 bubble.classList.add("bubble");
45 bubble.onclick = function ()
46 {
47 pop(bubble);
48 };
49
50 let colors = ["midnightblue", "darkred", "orange", "yellow", "green", "cornsilk", "magenta"];
51 let index = Math.floor(Math.random() * colors.length);
52 bubble.style.backgroundColor = colors[index];
53
54 let size = Math.floor(Math.random() * 15) + 25;
55 bubble.style.width = size + "px";
56 bubble.style.height = size + "px";
57
58 let speed = Math.floor(Math.random() * 2) + 1;
59 bubble.speed = speed;
60
61 let playWidth = playField.width - size;
62 let left = Math.floor(Math.random() * playWidth);
63 let top = playField.height;
64 bubble.style.left = left + "px";
65 bubble.style.top = top + "px";
66
67 bubble.index = bubbles.length;
68 bubbles.push(bubble);
69
70 maxScore++;
71 updateScore();
72 }
73
74 function pop(bubble)
75 {
76
77 bubbles[bubble.index] = null;
78 bubble.parentNode.removeChild(bubble);
79 score++;
80 updateScore();
81 }
82
83 function updateScore()
84 {
85
86 let text = "Bubbles Popped: " + score;
87 text += "<br>Total Bubbles: " + maxScore;
88 scoreDiv.innerHTML = text;
89 }
90
91 function animate()
92 {
93 let hitTop = false;
94 for (let i = 0; i < bubbles.length; i++)
95 {
96 let bubble = bubbles[i];
97 if (!bubble)
98 {
99 continue;
100 }
101 let top = parseInt(bubble.style.top);
102 top -= bubble.speed;
103
104 bubble.style.top = top + "px";
105
106 if (top <= 0)
107 {
108 hitTop = true;
109 break;
110 }
111 }
112 if (hitTop)
113 {
114 gameOver();
115 }
116 else
117 {
118 requestAnimationFrame(animate);
119 }
120 }
121
122 function gameOver()
123 {
124 showButton(true);
125 removeBubbles();
126 clearInterval(interval);
127 updateScore();
128 scoreDiv.innerHTML += "<h1>Game Over</h1>";
129 }
130
131 function removeBubbles()
132 {
133 for (let i = 0; i < bubbles.length; i++)
134 {
135 let bubble = bubbles[i];
136 if (!bubble)
137 {
138 continue;
139 }
140 bubble.parentNode.removeChild(bubble);
141 }
142 bubbles = [];
143 }
144
145