forked from octachrome/treason
-
Notifications
You must be signed in to change notification settings - Fork 0
/
net-player.js
104 lines (92 loc) · 2.59 KB
/
net-player.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
/*
* Copyright 2015-2016 Christopher Brown and Jackie Niebling.
*
* This work is licensed under the Creative Commons Attribution-NonCommercial 4.0 International License.
*
* To view a copy of this license, visit http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to:
* Creative Commons
* PO Box 1866
* Mountain View
* CA 94042
* USA
*/
'use strict';
function createNetPlayer(game, socket, playerName) {
var player = {
name: playerName || 'Anonymous',
onStateChange: onStateChange,
onHistoryEvent: onHistoryEvent,
onChatMessage: onChatMessage,
onPlayerLeft: onPlayerLeft,
playerId: socket.playerId
};
try {
var gameProxy = game.playerJoined(player);
} catch(e) {
handleError(e);
return;
}
function onStateChange(state) {
socket.emit('state', state);
}
function onChatMessage(playerIdx, message) {
socket.emit('chat', {
from: playerIdx,
message: message
});
}
function onHistoryEvent(message, type, histGroup) {
socket.emit('history', {
message: message,
type: type,
histGroup: histGroup
});
}
function onCommand(data) {
try {
if (gameProxy != null) {
gameProxy.command(data);
}
} catch(e) {
handleError(e);
}
}
function sendChatMessage(message) {
if (gameProxy != null) {
gameProxy.sendChatMessage(message);
}
}
function onPlayerLeft() {
socket.removeListener('command', onCommand);
socket.removeListener('chat', sendChatMessage);
socket.removeListener('disconnect', leaveGame);
socket.removeListener('join', leaveGame);
setTimeout(function () {
socket.emit('state', null);
});
}
function leaveGame() {
if (gameProxy != null) {
gameProxy.playerLeft();
gameProxy = null;
game = null;
}
}
socket.on('command', onCommand);
socket.on('chat', sendChatMessage);
socket.on('disconnect', leaveGame);
// If the player joins another game, leave this one.
socket.on('join', leaveGame);
function handleError(e) {
var message;
if (e instanceof Error) {
console.error(e);
console.error(e.stack);
message = 'Internal error';
} else {
message = e.message;
}
socket.emit('game-error', message);
}
}
module.exports = createNetPlayer;