5.) MMO From Scratch - Players

Results 1 to 1 of 1
  1. #1
    :-) s-p-n is offline
    DeveloperRank
    Jun 2007 Join Date
    Next DoorLocation
    2,148Posts

    5.) MMO From Scratch - Players


    RaGEZONE Recommends

    RaGEZONE Recommends

    Previous (The Client)
    Table of Contents (Introduction)
    Next (Players 2)

    I already briefly went over the login/content serving system in a previous tutorial. If you aren't familiar with that, I suggest going through that before moving on.

    I'm not going into the code for login/register here. If you want to skim through the code on github, I'd encourage that. Just know that when a user registers, the data stored is an object formatted like this:
    Code:
    {
       username: <string>,
       password: <hashString>,
       key: <hashString || boolean:False>,
       game: <object> {x: <number>, y: <number>, ...}
    }
    At this point, I'm only going to set up 4 commands for walking - up, down, left, right. The client will send these commands to the server, and the server will determine if it those commands are reasonable enough to consider legitimate, and if so, execute those commands and broadcast the game state to the player who sent those commands. The server broadcasts changes to game-state to every player.

    So, I'll start with a file: /private/channels/player.js.

    Here are some commands we might want to execute:
    Code:
    var exec = {
        up: function (player) {
            player.game.y -= 7.5;
        },
        down: function (player) {
            player.game.y += 7.5;
        },
        left: function (player) {
            player.game.x -= 7.5;
        },
        right: function (player) {
            player.game.x += 7.5;
        }
    };
    Whenever a command is executed, Server is going to make assumptions after some simple verification that the command will execute successfully. Server will simultaneously update the database, and broadcast the changed state to all of the players. If for whatever reason Server was wrong or the database didn't accept the change, Server will broadcast another state to the clients. Note that any state the clients receive is in the past. This is one of the most challenging points we have to work with in regards to multiplayer game development over the internet.

    So let's get started with this player channel. The player can be in one of four different states-
    1. not logged in and game not ready (just entered site)
    2. not logged in but game ready (logged out of game)
    3. logged in but game not ready (just hit the log-in button and was successfully logged in, game initializing)
    4. logged in and game ready (playing the game)

    We want the transitions to/from these states to be as seamless as possible. Here's how we're going to respond to these different states:
    1. Display a login form.
    2. Remove session (server- done automatically when socket connection lost), clear cookie (client), refresh web-browser (also clears session by losing socket connection- transition to state 1).
    3. Initialize game (client) and send gameReady message to server, server responds with initial game state specific for the player. Transition to state 4.
    4. Periodically send game state updates to the player, and listen for commands from the player (server). Listen to UI events like mouse/keyboard/gamepad from player, send commands to server (client).


    So, first and foremost, to handle the the content-sending process on the server, we'll send the login form right away if there's no sessionID cookie. Also, we'll listen on the logged_in event, and if we get a true- indicating a successful login, we'll send the game. If we get false- indicating an unsuccessful login attempt, we'll send the login form again.

    Here is /private/channels/game.js:
    Code:
    var content = {
        login: null,
        game: null
    }
    
    module.exports = function (m, session) {
        var socket = session.socket;
        function sendLoginForm() {
            socket.emit("content", {
                selector: "#canvas",
                html: content.login || (content.login = m.fs.readFileSync(m.root + '/protected/login.html', 'utf8'))
            });
        }
        function sendGame() {
            socket.emit("content", {
                selector: "#canvas",
                html: content.game || (content.game = m.fs.readFileSync(m.root + '/protected/game.html', 'utf8'))
            });
        }
        if (!socket.request.cookies.sessionID) {
            sendLoginForm();
        }
    
        session.event.on("logged_in", function (success) {
            if (success === true) {
                sendGame();
            } else {
                sendLoginForm();
            }
        });
    }
    That should fulfill the server's responsibility in handling states 1 through 3- at least as far as content is concerned. The login/register channels handle the rest of those 3 responsibilities.

    I'll hold-off on handling the logout functionality- but that's almost entirely handled on the client. The server should handle step 2 pretty much automatically as long as the client does it's job. I'm not concerned if a cheater winds up in a fucked up game-state by changing the client code- I can't really prevent that. I just want to be sure it won't give the cheater any advantage.

    I want to concentrate on State 4 for the rest of this tutorial.

    Before we can do anything, we must set up a database. To do that, create a folder named /data and execute the following command in a terminal to start the database. The first time you run this, it will take a while as MongoDB must initialize the database. Please use MongoDB 3.x if you're following along with this tutorial.
    Code:
    mongod --dbpath data
    For best results, have mongo running before starting the node.js server.

    If you were successful starting your MongoDB instance, this should be the last message you see:
    Code:
    [initandlisten] waiting for connections on port 27017
    If your port is intentionally different than the default port 27017, you'll have to change some code in /private/extensions/db.js for your connection to be established.

    Once you have the database set up, you should be able to run the server and create a test account.

    You should get a message when logging in for the first time saying,
    Code:
    Unable to find user, <username>.
    Create it?
    Clicking the link will immediately create the user, and you can log-in with that username/password in the future. After clicking that link, the server will send /protected/game.html which has the following code:
    Code:
    <script>
    if (window.gameObj === void 0) {
        window.gameObj = {};
    } else {
        window.location = "/";
    }
    console.log(gameObj);
    initializeGame(gameObj);
    </script>
    The above code checks if the gameState is already active, if it is, it refreshes the browser to prevent duplicate game instances running at the same time. This situation may arise from the server restarting, which I've observed result in strange things happening. A different solution could be made very complex by stubbornly not refreshing the browser, but I find this to be the easiest catch-all solution.

    Back to the player!

    Here is the code from /private/channels/player.js:
    Code:
    var exec = {
        up: function (player) {
            player.game.y -= 7.5;
        },
        down: function (player) {
            player.game.y += 7.5;
        },
        left: function (player) {
            player.game.x -= 7.5;
        },
        right: function (player) {
            player.game.x += 7.5;
        }
    };
    
    module.exports = function (m, session) {
        var socket = session.socket;
        var player;
        var intervalTime = 100;
        var lastCmdTime = 0;
    
        function updatePlayer () {
            m.db.users.update({
                'username': player.username
            }, {
                $set: {game: player.game}
            }, {multi: false});
            m.event.emit('player-update', player);
        }
    
        function initPlayer () {
            var userId, other;
            socket.emit('player', {username: player.username, game: player.game});
            for (userId in m.session) {
                if (userId === session.id || m.session[userId].user === void 0) {
                    continue;
                }
                other = m.session[userId].user;
                socket.emit('others-update', {username: other.username, game: other.game});
            }
        }
        session.event.on('logged_in', function (result) {
            if (result === true) {
                player = session.user;
            }
        });
    
        socket.on('game-ready', function () {
            if (player) {
                initPlayer();
            } else {
                session.event.on('logged_in', function (result) {
                    if (result === true) {
                        initPlayer();
                    }
                });
            }
        });
        socket.on('player-input', function (data) {
            var now = Date.now();
            var lag = now - data.time;
            var cmd = data.action;
    
            console.log('cmd:', cmd, 'lag:', lag, 'step:', data.step);
            if (cmd in exec) {
                if ((lastCmdTime + intervalTime) > now) {
                    console.log("Client moving too fast!", lastCmdTime, now);
                } else if (isNaN(lag) || lag < 0) {
                    console.log("Client supplied invalid lag data!", data.lag);
                else {
                    exec[cmd](player);
                }
                lastCmdTime = now;
                
                socket.emit('player-move', {game: player.game, time: now - lag, step: data.step});
                updatePlayer();
            } else if (cmd === 'still') {
                //m.event.emit('player-update', player);
            }
        });
    }
    There's a lot going on here, I'll go through it step-by-step.

    First, we declare some variables.

    • socket - the client's socket connection data. It belongs to one client only.
    • player - the player for this socket.
    • intervalTime - The minimum amount of time there should be between client commands.
    • lastCmdTime - The last time a command was received.


    We have 2 helper functions, the first is updatePlayer. updatePlayer will update the DB with the user's game-state, and without waiting for confirmation, emit a 'player-update' event on the main variable. In laymen's terms, updatePlayer will not wait for the database to say the command was successful- it will just shout out and tell all the other players that this player's game-state has changed, and give them that changed data. This is optimistic to say the least, but we get a more responsive game this way- and the client's commands are usually executed successfully, anyway.

    Then we have initPlayer. This function will tell the player's client who (s)he is. It will also tell the player about other connected players.

    After those 2 helper functions, we have 3 socket listeners.

    The first listens for 'logged_in' for this session. Once this client successfully logs in, we assign the player variable documented above, to the logged in user.

    The second listens for the client to shout, 'game-ready'. When the client does that, we check if the player exists, and if not, we listen on for the server to shout 'logged_in' for this session. After either case, we invoke initPlayer().

    The third listens for the client to shout 'player-input'. Spoiler: This is the fun part.

    We start with 3 variables:
    • now - the current time.
    • lag - the time the client sent the request subtracted by the current time.
    • cmd - the command the client wants Server to execute.

    We're in development, so we log everything the client sends us.
    If the command sent from the client is a command Server recognizes, we go further, otherwise we ignore this request.
    If the time between commands is invalid, Server doesn't execute the command,
    If the lag variable is invalid, Server doesn't execute the command.
    Otherwise, server does execute the command, and the game-state is changed.
    After those checks, Server sets the lastCmdTime to the current time, and tells this client the current game-state, and then executes updatePlayer(). The client uses the step it gave us to determine if it needs to fix the player's game-state or not. In the end, we should be able to, on the client, use this system to implement some lag compensation.

    Now, before I go further I want to point out a bug in the above steps. That is the "Client moving too fast!", when in fact the client is acting legitimate. The 100ms delay on the client is flawed if, a bunch of commands are stacked up in the pipeline during a delay in internet connectivity, and the server receives several commands at once which were sent 100ms apart. We'll probably visit this code in the future to attempt and fix this bug, but to prevent cheating, we'll just let it be as-is.

    In the next tutorial, we'll visit the player on the client- and we'll be able to see our character moving around the world.

    Previous (The Client)
    Table of Contents (Introduction)
    Next (Players 2)
    Last edited by s-p-n; 29-01-16 at 10:01 PM.





Advertisement