-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
main.js
178 lines (155 loc) · 5.15 KB
/
main.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
/**
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
/**
* @fileoverview Tic-Tac-Toe, using the Firebase API
*/
/**
* @param gameKey - a unique key for this game.
* @param me - my user id.
* @param token - secure token passed from the server
* @param channelId - id of the 'channel' we'll be listening to
*/
function initGame(gameKey, me, token, channelId, initialMessage) {
var state = {
gameKey: gameKey,
me: me
};
// This is our Firebase realtime DB path that we'll listen to for updates
// We'll initialize this later in openChannel()
var channel = null;
/**
* Updates the displayed game board.
*/
function updateGame(newState) {
$.extend(state, newState);
$('.cell').each(function(i) {
var square = $(this);
var value = state.board[i];
square.html(' ' === value ? '' : value);
if (state.winner && state.winningBoard) {
if (state.winningBoard[i] === value) {
if (state.winner === state.me) {
square.css('background', 'green');
} else {
square.css('background', 'red');
}
} else {
square.css('background', '');
}
}
});
var displayArea = $('#display-area');
if (!state.userO) {
displayArea[0].className = 'waiting';
} else if (state.winner === state.me) {
displayArea[0].className = 'won';
} else if (state.winner) {
displayArea[0].className = 'lost';
} else if (isMyMove()) {
displayArea[0].className = 'your-move';
} else {
displayArea[0].className = 'their-move';
}
}
function isMyMove() {
return !state.winner && (state.moveX === (state.userX === state.me));
}
function myPiece() {
return state.userX === state.me ? 'X' : 'O';
}
/**
* Send the user's latest move back to the server
*/
function moveInSquare(e) {
var id = $(e.currentTarget).index();
if (isMyMove() && state.board[id] === ' ') {
$.post('/move', {cell: id});
}
}
/**
* This method lets the server know that the user has opened the channel
* After this method is called, the server may begin to send updates
*/
function onOpened() {
$.post('/opened');
}
/**
* This deletes the data associated with the Firebase path
* it is critical that this data be deleted since it costs money
*/
function deleteChannel() {
$.post('/delete');
}
/**
* This method is called every time an event is fired from Firebase
* it updates the entire game state and checks for a winner
* if a player has won the game, this function calls the server to delete
* the data stored in Firebase
*/
function onMessage(newState) {
updateGame(newState);
// now check to see if there is a winner
if (channel && state.winner && state.winningBoard) {
channel.off(); //stop listening on this path
deleteChannel(); //delete the data we wrote
}
}
/**
* This function opens a realtime communication channel with Firebase
* It logs in securely using the client token passed from the server
* then it sets up a listener on the proper database path (also passed by server)
* finally, it calls onOpened() to let the server know it is ready to receive messages
*/
function openChannel() {
// [START auth_login]
// sign into Firebase with the token passed from the server
firebase.auth().signInWithCustomToken(token).catch(function(error) {
console.log('Login Failed!', error.code);
console.log('Error message: ', error.message);
});
// [END auth_login]
// [START add_listener]
// setup a database reference at path /channels/channelId
channel = firebase.database().ref('channels/' + channelId);
// add a listener to the path that fires any time the value of the data changes
channel.on('value', function(data) {
onMessage(data.val());
});
// [END add_listener]
onOpened();
// let the server know that the channel is open
}
/**
* This function opens a communication channel with the server
* then it adds listeners to all the squares on the board
* next it pulls down the initial game state from template values
* finally it updates the game state with those values by calling onMessage()
*/
function initialize() {
// Always include the gamekey in our requests
$.ajaxPrefilter(function(opts) {
if (opts.url.indexOf('?') > 0)
opts.url += '&gameKey=' + state.gameKey;
else
opts.url += '?gameKey=' + state.gameKey;
});
$('#board').on('click', '.cell', moveInSquare);
openChannel();
onMessage(initialMessage);
}
setTimeout(initialize, 100);
}