How to use socket to send information between server and client using Javascript?

Viewed 24

I followed an online tutorial to learn how to create a multiplayer online game. I used the concepts from the video to try to build a board game.

Right now people can go to the website, and one person can roll the dice, and the result is broadcasted to everyone who is also on the website. And different people can take turns rolling the dice and the results are always broadcasted to everyone else.

But the problem is when one player is rolling the dice, all the information is shared properly, and the game pieces move around the board. But when the next players rolls, all the pieces are reset to the beginning, as if everything the first players did was forgotten. But if the first players rolls again, that person's rolls (and game pieces) are back, and everything the second person did is forgotten.

If you open the game in two browsers, you will be able to replicate this. Must roll a 6 to get pieces to start moving. http://fs-ludo.herokuapp.com/

Why is this happening and what can I add so that the mechanics is broadcasted and remembered by everyone playing?

Thank you for your help.

<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="gamestyle.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ludo</title>
  </head>
  <body>
    
    <div>
      <!--Title-->
      <h1>Ludo Game</h1>
      
      <form id="chat-form">
        <!--Button-->
        <button onclick="random()">ROLL</button>
        
        <!--Dice-->
        <p id='dice'></p>
      </form>

      <!--Token position-->
      <p id="token_pos"></p>
      
      <p id="turn"></p>
      
      <!--Recent rolls-->
      <p id="rolls"></p>
    </div>
    
    <!--Canvas. The second canvas is used to move the game pieces.-->
    <div>
      <canvas id="board" width="600" height="600" style="position: absolute; z-index: 0;"></canvas>
      
      <canvas id="token" width="600" height="600" style="position: absolute; z-index: 1;"></canvas>
    </div>
    
      <script>
       // Game Logic (which contains class LudoGame)
       // Board (created using canvas)

       var game = new LudoGame();

       // Dice logic
       var rolls = []
       var rounds = []
      
       function random() {
       var list = ['\u2680', '\u2681', '\u2682', '\u2683', '\u2684', '\u2685'];
       var value = list[Math.floor(Math.random() * 6)];
       document.getElementById('dice').value = value;
      
      
       if (value == '\u2680'){
        rolls.push(1);}
       else if (value == '\u2681'){
        rolls.push(2);}
       else if (value == '\u2682'){
        rolls.push(3);}
       else if (value == '\u2683'){
        rolls.push(4);}
       else if (value == '\u2684'){
        rolls.push(5);}
       else if (value == '\u2685'){
        rolls.push(6);}

      var number_of_player = game.set_players = 3;
        
     
      if (number_of_player === 2) {
        if (rounds.length == 0){
          rounds.push(['A', rolls[rolls.length - 1]]);}
        else if (rounds[rounds.length - 1][1] == 6 && rounds[rounds.length - 1][0] === 'A'){
          rounds.push(['A', rolls[rolls.length - 1]]);}
        else if (rounds[rounds.length - 1][1] == 6 && rounds[rounds.length - 1][0] === 'B'){
          rounds.push(['B', rolls[rolls.length - 1]]);}
        else if (rounds[rounds.length - 1][0] == 'B') {
          rounds.push(['A', rolls[rolls.length - 1]]);}
        else if (rounds[rounds.length - 1][0] == 'A') {
          rounds.push(['B', rolls[rolls.length - 1]]);}
      }
        
      else if (number_of_player === 3) {
        if (rounds.length == 0){
          rounds.push(['A', rolls[rolls.length - 1]]);}
        else if (rounds[rounds.length - 1][1] == 6 && rounds[rounds.length - 1][0] === 'A'){
          rounds.push(['A', rolls[rolls.length - 1]]);}
        else if (rounds[rounds.length - 1][1] == 6 && rounds[rounds.length - 1][0] === 'B'){
          rounds.push(['B', rolls[rolls.length - 1]]);}
        else if (rounds[rounds.length - 1][1] == 6 && rounds[rounds.length - 1][0] === 'C'){
          rounds.push(['C', rolls[rolls.length - 1]]);}
        else if (rounds[rounds.length - 1][0] == 'A') {
          rounds.push(['B', rolls[rolls.length - 1]]);}
        else if (rounds[rounds.length - 1][0] == 'B') {
          rounds.push(['C', rolls[rolls.length - 1]]);}
        else if (rounds[rounds.length - 1][0] == 'C') {
          rounds.push(['A', rolls[rolls.length - 1]]);}
      }
        

      
      var game_on; 
      game_on = game.play_game(rounds[rounds.length - 1]);
        
//    Recent rolls  
      if (rounds.length === 1){
        document.getElementById('rolls').value = ["Latest Roll: " + rounds[rounds.length-1]];}
      else if (rounds.length === 2){
        document.getElementById('rolls').value = ["Latest Roll: " + rounds[rounds.length-1], " &nbsp " + rounds[rounds.length-2]];}
      else if (rounds.length === 3){
        document.getElementById('rolls').value = ["Latest Roll: " + rounds[rounds.length-1], " &nbsp " + rounds[rounds.length-2], " &nbsp " + rounds[rounds.length-3]];}
      else if (rounds.length === 4){
        document.getElementById('rolls').value = ["Latest Roll: " + rounds[rounds.length-1], " &nbsp " + rounds[rounds.length-2], " &nbsp " + rounds[rounds.length-3], " &nbsp " + rounds[rounds.length-4]];}
      else {
        document.getElementById('rolls').value = ["Latest Roll: " + rounds[rounds.length-1], " &nbsp " + rounds[rounds.length-2], " &nbsp " + rounds[rounds.length-3], " &nbsp " + rounds[rounds.length-4], " &nbsp " + rounds[rounds.length-5]];}
        

        
      document.getElementById('turn').value = rounds[rounds.length-1];

          
    </script>
        

    <script src="/socket.io/socket.io.js"></script>
    <script src="/client.js"></script>
  </body>
</html>

client.js

const dice_result = (num2) => {
  document.querySelector('#dice').innerHTML = num2;
};

const token_position = (pos) => {
  document.querySelector('#token_pos').innerHTML = pos;
};

const turn = (tur) => {
  if (tur === "Turn: Player A"){
    document.querySelector('#turn').style.color = "orange";
    document.querySelector('#turn').innerHTML = tur;}
  else if (tur === "Turn: Player B"){
    document.querySelector('#turn').style.color = "blue";
    document.querySelector('#turn').innerHTML = tur;}
  else if (tur === "Turn: Player C"){
    document.querySelector('#turn').style.color = "#E37383";
    document.querySelector('#turn').innerHTML = tur;}
};

const roll_result = (num3) => {
  document.querySelector('#rolls').innerHTML = num3;
};

const board = (ct1, ct2, ct3, ct4, ct5, ct6, ct7, ct8, ct9, ct10) => {
    const canvas2 = document.querySelector('#token');
    const ctx2 = canvas2.getContext('2d');
    ctx2.clearRect(0, 0, 600, 600);
    ctx2.font = "20px serif";
    ctx2.fillStyle = "orange";
    ctx2.fillText(ct1[0], ct1[1], ct1[2]);
    ctx2.fillText(ct2[0], ct2[1], ct2[2]);
    if (ct5[0] === "Orange Wins!!"){
      ctx2.fillText(ct5[0], ct5[1], ct5[2]);
      ctx2.fillText(ct6[0], ct6[1], ct6[2]);
      ctx2.fillText(ct7[0], ct7[1], ct7[2]);
      ctx2.fillText(ct8[0], ct8[1], ct8[2]);}
    ctx2.fillStyle = "blue";
    ctx2.fillText(ct3[0], ct3[1], ct3[2]);
    ctx2.fillText(ct4[0], ct4[1], ct4[2]);
    if (ct5[0] === "Blue Wins!!"){
      ctx2.fillText(ct5[0], ct5[1], ct5[2]);
      ctx2.fillText(ct6[0], ct6[1], ct6[2]);
      ctx2.fillText(ct7[0], ct7[1], ct7[2]);
      ctx2.fillText(ct8[0], ct8[1], ct8[2]);}
    ctx2.fillStyle = "#E37383";
    ctx2.fillText(ct9[0], ct9[1], ct9[2]);
    ctx2.fillText(ct10[0], ct10[1], ct10[2]);
    if (ct5[0] === "Pink Wins!!"){
      ctx2.fillText(ct5[0], ct5[1], ct5[2]);
      ctx2.fillText(ct6[0], ct6[1], ct6[2]);
      ctx2.fillText(ct7[0], ct7[1], ct7[2]);
      ctx2.fillText(ct8[0], ct8[1], ct8[2]);}

};


const onClick = (sock) => (e) => {
  e.preventDefault();
  var number2 = document.querySelector('#dice').value;
  var number = document.querySelector('#token_pos').value;
  var number4 = document.querySelector('#turn').value;
  var number3 = document.querySelector('#rolls').value;

  sock.emit('dice_output', number2);
  sock.emit('roll', number3);

  
  if (number4[0] === 'A' && number4[1] === 6){
    sock.emit('player_turn',  "Turn: Player A");}
  else if (number4[0] === 'B' && number4[1] === 6){
    sock.emit('player_turn',  "Turn: Player B");}  
  else if (number4[0] === 'C' && number4[1] === 6){
    sock.emit('player_turn',  "Turn: Player C");}  
  else if (number4[0] === 'A' && number4[1] != 6){
    sock.emit('player_turn', "Turn: Player B");}
  else if (number4[0] === 'B' && number4[1] != 6){
    sock.emit('player_turn',  "Turn: Player C");}
  else if (number4[0] === 'C' && number4[1] != 6){
    sock.emit('player_turn',  "Turn: Player A");}

  
  // Here I have the logic for displaying the token in canvas2. The var are emitted  //below. Then used in the function board above. I omitted this portion because it is //long, but I can provide it if necessary. 
  sock.emit('sq', ap, aq, bp, bq, win1, win2, win3, win4, cp, cq);
  
};


(() => {
  
const sock = io();

  
sock.on('sq', board);
sock.on('dice_output', dice_result);

sock.on('roll', roll_result);
sock.on('player_turn', turn)


document
  .querySelector('#chat-form')
  .addEventListener('submit', onClick(sock));
  
})();

server.js

const http = require('http');
const express = require('express');
const app = express();
const socketio = require('socket.io');
const port = process.env.PORT || 8080


const clientPath = '$(...dirname)/../client';


app.use(express.static(clientPath));

const server = http.createServer(app);

const io = socketio(server);

io.on('connection', (sock) =>{

  sock.on('dice_output', (num2) => io.emit('dice_output', num2));
  sock.on('position', (pos) => io.emit('position', pos));
  sock.on('player_turn', (tur) => io.emit('player_turn', tur));
  sock.on('roll', (num3) => io.emit('roll', num3));
  
  sock.on('sq', (ct1, ct2, ct3, ct4, ct5, ct6, ct7, ct8, ct9, ct10) => io.emit('sq', ct1, ct2, ct3, ct4, ct5, ct6, ct7, ct8, ct9, ct10));
  
});

server.on('error', (err) =>{
  console.error('Server error:', err);
});

server.listen(port, () => console.log("Working"))
1 Answers

The computers are doing what you told them to.

Every time a client does a turn (I didn't see where onClick is called, but I assume it does get called), it sends the board variables to the server with 'sq'. Every time the server receives 'sq' it sends 'sq' to all clients. Every time a client receives 'sq', it updates all the stuff on the screen depending on the variables it received. This is what you told the client and server to do.

When player 1 rolls the dice, all the information from player 1's client is broadcasted to everyone and appears on everyone's screen. When player 2 rolls the dice, all the information from player 2's client is broadcasted to everyone and appears on everyone's screen. This is a completely separate set of information.

If this isn't what you want, you have to tell the computer to do what you want - I can't be more specific since I don't know what you want.

Related