-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
81 lines (68 loc) · 2.37 KB
/
index.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
'use strict';
const
express = require('express'),
app = express(),
server = require('http').createServer(app),
zmq = require('zmq'),
io = require('socket.io').listen(server, {log: false}),
Controller = require('./lib/controller'),
Game = require('./lib/game');
// Configure Express app:
app.use(express.static(__dirname + '/public'));
// Initialize game instance:
const game = new Game();
game.on('playerMiss', function(playerId) {
console.log('Player ['+playerId+'] missed the ball!');
clientEmit('playerMiss', { playerId: playerId, lives: game.lives })
});
game.on('over', function(lives) {
console.log('Game over! Score [player1: '+lives.player1+' lives] || [player2: '+lives.player2+' lives].');
clientEmit('over', { lives: lives })
});
game.ball.on('reset', function(timeout) {
clientEmit('ballReset', { timeout: timeout });
});
// Add new sockets to client pool:
const clients = {};
io.sockets.on('connection', function(socket) {
clients[socket.id] = socket;
socket.on('disconnect', function() {
delete clients[socket.id];
});
});
// Setup emitter hook:
function clientEmit(msg, data) {
for (let clientId in clients) {
let socket = clients[clientId];
socket.emit(msg, data);
}
}
// Setup controller emitters:
if (process.env.NODE_ENV === 'production') {
var controller1 = new Controller('zmq', { address: 'tcp://192.168.109.135:9000' });
var controller2 = new Controller('zmq', { address: 'tcp://192.168.109.135:9001' });
controller1.emitter.on('player1Move', game.paddles.player1.move);
controller1.emitter.on('player2Move', game.paddles.player2.move);
controller2.emitter.on('player1Move', game.paddles.player1.move);
controller2.emitter.on('player2Move', game.paddles.player2.move);
} else {
var controller = new Controller('test', { game: game });
controller.emitter.on('player1Move', game.paddles.player1.move);
controller.emitter.on('player2Move', game.paddles.player2.move);
}
// === spray data to clients
// todo: use setImmediate or throttle nextTick/run-loop
// todo: combine into single message thread
function spray() {
clientEmit('update', {
player1: game.paddles.player1,
player2: game.paddles.player2,
ball: game.ball.getPosition()
});
setTimeout(spray, 3);
}
// === start server
server.listen(3000);
console.log('Server started ---> listening on [localhost:3000]');
// Start spraying data to clients:
spray();