0

I've been browsing this site and the web for answer but cannot find any that really satisfies me.

I'm planing to code a small multiplayer web game based on node.js + socket.io for the back-end. For handling new user I coded this:

io.sockets.on('connection', function(socket)
{
    socket.emit('connected', {message: "you are connected!"});
    var player = new myGame();
}

myGame is a function of my own containing many variables for the game itself (user name, score, money...). My question is how can I have a game engine using data from all the players myGame objects and updating it ? I was thinking of using a global array of myGame objects but then it means that the data is copied twice (in the socket and in the global array).

In C/C++ I would have used pointers or references but JS is a pass-by-value language. Any idea ?

alexislg
  • 1,018
  • 13
  • 20
  • 1
    Javascript is pass by value only for primitives. Take a look here: http://stackoverflow.com/questions/13104494/does-javascript-pass-by-reference – Timothy Strimple Jul 21 '14 at 20:24

1 Answers1

3

You could create a global array of objects mapped to username/socket.id keys. You don't necessarily have to store that data in the socket, do you? Everytime an event occurs, grab the socket.id and event data and send it to the global object. From there, use the global object and socket id to relay any information back to the socket. This will hopefully keep it so what is on the socket is the same as what everyone sees because its all accessing the same data.

HarryH
  • 1,058
  • 7
  • 12