Skip to content

Instantly share code, notes, and snippets.

@hunterloftis
Created February 7, 2011 15:25
Show Gist options
  • Save hunterloftis/814531 to your computer and use it in GitHub Desktop.
Save hunterloftis/814531 to your computer and use it in GitHub Desktop.
io.setPath('/js/socketio-client/');
var socket = new io.Socket(null, {port: 100}),
game = ko.model(),
input = ko.model({
command: ko.observable('')
}),
canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
commands = {
37: 'left',
38: 'up',
39: 'right',
40: 'down'
};
// The first time we pull game data, start the redraw loop
game.on('firstFetch', function() {
(function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
var ball = game.ball.toObject();
ctx.translate(ball.x, ball.y);
ctx.fillStyle('#fff');
ctx.arc(0, 0, ball.r, 0, Math.PI * 2);
ctx.fill();
window.setTimeout(update, 20);
})();
});
// Listen for keyboard input and add to commands
$(document).bind('keydown', function(event) {
if (commands[event.which]) {
input.command(commands[event.which]);
}
})
// Synchronize data with the server
socket.on('message', function SyncUp(data) {
if (data.type === 'sync') {
game.sync(data.game_id, socket, 'r');
input.sync(data.input_id, socket, 'w');
socket.removeEvent('message', SyncUp);
}
})
socket.on('connect', function RequestSync() {
socket.send({type: 'sync'});
})
socket.connect();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment