-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket.js
109 lines (67 loc) · 2.83 KB
/
socket.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
var socketio = require( 'socket.io' )
, models = require( './models' );
exports.initialize = function( server ) {
var io = socketio.listen( server )
, player_count = 0;
models.Player.findAll( { limit: 1, order: 'id DESC' } ).success( function( players ) {
if ( players[ 0 ] ) {
player_count = players[ 0 ].get( 'id' );
}
io.sockets.on( 'connection', function( socket ) {
var player = models.Player.create( {
name: 'Player ' + ++player_count
} )
.success( function( player ) {
console.log( player.get( 'name' ) + ' joined the server' );
socket.emit( 'started', {
player: player,
rooms: models.rooms
} );
player.socket = socket;
socket.on( 'join', function( room_id, callback ) {
var room = models.rooms[ room_id ];
if ( !room ) {
return callback && callback( true, 'Room does not exist' );
}
if ( player.room ) {
player.room.removePlayer( player );
}
try {
room.addPlayer( player );
} catch( e ) {
return callback && callback( true, 'Failed to join room: ' + e );
}
return callback( false, {
opponent: room.getOpponent( player )
, position: room.getPosition( player )
} );
} );
socket.on( 'leave', function( callback ) {
if ( player.room ) {
player.room.removePlayer( player );
}
callback( false );
} );
socket.on( 'relay', function( options, callback ) {
if ( !player.room ) {
return callback && callback(true, 'Player is not part of a room')
}
player.room.getPlayers().forEach( function( room_player ) {
if ( room_player.socket && room_player != player ) {
room_player.socket.emit( 'relay', options );
}
} );
callback && callback(false);
} );
socket.on( 'room_list', function( callback ) {
callback( false, models.rooms )
} );
socket.on( 'disconnect', function() {
if ( player.room ) {
player.room.removePlayer( player );
}
} );
} );
} );
} );
}