-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
72 lines (59 loc) · 1.63 KB
/
Copy pathindex.js
File metadata and controls
72 lines (59 loc) · 1.63 KB
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
const express = require('express');
const socket = require('socket.io');
const app = express();
const server = app.listen(8080, function() {
console.log("Listening to request on port 8080");
});
const io = socket(server);
app.use(express.static('public'));
let userOnline = 0;
var player = {},
unmatched;
io.on('connection', function(socket) {
console.log("Making connection", socket.id);
socket.on("join", function(){
userOnline++;
console.log("User Join = " + userOnline);
io.sockets.emit("userOnline", userOnline);
});
joinGame(socket);
if (getOpponent(socket)) {
io.sockets.emit("begin", {
chara: player[socket.id].chara,
});
getOpponent(socket).emit("begin", {
chara: player[getOpponent(socket).id].chara,
});
}
socket.on("nickname", function(data){
io.sockets.emit("nickname", data);
});
socket.on("chat", function(data) {
io.sockets.emit("chat", data);
});
socket.on("disconnect", function(){
userOnline--;
console.log("User Out");
io.sockets.emit("userOnline", userOnline);
});
});
function joinGame(socket) {
player[socket.id] = {
opponent: unmatched,
chara: "./white.png",
socket: socket,
};
if (unmatched) {
player[socket.id].chara = "./black.png";
player[unmatched].opponent = socket.id;
unmatched = null;
} else {
unmatched = socket.id;
}
}
function getOpponent(socket) {
if (!player[socket.id].opponent) {
return;
}
return player[player[socket.id].opponent].socket;
}