Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Welcome player one\!

  • Loading branch information...
commit 446df19f0da2e2d4b4b9547e38b83326f6bda45e 1 parent 0116e95
@squaremo authored
Showing with 51 additions and 2 deletions.
  1. +49 −2 app.js
  2. +2 −0  public/index.html
View
51 app.js
@@ -1,11 +1,58 @@
var express = require('express'),
-server = express.createServer();
+sockjs = require('sockjs');
+
+function debug(msg) {
+ console.log(msg);
+}
+
+var server = express.createServer();
server.configure(
function() {
server.use(express.static(__dirname + '/public'))
});
-// Fight!
+var socks = sockjs.createServer();
+socks.installHandlers(server, {prefix:'/socks'});
+
+socks.on('connection', function(conn) {
+ initPlayer(conn);
+});
+
+function initPlayer(connection) {
+ connection.on('data', function(msg) {
+ connection.removeAllListeners('data');
+ var player = new Player(connection, msg);
+ debug("Welcome player " + player.info.name);
+ makeMatches(player);
+ });
+}
+function Player(conn, name) {
+ this.info = {name: name, wins: 0};
+ this.connection = conn;
+}
+
+var queue = [];
+function makeMatches(player) {
+ queue.push(player);
+ attemptMatches();
+}
+
+function attemptMatches() {
+ if (queue.length > 1) {
+ var player1 = queue.shift();
+ var player2 = queue.shift();
+ gameOn(player1, player2);
+ attemptMatches();
+ }
+}
+
+function gameOn(player1, player2) {
+ debug("Matching " + player1.info.name + " with " + player2.info.name);
+ player1.connection.write(JSON.stringify({start: player2.info}));
+ player2.connection.write(JSON.stringify({start: player1.info}));
+}
+
+// Fight!
server.listen(process.env['VCAP_APP_PORT'] || 3000);
View
2  public/index.html
@@ -1,5 +1,7 @@
<html>
<head>
+ <script src="http://cdn.sockjs.org/sockjs-0.3.min.js">
+ </script>
</head>
<body>
<h1>Ponk!</h1>
Please sign in to comment.
Something went wrong with that request. Please try again.