Book Image

HTML5 Game Development by Example: Beginner's Guide

By : Seng Hin Mak
Book Image

HTML5 Game Development by Example: Beginner's Guide

By: Seng Hin Mak

Overview of this book

Table of Contents (18 chapters)
HTML5 Game Development by Example Beginner's Guide Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
9
Building a Physics Car Game with Box2D and Canvas
Index

Time for action – sending the drawing through WebSockets


Carry out the following steps:

  1. First, we need to modify the server logic. Open the game.js file and add two constants at the beginning of the file, as follows:

    // Constants
    var LINE_SEGMENT = 0;
    var CHAT_MESSAGE = 1;
  2. In the Room.prototype.addUser method, add the following code at the beginning of the method:

    this.users.push(user);
    var room = this;
    // tell others that someone joins the room
    var data = {
      dataType: CHAT_MESSAGE,
      sender: "Server",
      message: "Welcome " + user.id 
         + " joining the party. Total connection: " + this.users.length
    };  
    room.sendAll(JSON.stringify(data));
  3. We use JSON-formatted string for communicating both drawing actions and chat messages. Add the following code to the user sockets on the message event handler:

    user.socket.on("message", function(message){
      console.log("Receive message from " + user.id + ": " + message);
      
      // construct the message
      var data = JSON.parse(message);
      if (data.dataType ...