pirate/server.js
2017-06-25 21:45:40 +02:00

79 lines
1.6 KiB
JavaScript

var PORT = 8080;
var gameMode = true;
var allSockets = {};
var allPlayers = {};
var userCnt = 0;
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/'));
var server = require('http').Server(app);
var io = require('socket.io')(server);
var map = require("./s_map.js");
var newmap = map.generateMap(100,100);
server.listen(PORT);
console.log("Pirate running on port:"+PORT);
console.log();
io.on('connection', function(socket){
userCnt++;
console.log("New user", socket.id);
allSockets[socket.id] = socket;
allPlayers[socket.id] = {
keys : {},
x : 10,
y : 10
};
socket.on('disconnect', function () {
userCnt--;
delete allSockets[socket.id];
delete allPlayers[socket.id];
console.log("User Disconnected:", socket.id);
});
socket.on('getmap', function () {
//console.log("getmap",newmap);
socket.emit("getmap", newmap);
});
socket.on('keyUp', function (key) {
allPlayers[socket.id]["keys"][key] = false;
});
socket.on('keyDown', function (key) {
console.log(allPlayers);
allPlayers[socket.id]["keys"][key] = true;
});
});
setInterval(function() {
for(var id in allPlayers) {
var player = allPlayers[id];
for(var key in player["keys"]) {
if(player["keys"][key]) { //if key is pressed
var tx = 0;
var ty = 0;
var mvnt = 2;
if(key==37) { //left
tx = -1 * mvnt;
} else if(key==38) { //top
ty = -1 * mvnt;
} else if(key==39) { //right
tx = mvnt;
} else if(key==40) { //bottom
ty = mvnt;
}
player["x"] = player["x"]+tx;
player["y"] = player["y"]+ty;
}
}
}
io.sockets.emit("setpos", allPlayers);
},100);