-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
81 lines (58 loc) · 1.82 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
const express = require('express');
const http = require('http');
const socket = require('socket.io');
const PORT = process.env.PORT || 5000
var app = express();
const server = http.createServer(app)
const io = socket(server)
var players;
// var joined = true;
app.use(express.static(__dirname + "/"));
var games = Array(100);
for (let i = 0; i < 100; i++) {
games[i] = { players: 0, pid: [0, 0] };
}
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/index.html');
});
io.on('connection', function (socket) {
// console.log(players);
var color;
var playerId = Math.floor((Math.random() * 100) + 1)
console.log(playerId + ' connected');
socket.on('joined', function (roomId) {
// games[roomId] = {}
if (games[roomId].players < 2) {
games[roomId].players++;
games[roomId].pid[games[roomId].players - 1] = playerId;
}
else {
socket.emit('full', roomId)
return;
}
console.log(games[roomId]);
players = games[roomId].players
if (players % 2 == 0) color = 'black';
else color = 'white';
socket.emit('player', { playerId, players, color, roomId })
// players--;
});
socket.on('move', function (msg) {
socket.broadcast.emit('move', msg);
// console.log(msg);
});
socket.on('play', function (msg) {
socket.broadcast.emit('play', msg);
console.log("ready " + msg);
});
socket.on('disconnect', function () {
for (let i = 0; i < 100; i++) {
if (games[i].pid[0] == playerId || games[i].pid[1] == playerId)
games[i].players--;
}
console.log(playerId + ' disconnected');
});
});
server.listen(PORT, function () {
console.log(`Server running on port ${PORT}`);
});