Search code examples
javascriptwebsocketreal-time2d-gamesenchantjs

2D multiplayer game real-time comunication JavaScript


I am programming a multi-player game with JavaScript and html. For this objective I need communication between the players. How can I manage this?

My code:

    enchant();
    window.onload = function() {
    var game = new Game(320, 320);

Here my first question: It should be counted how many player is that now, who entered the room last. Then a number should be assigned to this player. I´d like to solve this with a function.

    var my_bear = get_player_number();

    game.preload('chara1.gif');
    game.fps=15;
    var bears = [];
    game.onload = function() {
        var ix;
        var bear;
        for (ix = 0; ix < 5; ix++) {
            bear=new Sprite(32, 32);
            bear.image = game.assets['chara1.gif'];
            bear.frame = 4;
            bear.x=Math.random()*300;
            bear.y=Math.random()*300;
            game.rootScene.addChild(bear);
            bears.push(bear);
        }
    };
    game.start();
    var addit=6;
    document.addEventListener('keyup',function (evt) {
        if(evt.keyCode == 38){bears[my_bear-1].y-=addit;}
        if(evt.keyCode == 39){bears[my_bear-1].x+=addit;}
        if(evt.keyCode == 40){bears[my_bear-1].y+=addit;}
        if(evt.keyCode == 37){bears[my_bear-1].x-=addit;}
    });
}

Due to this simplification of my programme you have 5 bears. One of them you can control with the arrow-keys (the bear with the value of the variable “my_bear”).

But it´s still a single-player game yet...

init_other_players(my_bear);

A function would be perfect, which detects and indicates any movement of a player on an other computer. Webspace an two domains are available for my programme.



I´m very looking forward to your helpful answer, thank you !!!


Solution

  • First, if you want multiplayer, you need something to manage the rooms and such, so you need a server. For games, I'd suggest NodeJS. Node is a server app built in JS, so a language you are familiar with. You don't need to know too much about node for now, simply running it will be enough while you progress on your code, after that I'd say you should look a bit more into it.

    After, I'd look into Socket.io which lets you manage your websockets and therefore communication between the users and the server. There are tutorials about a chat in the Get Started section of the website which will you let you know the basics of communication between users.

    From there you can create the logic for your rooms and the rest of your game! It may look like a lot to learn but, honstly, it's well explained and quite easy to get a grasp of.