forked from GeNoSeS/Multiplayer-Game
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
339 lines (295 loc) · 8.84 KB
/
app.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
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
const mapData = {
minX: 1,
maxX: 14,
minY: 4,
maxY: 12,
blockedSpaces: {
"7x4": true,
"1x11": true,
"12x10": true,
"4x7": true,
"5x7": true,
"6x7": true,
"8x6": true,
"9x6": true,
"10x6": true,
"7x9": true,
"8x9": true,
"9x9": true,
},
};
// Options for Player Colors... these are in the same order as our sprite sheet
const playerColors = ["blue", "red", "orange", "yellow", "green", "purple"];
//Misc Helpers
function randomFromArray(array) {
return array[Math.floor(Math.random() * array.length)];
}
function getKeyString(x, y) {
return `${x}x${y}`;
}
function createName() {
const prefix = randomFromArray([
"COOL",
"SUPER",
"HIP",
"SMUG",
"COOL",
"SILKY",
"GOOD",
"SAFE",
"DEAR",
"DAMP",
"WARM",
"RICH",
"LONG",
"DARK",
"SOFT",
"BUFF",
"DOPE",
]);
const animal = randomFromArray([
"BEAR",
"DOG",
"CAT",
"FOX",
"LAMB",
"LION",
"BOAR",
"GOAT",
"VOLE",
"SEAL",
"PUMA",
"MULE",
"BULL",
"BIRD",
"BUG",
]);
return `${prefix} ${animal}`;
}
function isSolid(x,y) {
const blockedNextSpace = mapData.blockedSpaces[getKeyString(x, y)];
return (
blockedNextSpace ||
x >= mapData.maxX ||
x < mapData.minX ||
y >= mapData.maxY ||
y < mapData.minY
)
}
function getRandomSafeSpot() {
//We don't look things up by key here, so just return an x/y
return randomFromArray([
{ x: 1, y: 4 },
{ x: 2, y: 4 },
{ x: 1, y: 5 },
{ x: 2, y: 6 },
{ x: 2, y: 8 },
{ x: 2, y: 9 },
{ x: 4, y: 8 },
{ x: 5, y: 5 },
{ x: 5, y: 8 },
{ x: 5, y: 10 },
{ x: 5, y: 11 },
{ x: 11, y: 7 },
{ x: 12, y: 7 },
{ x: 13, y: 7 },
{ x: 13, y: 6 },
{ x: 13, y: 8 },
{ x: 7, y: 6 },
{ x: 7, y: 7 },
{ x: 7, y: 8 },
{ x: 8, y: 8 },
{ x: 10, y: 8 },
{ x: 8, y: 8 },
{ x: 11, y: 4 },
]);
}
(function () {
let playerId;
let playerRef;
let players = {};
let playerElements = {};
let coins = {};
let coinElements = {};
const gameContainer = document.querySelector(".game-container");
const playerNameInput = document.querySelector("#player-name");
const playerColorButton = document.querySelector("#player-color");
function placeCoin() {
const { x, y } = getRandomSafeSpot();
const coinRef = firebase.database().ref(`coins/${getKeyString(x, y)}`);
coinRef.set({
x,
y,
})
const coinTimeouts = [2000, 3000, 4000, 5000];
setTimeout(() => {
placeCoin();
}, randomFromArray(coinTimeouts));
}
function attemptGrabCoin(x, y) {
const key = getKeyString(x, y);
if (coins[key]) {
// Remove this key from data, then uptick Player's coin count
firebase.database().ref(`coins/${key}`).remove();
playerRef.update({
coins: players[playerId].coins + 1,
})
}
}
function handleArrowPress(xChange=0, yChange=0) {
const newX = players[playerId].x + xChange;
const newY = players[playerId].y + yChange;
if (!isSolid(newX, newY)) {
//move to the next space
players[playerId].x = newX;
players[playerId].y = newY;
if (xChange === 1) {
players[playerId].direction = "right";
}
if (xChange === -1) {
players[playerId].direction = "left";
}
playerRef.set(players[playerId]);
attemptGrabCoin(newX, newY);
}
}
function initGame() {
new KeyPressListener("ArrowUp", () => handleArrowPress(0, -1))
new KeyPressListener("ArrowDown", () => handleArrowPress(0, 1))
new KeyPressListener("ArrowLeft", () => handleArrowPress(-1, 0))
new KeyPressListener("ArrowRight", () => handleArrowPress(1, 0))
const allPlayersRef = firebase.database().ref(`players`);
const allCoinsRef = firebase.database().ref(`coins`);
allPlayersRef.on("value", (snapshot) => {
//Fires whenever a change occurs
players = snapshot.val() || {};
Object.keys(players).forEach((key) => {
const characterState = players[key];
let el = playerElements[key];
// Now update the DOM
el.querySelector(".Character_name").innerText = characterState.name;
el.querySelector(".Character_coins").innerText = characterState.coins;
el.setAttribute("data-color", characterState.color);
el.setAttribute("data-direction", characterState.direction);
const left = 16 * characterState.x + "px";
const top = 16 * characterState.y - 4 + "px";
el.style.transform = `translate3d(${left}, ${top}, 0)`;
})
})
allPlayersRef.on("child_added", (snapshot) => {
//Fires whenever a new node is added the tree
const addedPlayer = snapshot.val();
const characterElement = document.createElement("div");
characterElement.classList.add("Character", "grid-cell");
if (addedPlayer.id === playerId) {
characterElement.classList.add("you");
}
characterElement.innerHTML = (`
<div class="Character_shadow grid-cell"></div>
<div class="Character_sprite grid-cell"></div>
<div class="Character_name-container">
<span class="Character_name"></span>
<span class="Character_coins">0</span>
</div>
<div class="Character_you-arrow"></div>
`);
playerElements[addedPlayer.id] = characterElement;
//Fill in some initial state
characterElement.querySelector(".Character_name").innerText = addedPlayer.name;
characterElement.querySelector(".Character_coins").innerText = addedPlayer.coins;
characterElement.setAttribute("data-color", addedPlayer.color);
characterElement.setAttribute("data-direction", addedPlayer.direction);
const left = 16 * addedPlayer.x + "px";
const top = 16 * addedPlayer.y - 4 + "px";
characterElement.style.transform = `translate3d(${left}, ${top}, 0)`;
gameContainer.appendChild(characterElement);
})
//Remove character DOM element after they leave
allPlayersRef.on("child_removed", (snapshot) => {
const removedKey = snapshot.val().id;
gameContainer.removeChild(playerElements[removedKey]);
delete playerElements[removedKey];
})
//New - not in the video!
//This block will remove coins from local state when Firebase `coins` value updates
allCoinsRef.on("value", (snapshot) => {
coins = snapshot.val() || {};
});
//
allCoinsRef.on("child_added", (snapshot) => {
const coin = snapshot.val();
const key = getKeyString(coin.x, coin.y);
coins[key] = true;
// Create the DOM Element
const coinElement = document.createElement("div");
coinElement.classList.add("Coin", "grid-cell");
coinElement.innerHTML = `
<div class="Coin_shadow grid-cell"></div>
<div class="Coin_sprite grid-cell"></div>
`;
// Position the Element
const left = 16 * coin.x + "px";
const top = 16 * coin.y - 4 + "px";
coinElement.style.transform = `translate3d(${left}, ${top}, 0)`;
// Keep a reference for removal later and add to DOM
coinElements[key] = coinElement;
gameContainer.appendChild(coinElement);
})
allCoinsRef.on("child_removed", (snapshot) => {
const {x,y} = snapshot.val();
const keyToRemove = getKeyString(x,y);
gameContainer.removeChild( coinElements[keyToRemove] );
delete coinElements[keyToRemove];
})
//Updates player name with text input
playerNameInput.addEventListener("change", (e) => {
const newName = e.target.value || createName();
playerNameInput.value = newName;
playerRef.update({
name: newName
})
})
//Update player color on button click
playerColorButton.addEventListener("click", () => {
const mySkinIndex = playerColors.indexOf(players[playerId].color);
const nextColor = playerColors[mySkinIndex + 1] || playerColors[0];
playerRef.update({
color: nextColor
})
})
//Place my first coin
placeCoin();
}
firebase.auth().onAuthStateChanged((user) => {
console.log(user)
if (user) {
//You're logged in!
playerId = user.uid;
playerRef = firebase.database().ref(`players/${playerId}`);
const name = createName();
playerNameInput.value = name;
const {x, y} = getRandomSafeSpot();
playerRef.set({
id: playerId,
name,
direction: "right",
color: randomFromArray(playerColors),
x,
y,
coins: 0,
})
//Remove me from Firebase when I diconnect
playerRef.onDisconnect().remove();
//Begin the game now that we are signed in
initGame();
} else {
//You're logged out.
}
})
firebase.auth().signInAnonymously().catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
// ...
console.log(errorCode, errorMessage);
});
})();