6

im really downhearted, i cant solve this, im trying it since days, im developing a game (tic tac toe) it has multiplayer feature using nodeJS, also the problem is not the game, the problem is handling different rooms...

Im using socket.join etc, so user can join different room; to join different games also boards i pass through url game name, example:

localhost?gameId=test

Then i parse this name and start sending board to these users. Also the problem is, when i have more then one more, the game collapses, also the board info from room 1 collapse with room 2... i cant find the error, i paste the code here:

Create.html jsfiddle.net/svaae1vL/

Enter.html jsfiddle.net/6qzbpbxx/

Server.js jsfiddle.net/1q0qo8xo/

Like i sayd before, the problem is:

room1: player1, player2 room2: player3, player4

room1:
[x,o,x]
[0, 0, 0]
[x,x,x]

room2:
[x,o,x]
[0, 0, 0]
[x,x,x]

Also when i click in room1, it affects room2, please help im stuck since days...

Dygestor
  • 1,259
  • 1
  • 10
  • 20
redigaffi
  • 429
  • 6
  • 22

2 Answers2

2

I believe your problem is that you are sharing variable emptyBoard in createRoom event:

boards[data.name] = emptyBoard;

Therefore, if you edit one board, it will edit all the others too. Try changing the assignment to:

boards[data.name] = emptyBoard.slice(0);

That should clone the array into another object.

Edit:

Cloning the array with slice(0) won't clone objects in the array, so perhaps what you need is deep cloning, e.g. as described here.

Community
  • 1
  • 1
Dygestor
  • 1,259
  • 1
  • 10
  • 20
0

@Dygestor

Hey thank you so much, well, this line:

boards[data.name] = emptyBoard.slice(0);

Haven't fixed it, but the problem was what you sayd, so i tried this:

    // Initalize board.
    boards[data.name] = [
                ['', '', ''],
                ['', '', ''],
                ['', '', '']
            ];

And it worked, thank you so much!

redigaffi
  • 429
  • 6
  • 22
  • 1
    As I mentioned in the edit, using 'slice' won't be enough, since your array contains other arrays and slice does not perform deep cloning. Anyway, I'm glad it worked out. – Dygestor Apr 28 '15 at 14:02