-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
216 lines (186 loc) · 7.75 KB
/
app.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
var
http = require('http'),
path = require('path'),
fs = require('fs'),
swig = require('swig'),
socket = require('socket.io'),
deleteKey = require('key-del');
gu = require('./gameutils.js');
var domain = 'localhost:8080'; // change this
var room, ongoing = {};
// function defs
function randomString(length) {
chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
return result;
}
// route
var server = http.createServer(function(req, res) {
var
content = '',
fileName = path.basename(req.url),
pathName = path.dirname(req.url),
localFolder = __dirname;
// serve static files
if (path.dirname(pathName) == '/static') {
content = localFolder + req.url;
fs.readFile(content, function(err, contents) {
if(!err) {
// write proper header
if (path.basename(pathName) == 'css')
res.writeHead(200, {'Content-Type': 'text/css'});
else if (path.basename(pathName) == 'js')
res.writeHead(200, {'Content-Type': 'text/javascript'});
// write contents
res.end(contents);
} else {
console.dir(err);
}
});
} else if (fileName == 'favicon.ico') {
} else if (fileName == '' && pathName == '/'){ // serve intro page
res.writeHead(200, {'Content-Type': 'text/html'});
tpl = swig.compileFile('templates/index.html');
res.write(tpl({
'quickroom': randomString(6),
'rooms': Object.keys(ongoing),
'domain': domain
}));
res.end();
} else if (pathName == '/') { // serve board page
room = fileName; // temporary
res.writeHead(200, {'Content-Type': 'text/html'});
tpl = swig.compileFile('templates/gameboard.html');
res.write(tpl());
res.end();
} else {
res.writeHead(404, {'Content-Type': 'text/html'});
res.write(':(');
res.end();
}
});
// sockets
var io = socket.listen(server);
io.sockets.on('connection', function(client) {
// connect to room
client.room = room;
client.join(client.room);
// initialize game
client_list = io.sockets.adapter.rooms[client.room];
client_list_length = Object.keys(client_list).length;
// initialize room
if (!(client.room in ongoing)) {
ongoing[client.room] = {};
ongoing[client.room]['player1'] = client.id;
ongoing[client.room]['player2'] = false;
ongoing[client.room]['spectators'] = 0;
ongoing[client.room]['nextMove'] = 1;
ongoing[client.room]['board'] = JSON.parse(JSON.stringify(gu.emptyBoard)); // feels dirty
client.pn = 1;
console.log('[NEW] room: ' + client.room + ' | player1: ' + ongoing[client.room]['player1'] + ' | player2: ' + ongoing[room]['player2']); //FIXME logging
} else if (!ongoing[client.room]['player1']) {
ongoing[room]['player1'] = client.id;
client.pn = 1;
} else if (!ongoing[client.room]['player2']) {
ongoing[room]['player2'] = client.id;
client.pn = 2;
} else {
ongoing[room]['spectators'] += 1;
client.pn = 3;
}
// send connection data
client.emit('new-connect', {'pn': client.pn ,
'board': ongoing[client.room]['board'],
'nextPlayer': ongoing[client.room]['nextMove']
});
// display message to opponent
if (client.pn < 3) {
client.broadcast.to(client.room).emit(
'display-message',
{'to': [1, 2], 'message': 'Opponnent connected.'}
);
client.broadcast.to(client.room).emit(
'display-message',
{'to': [3], 'message': 'Player ' + client.pn + ' connected.'}
);
} else {
client.broadcast.to(client.room).emit(
'display-message',
{'to': [1, 2, 3], 'message': 'Spectator connected.'}
);
}
console.log('[CON] room: ' + client.room + ' | pn: ' + client.pn + ' | id: ' + client.id); //FIXME logging
// on disconnect
client.on('disconnect', function(data) {
console.log('[DCN] room: ' + client.room + ' | pn: ' + client.pn + ' | id: ' + client.id); //FIXME logging
// log player disconnect
if (client.pn == 1) {
ongoing[client.room]['player1'] = false;
} else if (client.pn == 2) {
ongoing[client.room]['player2'] = false;
} else {
ongoing[client.room]['spectators'] -= 1;
}
// destroy room if nobody left
if (!ongoing[client.room]['player1'] && !ongoing[client.room]['player2'] && !ongoing[client.room]['spectators']) {
console.log('[DEL] room: ' + client.room + ' | player1: ' + ongoing[client.room]['player1'] + ' | player2: ' + ongoing[client.room]['player2'] + ' | spectators: ' + ongoing[client.room]['spectators']); //FIXME logging
ongoing = deleteKey(ongoing, [client.room]);
}
if (client.pn < 3) {
client.broadcast.to(client.room).emit(
'display-message',
{'to': [1, 2], 'message': 'Opponnent disconnected.'}
);
client.broadcast.to(client.room).emit(
'display-message',
{'to': [3], 'message': 'Player ' + client.pn + ' disconnected.'}
);
} else {
client.broadcast.to(client.room).emit(
'display-message',
{'to': [1, 2, 3], 'message': 'Spectator disconnected.'}
);
}
});
// sending moves
client.on('send-move', function(data) {
// validate move
if (client.pn == ongoing[client.room]['nextMove'] &&
ongoing[client.room]['board'][data['outer']][data['inner']] != 'e')
return;
if (ongoing[client.room]['nextMove'] == 0)
return;
ongoing[client.room]['nextMove'] = (ongoing[client.room]['nextMove'] == 1) ? 2 : 1;
// update board
ongoing[client.room]['board'][data['outer']][data['inner']] = data['player']['symbol'];
gu.disableAll(ongoing[client.room]['board']);
// check for captures
if (gu.isCaptured(ongoing[client.room]['board'], data['outer'])) {
for (inner = 0; inner < 9; inner++)
ongoing[client.room]['board'][data['outer']][inner] = client.pn;
if (gu.isWon(ongoing[client.room]['board'])) {
io.in(client.room).emit('game-over', {'winner': client.pn});
ongoing[client.room]['nextMove'] = 0;
console.log('[WIN] room: ' + client.room + ' | player: ' + client.pn); //FIXME logging
} else if (gu.isTie(ongoing[client.room]['board'])) {
io.in(client.room).emit('game-over', {'winner': 0});
ongoing[client.room]['nextMove'] = 0;
console.log('[TIE] room: ' + client.room); //FIXME logging
}
}
// enable moves
if (ongoing[client.room]['board'][data['inner']][0] == '1' ||
ongoing[client.room]['board'][data['inner']][0] == '2' ||
gu.isFull(ongoing[client.room]['board'], data['inner'])) {
gu.enableAll(ongoing[client.room]['board']);
} else {
gu.enableBlock(ongoing[client.room]['board'], data['inner']);
}
// send move
data['nextPlayer'] = ongoing[client.room]['nextMove'];
data['board'] = JSON.parse(JSON.stringify(ongoing[client.room]['board']));
client.broadcast.to(client.room).emit('push-move', data);
});
});
server.listen(8080);