added lobby, nickname fixes #44, channel name

This commit is contained in:
Jeena 2014-02-25 00:55:16 +01:00
parent aa4535cb0c
commit da913c4709
10 changed files with 285 additions and 68 deletions

View file

@ -1,16 +1,18 @@
define([ define([
'http', 'http',
'node-static' 'node-static',
'Lobby/Api'
], ],
function (http, nodeStatic) { function (http, nodeStatic, Api) {
function HttpServer (options) { function HttpServer (options, coordinator) {
options.port = options.port || 1234; options.port = options.port || 1234;
options.caching = typeof options.caching != 'undefined' ? options.caching : 3600; options.caching = typeof options.caching != 'undefined' ? options.caching : 3600;
options.rootDirectory = options.rootDirectory || './'; options.rootDirectory = options.rootDirectory || './';
this.server = null; this.server = null;
this.api = new Api(coordinator);
this.init(options); this.init(options);
} }
@ -23,23 +25,29 @@ function (http, nodeStatic) {
this.server = http.createServer( this.server = http.createServer(
function (req, res) { function (req, res) {
req.addListener('data', function() { // doesn't work on Jeenas computer without this var fullBody = '';
//console.log("data") req.addListener('data', function(chunk) { // doesn't work on Jeenas computer without this
fullBody += chunk.toString();
}); });
req.addListener('error', function(err) { req.addListener('error', function(err) {
console.log(''); console.log('');
}); });
req.addListener('end', function () { req.addListener('end', function () {
switch(true) { switch(true) {
case req.url == '/': case req.url == '/':
fileServer.serveFile('./static/html/index.html', 200, {}, req, res); fileServer.serveFile('./static/html/index.html', 200, {}, req, res);
console.checkpoint('HTTP Server serves index'); console.checkpoint('HTTP Server serves index');
break; break;
case req.url == '/game.html':
fileServer.serveFile('./static/html/game.html', 200, {}, req, res);
console.checkpoint('HTTP Server serves game');
break;
case req.url == '/client.js': case req.url == '/client.js':
fileServer.serveFile('./client.js', 200, {}, req, res); fileServer.serveFile('./client.js', 200, {}, req, res);
break; break;
@ -52,6 +60,13 @@ function (http, nodeStatic) {
fileServer.serveFile('./node_modules/screenfull/dist/screenfull.js', 200, {}, req, res); fileServer.serveFile('./node_modules/screenfull/dist/screenfull.js', 200, {}, req, res);
break; break;
case req.url == '/api':
self.api.handleCall(fullBody);
var status = self.api.isError ? 400 : 200;
res.writeHead(status, {"Content-Type": self.api.getContentType()});
res.end(self.api.getOutput());
break;
case new RegExp(/^\/app/).test(req.url): case new RegExp(/^\/app/).test(req.url):
fileServer.serve(req, res, function () { fileServer.serve(req, res, function () {
self.handleFileError(res) self.handleFileError(res)

View file

@ -34,7 +34,12 @@ function (ProtocolHelper, GameController, User, NotificationCenter, Settings, Do
Networker.prototype.onConnect = function () { Networker.prototype.onConnect = function () {
console.log('connected.') console.log('connected.')
this.sendCommand('join', 'dungeon'); var channel = JSON.parse(localStorage["channel"]);
if(channel.name) {
this.sendCommand('join', channel.name);
} else {
window.location.href = "/";
}
} }
Networker.prototype.onDisconnect = function () { Networker.prototype.onDisconnect = function () {
@ -45,6 +50,7 @@ function (ProtocolHelper, GameController, User, NotificationCenter, Settings, Do
} }
Networker.prototype.onJoinSuccess = function (options) { Networker.prototype.onJoinSuccess = function (options) {
console.log("join success")
this.userId = options.userId; this.userId = options.userId;
this.gameController = new GameController(); this.gameController = new GameController();

52
app/Lobby/Api.js Normal file
View file

@ -0,0 +1,52 @@
define([
"Lib/Utilities/NotificationCenter",
"Lib/Utilities/Protocol/Helper"
],
function (NotificationCenter, ProtocolHelper) {
function Api(coordinator) {
this.coordinator = coordinator;
this.isError = false;
this.output = null;
}
Api.prototype.handleCall = function(queryParameters) {
var command;
try {
var message = JSON.parse(queryParameters);
command = message.command;
} catch(e) {
console.error(e)
}
var output = null;
switch(command) {
case "getChannels":
output = this.coordinator.getChannels();
break;
default:
this.isError = true;
output = "Command not found";
break;
}
this.output = output;
}
Api.prototype.getOutput = function() {
var output = {};
var key = this.isError ? "error" : "success";
output[key] = this.output;
return JSON.stringify(output);
};
Api.prototype.getContentType = function() {
return "application/json";
};
return Api;
});

View file

@ -92,6 +92,16 @@ function (User, Channel, PipeToChannel, NotificationCenter) {
return channelPipe; return channelPipe;
}; };
Coordinator.prototype.getChannels = function(options) {
var list = [];
for (var channelName in this.channelPipes) {
list.push({
name: channelName
});
}
return list;
};
return Coordinator; return Coordinator;
}); });

View file

@ -13,6 +13,7 @@ function (NotificationCenter, childProcess) {
try { try {
this.channelPipe = fork('channel.js'); this.channelPipe = fork('channel.js');
console.log(this.channelPipe)
} catch (err) { } catch (err) {
throw 'Failed to fork channel! (' + err + ')'; throw 'Failed to fork channel! (' + err + ')';
} }

View file

@ -21,10 +21,6 @@ function (Parent, ProtocolHelper, NotificationCenter) {
User.prototype = Object.create(Parent.prototype); User.prototype = Object.create(Parent.prototype);
User.prototype.setChannelProcess = function (channelProcess) {
this.channelProcess = channelProcess;
}
// Socket callbacks // Socket callbacks

View file

@ -27,7 +27,7 @@ function (Networker, SocketIO, Settings, Exception, PIXI) {
"flashsocket" "flashsocket"
] ]
}; };
var socket = SocketIO.connect(location.href, options); var socket = SocketIO.connect("/", options);
var networker = new Networker(socket); var networker = new Networker(socket);
inspector.networker = networker; inspector.networker = networker;
inspector.settings = Settings; inspector.settings = Settings;

View file

@ -28,7 +28,7 @@ requirejs([
function (HttpServer, Socket, Coordinator) { function (HttpServer, Socket, Coordinator) {
var coordinator = new Coordinator(); var coordinator = new Coordinator();
var httpServer = new HttpServer(options); var httpServer = new HttpServer(options, coordinator);
var socket = new Socket(httpServer.getServer(), options, coordinator); var socket = new Socket(httpServer.getServer(), options, coordinator);
inspector = { inspector = {

61
static/html/game.html Executable file
View file

@ -0,0 +1,61 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Chuck</title>
<style>
html, body {
margin: 0;
padding: 0;
display: table;
width: 100%;
height: 100%;
background: black;
color: white;
font-family: monospace;
}
#canvasContainer {
/*
text-align: center;
display: table-cell;
vertical-align: middle;
*/
height: 100%;
}
canvas {
position: absolute;
top: 50%;
left: 50%;
margin-top: -200px;
margin-left: -300px;
}
:-webkit-full-screen {
top: 0;
left: 0;
margin: 0;
padding: 0;
}
#devtools {
position: absolute;
right: 0;
top: 0;
padding: 10px;
background: #222;
}
#devtools p {
padding: 5px 0 0 0;
margin: 0;
}
</style>
</head>
<body>
<div id="canvasContainer"></div>
<script data-main="client" src="require.js"></script>
</body>
</html>

168
static/html/index.html Executable file → Normal file
View file

@ -1,61 +1,137 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <title>Chuck Lobby</title>
<title>Chuck</title> </head>
<style> <body>
html, body { <form action="game.html" method="POST">
margin: 0; <p>
padding: 0; <label>
display: table; Nickname:<br>
width: 100%; <input id="nick" name="nick" type="text">
height: 100%; </label>
background: black; </p>
color: white;
font-family: monospace; <table>
<thead>
<tr><th>Name</th></tr>
</thead>
<tfoot>
<tr>
<td>
<label>
<input type="radio" name="channel" id="radiochannel" checked>
custom channel: <input id="customname">
</label>
</td>
</tr>
</tfoot>
<tbody id="list"></tbody>
</table>
<p>
<button>Join</button>
<button id="refresh">Refresh list</button>
</p>
</form>
<script>
function $(selector) {
return document.querySelector(selector);
} }
#canvasContainer { if(localStorage["player"]) {
/* var player = JSON.parse(localStorage["player"]);
text-align: center; if(player.nickname) {
display: table-cell; $("#nick").value = player.nickname;
vertical-align: middle; }
*/
height: 100%;
} }
canvas { $("#customname").onfocus = function() {
position: absolute; $("#radiochannel").checked = true;
top: 50%;
left: 50%;
margin-top: -200px;
margin-left: -300px;
} }
:-webkit-full-screen { if(localStorage["channel"]) {
top: 0; var channel = JSON.parse(localStorage["channel"])
left: 0; if(channel.customname) {
margin: 0; $("#customname").value = channel.customname;
padding: 0; }
} }
#devtools { var hash = window.location.hash.split("#").join("");
position: absolute; if(hash) {
right: 0; $("#customname").value = hash;
top: 0; $("#radiochannel").checked = true;
padding: 10px;
background: #222;
} }
#devtools p { function refresh() {
padding: 5px 0 0 0; $("#list").innerHTML = "";
margin: 0; var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
if(xhr.status == 200) {
populate(JSON.parse(xhr.responseText).success);
} else {
console.error("Ajax error: " + xhr.status + " " + xhr.statusText)
}
}
}
xhr.open("POST", "/api", true);
xhr.send(JSON.stringify({command:"getChannels"}));
return false
} }
</style> function populate(list) {
</head> var html = "";
<body> for (var i = 0; i < list.length; i++) {
<div id="canvasContainer"></div> var channel = list[i];
<script data-main="client" src="require.js"></script> html += "<tr><td><label>";
</body> html += "<input name='channel' type='radio' value='" + channel.name + "'"
if(!hash && i == 0) html += " checked"
html += "> ";
html += channel.name
html += "</label></td></tr>";
};
$("#list").innerHTML = html;
}
$("form").onsubmit = function(e) {
var nickname = $("#nick").value;
if(!nickname || nickname.length < 3) {
alert("nickname too short")
return false;
}
localStorage["player"] = JSON.stringify({nickname: nickname});
if ($("#radiochannel").checked) {
var name = $("#customname").value;
if(name) {
$("#radiochannel").value = name;
} else {
alert("custom channel empty")
return false;
}
} else {
var radios = document.querySelectorAll("form input[name=channel]");
for (var i = 0; i < radios.length; i++) {
var radio = radios[i];
if(radio.checked) {
name = radio.value;
break;
}
};
}
if(name) {
localStorage["channel"] = JSON.stringify({
name: name,
customname: $("#customname").value
});
} else {
alert("no channel selected")
return false;
}
}
$("#refresh").onclick = refresh;
refresh();
</script>
</body>
</html> </html>