-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcocoon_multiplayer.js
425 lines (370 loc) · 17.9 KB
/
cocoon_multiplayer.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
(function(){
if (!window.Cocoon && window.cordova && typeof require !== 'undefined') {
require('cocoon-plugin-common.Cocoon');
}
var Cocoon = window.Cocoon;
/**
* @fileOverview
<h2>About Atomic Plugins</h2>
<p>Atomic Plugins provide an elegant and minimalist API and are designed with portability in mind from the beginning. Framework dependencies are avoided by design so the plugins can run on any platform and can be integrated with any app framework or game engine.
<br/> <p>You can contribute and help to create more awesome plugins. </p>
<h2>Atomic Plugins for Multiplayer</h2>
<p>This <a src="https://github.com/ludei/atomic-plugins-multiplayer">repository</a> contains a Multiplayer API designed using the Atomic Plugins paradigm. The API is already available in many languagues and we plan to add more in the future.</p>
<h3>Setup your project</h3>
<p>Releases are deployed to Cordova Plugin Registry.
You only have to install the desired plugins using Cordova CLI and <a href="https://cocoon.io"/>Cocoon Cloud service</a>.</p>
<ul>
<code>cordova plugin add cocoon-plugin-multiplayer-ios-gamecenter</code><br/>
<code>cordova plugin add cocoon-plugin-multiplayer-android-googleplaygames</code><br/>
</ul>
<h3>Documentation</h3>
<p>In this section you will find all the documentation you need for using this plugin in your Cordova project.
Select the specific namespace below to open the relevant documentation section:</p>
<ul>
<li><a href="http://ludei.github.io/atomic-plugins-docs/dist/doc/js/Cocoon.Multiplayer.html">Multiplayer</a></li>
<li><a href="http://ludei.github.io/atomic-plugins-docs/dist/doc/js/Cocoon.Multiplayer.Loopback.html">Loopback Multiplayer</a></li>
<li><a href="http://ludei.github.io/atomic-plugins-docs/dist/doc/js/Cocoon.Multiplayer.GameCenter.html">Game Center Multiplayer</a></li>
<li><a href="http://ludei.github.io/atomic-plugins-docs/dist/doc/js/Cocoon.Multiplayer.GooglePlayGames.html">Google Play Games Multiplayer</a></li>
</ul>
<h3>Full example</h3>
See a full example here: <a href="https://github.com/CocoonIO/cocoon-sample-multiplayer/"/>Multiplayer demo</a>
* @version 1.0
*/
/**
* @namespace Cocoon.Multiplayer
*/
Cocoon.define("Cocoon.Multiplayer" , function(extension){
extension.MultiplayerService = function(serviceName)
{
this.serviceName = serviceName;
this.serviceSignal = new Cocoon.Signal();
this.on = this.serviceSignal.expose();
this.matches = {};
this.currentMatch = null;
document.addEventListener('deviceready', function(){
this.init();
}.bind(this));
};
/**
* Triggered when an invitation is received and loaded. This listener should be setup first thing even before the init is called.
* @memberOf Cocoon.Multiplayer
* @event On invitation
* @example
* multiplayerService.on("invitation", {
* received: function() {
* console.log("Invitation received");
* },
* loaded: function(match, error) {
* console.log("Invitation ready: (Error: + " + JSON.stringify(error) + ")");
* }
* });
*/
extension.MultiplayerService.prototype = {
/**
* @private
*/
init: function(){
var me = this;
//Invitation listeners
Cocoon.exec(me.serviceName, "setServiceListener", [], function(params) {
var event = params[0];
if (event === 'invitationReceived') {
me.serviceSignal.emit('invitation', 'received');
}
else if (event === 'invitationLoaded') {
var matchData = params[1];
me.serviceSignal.emit('invitation', 'loaded', [me._createMatch(matchData)]);
}
}, function(event, error) {
me.serviceSignal.emit('invitation', 'loaded', [null, error]);
});
//Match listeners
Cocoon.exec(me.serviceName, "setMatchListener", [], function(params) {
var matchKey = params[0];
var eventName = params[1];
var match = me.matches[matchKey];
if (!match) {
return;
}
var playerID;
if (eventName === 'dataReceived') {
var msg = params[2];
playerID = params[3];
match.signal.emit('match', eventName, [match, msg, playerID]);
}
else if (eventName === 'stateChanged') {
playerID = params[2];
var state = params[3];
match.matchData = params[4];
match.signal.emit('match', eventName, [match, playerID, state]);
}
else {
//connectionWithPlayerFailed or failed
match.signal.emit('match', eventName, [match, params[2], params[3]]);
}
});
},
/**
* @private
*/
_createMatch: function(matchData) {
var match = new Cocoon.Multiplayer.Match(this.serviceName, matchData);
this.matches[matchData.key] = match;
this.currentMatch = match;
return match;
},
/**
* Presents a system View for the matchmaking and creates a new Match.
* @function findMatch
* @memberOf Cocoon.Multiplayer
* @private
* @param {Cocoon.Multiplayer.MatchRequest} matchRequest The parameters for the match.
* @param {Function} callback The callback function. It receives the following parameters:
* - {@link Cocoon.Multiplayer.Match}.
* - Error.
*/
findMatch : function(matchRequest, callback) {
var me = this;
callback = callback || function(){};
Cocoon.exec(this.serviceName, 'findMatch', [matchRequest], function(matchData){
callback(me._createMatch(matchData));
}, function(error) {
callback(null, error);
});
},
/**
* Sends an automatch request to join the authenticated user to a match. It doesn't present a system view while waiting to other players.
* @function findAutoMatch
* @memberOf Cocoon.Multiplayer
* @private
* @param {Cocoon.Multiplayer.MatchRequest} matchRequest The parameters for the match.
* @param {Function} callback The callback function. It receives the following parameters:
* - {@link Cocoon.Multiplayer.Match}.
* - Error.
*/
findAutoMatch : function(matchRequest, callback) {
var me = this;
callback = callback || function(){};
Cocoon.exec(this.serviceName, 'findAutoMatch', [matchRequest], function(matchData){
callback(me._createMatch(matchData));
}, function(error) {
callback(null, error);
});
},
/**
* Cancels the ongoing automatch request.
* @function cancelAutoMatch
* @memberOf Cocoon.Multiplayer
* @private
*/
cancelAutoMatch : function() {
Cocoon.exec(this.serviceName, 'cancelAutoMatch');
},
/**
* Automatically adds players to an ongoing match owned by the user.
* @function addPlayersToMatch
* @memberOf Cocoon.Multiplayer
* @private
* @param {Cocoon.Multiplayer.MatchRequest} matchRequest The parameters for the match.
* @param {Cocoon.Multiplayer.Match} matchRequest The match where new players will be added.
* @param {Function} callback The callback function. Response parameters: error.
*/
addPlayersToMatch : function(matchRequest, match, callback) {
callback = callback || function(){};
Cocoon.exec(this.serviceName, 'addPlayersToMatch', [match.key, matchRequest], function(){
callback(null);
}, function(error){
callback(error);
});
},
/**
* Get the current match reference.
* @function getMatch
* @memberOf Cocoon.Multiplayer
* @private
* @return {Cocoon.Multiplayer.Match} The current match reference.
*/
getMatch : function() {
return this.currentMatch;
}
};
/**
* This type provides a transmission network between a group of users.
* The match might be returned before connections have been established between players. At this stage, all the players are in the process of connecting to each other.
* Always check the getExpectedPlayerCount value before starting a match. When its value reaches zero, all expected players are connected, and your game can begin the match.
* Do not forget to call the start method of the match when your game is ready to process received messages via onMatchDataReceived listener.
* @constructor Match
* @memberOf Cocoon.Multiplayer
* @param {string} serviceName The name of the native ext object extension property name.
* @param {object} matchData The match data received from the native service bridge.
*/
extension.Match = function(serviceName, matchData)
{
this.serviceName = serviceName;
this.matchData = matchData;
this.signal = new Cocoon.Signal();
this.on = this.signal.expose();
/**
* Allows to listen to events about the restoring process.
* - The callback 'dataReceived'
* - The callback 'stateChanged'
* - The callback 'connectionWithPlayerFailed' allows listening to events called when a netowrk connection with a player fails
* - The callback 'failed' allows listening to events called when the match fails.
* @event On restore products callbacks
* @memberof Cocoon.Multiplayer.Match
* @example
* match.on("match",{
* dataReceived: function(match, data, playerId){ ... },
* stateChanged: function(match, playerId, connectionState){ ... },
* connectionWithPlayerFailed: function(match, playerId, errorMsg){ ... }
* failed: function(match, errorMsg){ ... }
* });
*/
this.on = this.signal.expose();
};
extension.Match.prototype = {
/**
* Starts processing received messages. The user must call this method when the game is ready to process messages. Messages received before being prepared are stored and processed later.
* @function start
* @memberOf Cocoon.Multiplayer.Match
*/
start : function() {
Cocoon.exec(this.serviceName, 'start', [this.matchData.key]);
},
/**
* Transmits data to all players connected to the match. The match queues the data and transmits it when the network becomes available.
* @function sendDataToAllPlayers
* @memberOf Cocoon.Multiplayer.Match
* @param {string} data The data to transmit.
* @param {Cocoon.Multiplayer.SendDataMode} [sendMode] The optional {@link Cocoon.Multiplayer.SendDataMode} value. The default value is RELIABLE.
* @return {boolean} TRUE if the data was successfully queued for transmission; FALSE if the match was unable to queue the data.
*/
sendDataToAllPlayers : function(data, sendMode) {
Cocoon.exec(this.serviceName, 'sendDataToAllPlayers', [this.matchData.key, data, sendMode]);
},
/**
* Transmits data to a list of connected players. The match queues the data and transmits it when the network becomes available.
* @function sendData
* @memberOf Cocoon.Multiplayer.Match
* @param {string} data The data to transmit
* @param {array} playerIDs An array containing the identifier strings for the list of players who should receive the data.
* @param {Cocoon.Multiplayer.SendDataMode} [sendMode] The optional {@link Cocoon.Multiplayer.SendDataMode} value. The default value is RELIABLE.
* @return {boolean} TRUE if the data was successfully queued for transmission; FALSE if the match was unable to queue the data.
*/
sendData : function(data, playerIDs, sendMode) {
Cocoon.exec(this.serviceName, 'sendData', [this.matchData.key, data, playerIDs, sendMode]);
},
/**
* Disconnects the local player from the match and releases the match. Calling disconnect notifies other players that you have left the match.
* @function disconnect
* @memberOf Cocoon.Multiplayer.Match
*/
disconnect : function() {
Cocoon.exec(this.serviceName, 'disconnect', [this.matchData.key]);
},
/**
* Requests additional information of the current players in the match.
* @function requestPlayersInfo
* @memberOf Cocoon.Multiplayer.Match
* @param {Function} callback The callback function. Response params: players array and error
*/
requestPlayersInfo : function(callback) {
Cocoon.exec(this.serviceName, 'requestPlayersInfo', [this.matchData.key], function(players){
var result = [];
for (var i = 0; i < players.length; ++i) {
var player = players[i];
result.push(new Cocoon.Multiplayer.PlayerInfo(player.playerID, player.alias));
}
callback(result, null);
}, function(error) {
callback(null, error);
});
},
/**
* Returns the remaining players count who have not yet connected to the match.
* @function getExpectedPlayerCount
* @memberOf Cocoon.Multiplayer.Match
* @return {number} The remaining number of players who have not yet connected to the match.
*/
getExpectedPlayerCount : function() {
return this.matchData.expectedPlayerCount;
},
/**
* Returns an array with all the player identifiers taking part in the match.
* @function getPlayerIDs
* @memberOf Cocoon.Multiplayer.Match
* @return {array} The player identifiers for the players in the match.
*/
getPlayerIDs : function() {
return this.matchData.playerIDs;
},
/**
* Gets the local playerID taking part in the match.
* @function getLocalPlayerID
* @memberOf Cocoon.Multiplayer.Match
* @return {string} the playerID attached to the match manager.
*/
getLocalPlayerID : function() {
return this.matchData.localPlayerID;
},
};
/**
* This object represents the modes to send data.
* @memberof Cocoon.Multiplayer
* @name Cocoon.Multiplayer.SendDataMode
* @property {object} Cocoon.Multiplayer.SendDataMode - The object itself
* @property {string} Cocoon.Multiplayer.SendDataMode.RELIABLE The data is sent continuously until it is successfully received by the intended recipients or the connection times out.
* @property {string} Cocoon.Multiplayer.SendDataMode.UNRELIABLE The data is sent once and is not sent again if a transmission error occurs.
*/
extension.SendDataMode = {
RELIABLE : 0,
UNRELIABLE : 1
};
/**
* This object represents the connection state of a player.
* @memberof Cocoon.Multiplayer
* @name Cocoon.Multiplayer.ConnectionState
* @property {object} Cocoon.Multiplayer.ConnectionState - The object itself
* @property {string} Cocoon.Multiplayer.ConnectionState.UNKNOWN The connection is in unknown state.
* @property {string} Cocoon.Multiplayer.ConnectionState.CONNECTED The connection is in connected state.
* @property {string} Cocoon.Multiplayer.ConnectionState.DISCONNECTED The connection is in disconnected state.
*/
extension.ConnectionState = {
UNKNOWN : 0,
CONNECTED : 1,
DISCONNECTED : 2
};
/**
* The object that represents the information of a player inside a multiplayer match.
* @memberof Cocoon.Multiplayer
* @name Cocoon.Multiplayer.PlayerInfo
* @property {object} Cocoon.Multiplayer.PlayerInfo - The object itself
* @property {string} Cocoon.Multiplayer.PlayerInfo.userID The id of the user.
* @property {string} Cocoon.Multiplayer.PlayerInfo.userName The name of the user.
*/
extension.PlayerInfo = function(userID, userName) {
this.userID = userID;
this.userName = userName;
};
/**
* This object is used to specify the parameters for a new multiplayer match.
* @memberof Cocoon.Multiplayer
* @name Cocoon.Multiplayer.MatchRequest
* @property {object} Cocoon.Multiplayer.MatchRequest - The object itself
* @property {number} Cocoon.Multiplayer.MatchRequest.minPlayers The minimum number of players that may join the match.
* @property {number} Cocoon.Multiplayer.MatchRequest.maxPlayers The maximum number of players that may join the match.
* @property {array} [Cocoon.Multiplayer.MatchRequest.playersToInvite] Optional list of player identifers for players to invite to the match.
* @property {number} [Cocoon.Multiplayer.MatchRequest.playerGroup] Optional number identifying a subset of players allowed to join the match.
* @property {number} [Cocoon.Multiplayer.MatchRequest.playerAttributes] Optional mask that specifies the role that the local player would like to play in the game.
*/
extension.MatchRequest = function(minPlayers, maxPlayers, playersToInvite, playerGroup, playerAttributes) {
this.minPlayers = minPlayers || 2;
this.maxPlayers = maxPlayers || this.minPlayers;
this.playersToInvite = playersToInvite;
this.playerGroup = playerGroup;
this.playerAttributes = playerAttributes;
return this;
};
return extension;
});
})();