multiplayer


games 4 people

Web makes it super easy to do multiplayer
Everyone's simultaneously connected to a server!
Previously...

multiplayer basics

  • Central server handles communication
  • Stream player movements/speech
  • Handle security issues (hax!)
  • Lag/latency/etc..

How do we stream via web?

implementation

Native: WebSockets
var ws = new WebSocket("ws://localhost/socket");

ws.onopen = function() { 
    console.log('connected!'); 
    ws.send("hello, socket");
}

ws.onmessage = function (event) {
    console.log('received', event.data);
} 
Easy: Firebase
var chat = new Firebase('https://chat.firebaseIO.com/');

chat.push({name:"Will", text: "Firebase is awesome!"});

chat.on("child_added", function(message) {
    console.log(message.val());
}); 

websockets

Open channel between server and client
New: last two years!

Requires: setting up a server
Node.js, PHP, Golang, etc...

websocket server

Sample Node.js server
var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  socket.emit('greetings', { hello: 'world' });
  socket.on('chat', function (message) {
    socket.broadcast.emit(message)
  });
}); 
Client:
var socket = io.connect('http://localhost');
socket.on('greetings', function (data) {
    console.log(data);
    socket.emit('chat', 'hi server');
}); 

firebase

Luckily, Firebase is super easy.
var fb = new Firebase('https://web-games.firebaseio.com');
fb.push({test: 'data'});
fb.on('child_added', function(child) {
    console.log(child);
}); 

Try it!

exercise: drawing

Draw in real-time! Data format:
{
    color: 'green',
    position: [10, 50]
} 

For example:
document.addEventListener('mousemove', function(e) {
    fb.push({
        color: 'blue',
        position: [e.clientX, e.clientY]
    });
}); 

Week 11: Multiplayer

By Will Crichton

Week 11: Multiplayer

  • 677