-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
94 lines (60 loc) · 2.01 KB
/
server.js
File metadata and controls
94 lines (60 loc) · 2.01 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Dependencies
var express = require('express');
var http = require('http');
var path = require('path');
var socketIO = require('socket.io');
var app = express();
var server = http.Server(app);
var io = socketIO(server);
app.set('port', 5000);
app.use('/static', express.static(__dirname + '/static'));
// Routing
app.get('/', function(request, response) {
response.sendFile(path.join(__dirname, '/static/index.html'));
});
// Starts the server.
server.listen(5000, function() {
console.log('Starting server on port 5000');
});
//setInterval(function() {
// io.sockets.emit('message', 'hi!');
//}, 1000);
var players = {};
io.on('connection', function(socket) {
socket.on('new player', function() {
players[socket.id] = {
x: 300,
y: 300
};
socket.emit("yoursocketid", socket.id);
});
socket.on('movement', function(data) {
var player = players[socket.id] || {};
if (data.left) {
player.x -=5;
}
if (data.up) {
player.y -= 5;
}
if (data.right) {
player.x += 5;
}
if (data.down) {
player.y += 5;
}
});
socket.on('disconnect', function() {
io.sockets.emit('player disconnected', "player " + socket.id + " disconnected");
delete players[socket.id];
});
socket.on("chat message", function(data) {
console.log("message from " + data.from + ": " + data.message);
io.sockets.emit("new message", data.from + ": " + data.message);
});
socket.on("myusername", function(data) {
players[socket.id].username = data;
});
});
setInterval(function() {
io.sockets.emit('state', players);
}, 1000 / 60);