Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
104 lines (88 loc) · 2.32 KB
/
Copy pathapp.js
File metadata and controls
104 lines (88 loc) · 2.32 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
95
96
97
98
99
100
101
102
103
104
var app = require("http").createServer(handler),
io = require("socket.io").listen(app),
fs = require("fs"),
path = require("path"),
sprite = require("./spritemap"),
world = require("./world"),
player = require("./player");
app.listen(8056);
function handler(req, res) {
var file = "." + req.url;
if(file === "./") file = "./index.html";
var extname = path.extname(file);
var contentType;
switch(extname) {
case '.html':
case '.htm':
contentType = 'text/html';
break;
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.png':
contentType = 'image/png';
break;
//don't allow any other file types
default:
console.log(extname, file);
res.writeHead(500);
res.end();
return;
}
path.exists(file, function(exists) {
if(exists) {
fs.readFile(file, function(err, data) {
res.writeHead(200, {'Content-Type': contentType});
res.end(data);
});
} else {
console.log("404", "[" + file + "]");
res.writeHead(404);
res.end();
}
});
}
//on first connection, send map
io.sockets.on("connection", function(socket) {
//user provides their name
socket.on("name", function(data) {
//check valid name
if(!player.register(data)) {
socket.emit("error");
return;
}
socket.set("name", data);
//sit them in the middle
var key = player.add(0, 0, data, [8, 11], socket);
socket.set("key", key);
//once their name is provided, give them 0, 0
socket.emit("generate", world.load(0, 0));
});
//on update position, emit
socket.on("updatepos", function(data) {
socket.get("key", function(err, key) {
socket.get("name", function(err, name) {
socket.set("key", player.updatePosition(key, name, data, socket));
});
});
});
//on update map
socket.on("updatemap", function(data) {
socket.get("name", function(err, name) {
world.updateBlock(data.chunk, data);
socket.broadcast.emit("blockchange", data);
});
});
//user requests new chunk
socket.on("newchunk", function(x, y) {
socket.emit("newchunk", {key: (x + "," + y), data: world.load(x, y)});
});
socket.on("disconnect", function() {
socket.get("name", function(err, name) {
player.remove(name);
});
});
});