-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
109 lines (83 loc) · 2.43 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
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 app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var slashes = require('connect-slashes');
app.use(slashes());
/* ROUTING */
app.get('/', function(req, res){
res.sendFile(__dirname + "/game/index.html");
});
app.get('/game/:file', function(req, res) {
var file = req.params.file;
res.sendFile(__dirname + "/game/" + file);
});
app.get('/control/', function(req, res) {
res.sendFile(__dirname + "/control/index.html");
});
app.get('/control/:file', function(req, res) {
var file = req.params.file;
res.sendFile(__dirname + "/control/" + file);
});
app.get('/control/img/:file', function(req, res) {
var file = req.params.file;
res.sendFile(__dirname + "/control/img/" + file);
});
/*SOCKET*/
var serverList = {};
var serverIdList = new Array();
io.on('connection', function(socket){
var newId = "";
var isServer = false;
socket.on("register", function(obj) {
/*JIKA YANG REGISTER SERVER*/
if (obj.as == "server") {
newId = makeid();
serverList[newId] = socket;
serverIdList.push(newId);
isServer = true;
socket.emit("reg_success", newId);
console.log("new server -", newId);
} else {
/*JIKA YANG REGISTER BUKAN SERVER*/
newId = obj.kode;
if (serverList[newId] != undefined) {
socket.emit("reg_success", newId);
serverList[newId].emit("new user");
} else {
socket.emit("reg_fail", "tidak ada game dengan kode " + newId);
}
console.log("client connect with", newId);
}
});
socket.on("move", function (arah) {
if (serverList[newId] != undefined) {
serverList[newId].emit("move", arah);
} else {
socket.emit("game_disconnect");
}
});
socket.on("disconnect", function() {
if (isServer) {
serverList[newId] = undefined;
serverIdList.splice(serverIdList.indexOf(newId), 1);
console.log("disconnect server -", newId);
} else if (newId != "") {
if (serverList[newId] != undefined)
serverList[newId].emit("remove user");
console.log("disconnect client -", newId);
}
});
});
function makeid() {
var text = "";
var possible = "abcdefghijklmnopqrstuvwxyz";
for( var i=0; i < 3; i++ ) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
if (serverList[text] != undefined)
text = makeid();
return text;
}
http.listen(81, function(){
console.log('listening on *:81');
});