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 mapWidth = 100; var mapHeight = 100; var maxX = mapWidth * 32; var maxY = mapHeight * 32; var newmap = map.generateMap(mapWidth,mapHeight); var cssMap = newmap["cssMap"]; var map = newmap["map"]; var utilMap = newmap["utilMap"]; var defaultMvnt = 2; 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, mvnt : defaultMvnt }; io.sockets.emit("newPlayer", { player : allPlayers[socket.id], id : socket.id }); socket.on('disconnect', function () { userCnt--; delete allSockets[socket.id]; delete allPlayers[socket.id]; console.log("User Disconnected:", socket.id); io.sockets.emit("playerDisc", 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) { 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 = player["mvnt"]; 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; } var newX = player["x"]+tx; var newY = player["y"]+ty; var groundUnderPlayer = getGroundUnderPlayer(newX, newY); if(checkPlayerPosition(newX, newY, groundUnderPlayer)) { player["x"] = newX; player["y"] = newY; player["mvnt"] = getPlayerMvnt(groundUnderPlayer); console.log(player["mvnt"], groundUnderPlayer); } } } } io.sockets.emit("setpos", allPlayers); },20); function checkPlayerPosition(newX, newY, groundUnderPlayer) { if(newX <0 || newY<0 || newX > maxX || newY > maxY) { return false; } if(groundUnderPlayer < 0 || groundUnderPlayer > 2) { return 0; } return true; } function getGroundUnderPlayer(newX, newY) { //0 = water; 10 = hard ground var mapX = Math.floor(newX/32); var mapY = Math.floor(newY/32); var ground = cssMap[mapY][mapX]; var groundSplit = ground.split("_"); if(groundSplit.length != 2) { if(ground == "water") { return 0; } return 10; //Ground } return parseFloat(groundSplit[1]); } function getPlayerMvnt(groundUnderPlayer) { if(groundUnderPlayer===1) { return 0.5; } else if(groundUnderPlayer===2) { return 0.1; } return defaultMvnt; }