-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
53 lines (41 loc) · 1.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
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const PORT = process.env.PORT || 3000;
//middleware
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const path = require('path');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => res.sendFile(path.resolve('public/html/index.html')));
server.listen(PORT, () => {
console.log(`App listening at http://localhost:${PORT}`);
});
const playerIDs = new Set();
io.on('connection', (socket) => {
// notify all other players of new joiner
socket.broadcast.emit('playerConnected', { id: socket.id });
// notify new joiner of players already in game
socket.emit('playersInRoom', Array.from(playerIDs));
playerIDs.add(socket.id);
//position = {x,y}
socket.on('playerPositionUpdated', (position) =>
socket.broadcast.emit('playerPositionUpdated', { ...position, id: socket.id })
);
socket.on('disconnect', () => {
socket.broadcast.emit('playerDisconnected', { id: socket.id });
playerIDs.delete(socket.id);
});
// console.log(io.of('/').connected);
// socket.on('update', (player) => {
// socket.broadcast.emit('update', {
// x: player.x,
// y: player.y,
// });
// });
});