user3928524
user3928524

Reputation:

How To Change the turn in chessboard.js?

I am working in chessboard.js for creating a multyplayer chessboard using signalR. but i am having a problem in player movement.

what i am doing is sending the FEN string from client1 to client2.and Thus client2 represent that FEN string on board. Now the problem is that the player2 represent the FEN on Board but player turn is not changed by FEN. So both Player 1 and 2 move white first then black secondly.and that is not to be supposed.

i want Player1 moves from white side.His FEN is send To Player2.then Player2 will Move with Black Color (but currently player2 move with white which is error). So please help me how to change the turn of player1 or player2 forcely.

enter image description here

Upvotes: 4

Views: 3079

Answers (1)

mike510a
mike510a

Reputation: 2168

I was struggling with the same issue when creating a similar multiplayer chess game using chessboard.js along with chess.js (the engine running the actual game rules)

The answer lies within the chess.js file that is referenced on the chessboard.js api documentation.

Line 157 of chess.js has this:

   var turn = WHITE;

If you wish to change the turn of the whole game you can simply do this:

turn = BLACK;
turn = WHITE;
turn = "w";
turn = "b";

Any of them will work. I also created a convenience function that can be more easily used by other scripts which adds setTurn() and turn() to the public API..


Convenience function to add to API for turn manipulation:


Around line 1115 of chess.js (not chessboard.js), you will find a function that starts off with:

return {
/***************************************************************************
 * PUBLIC CONSTANTS (is there a better way to do this?)
 **************************************************************************

I simply added The following to right below the comment:

turn: function() {
   return turn;
},
setTurn: function(newTurn) {
    turn = newTurn;
},

The result is that now from either any instance of chess.js (default name is game), you can simply change turns like this:

game.setTurn("b");
game.setTurn("w");

This is but one hurdle that I ran into while making a multiplayer version. The next hurdle you will likely face is going to be: what happens if a player gets disconnected or doesn't respond? How about if they inject a JS file into the page that allows them to change turns at will? These issues will be more of a pain to solve. Also look out for other types of injection attacks such as manipulation of the game FEN externally.

Good luck!

Leave comment if you want me to share my source code -- I figured out most of the issues that come up with chessboard.js as multiplayer.

Upvotes: 4

Related Questions