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 total count to all users


Perform the following steps to create our foundation logic for the game:

  1. In the server folder, we create a new file named game.js. We will store the room and game logic in this file.

  2. We define a User class that stores the socket connection object and creates a random ID.

    function User(socket) {
      this.socket = socket; 
      // assign a random number to User.
      // Long enough to make duplication chance less.
      this.id = "1" + Math.floor( Math.random() * 1000000000);
    }
  3. We also define a Room class. We store a collection of user instances in this class.

    function Room() {
      this.users = []; 
    }
  4. We define the two instance methods in the Room class that manages the adding and removing of users.

    Room.prototype.addUser = function(user){
      this.users.push(user); 
      var room = this; 
    
      // handle user closing
      user.socket.onclose = function(){
        console.log('A connection left.');
        room.removeUser(user);
      }
    };
    Room.prototype.removeUser = function(user)...