replaced all tabs with 4 spaces

This commit is contained in:
logsol 2012-07-28 13:26:05 +02:00
parent 5d11540c55
commit 26f3d22db7
30 changed files with 1017 additions and 1011 deletions

View file

@ -1,34 +1,34 @@
define([ define([
"Game/Server/Channel", "Game/Server/Channel",
"Game/Server/CoordinatorLink" "Game/Server/CoordinatorLink"
], ],
function(Channel, CoordinatorLink) { function(Channel, CoordinatorLink) {
function ChannelBootstrap(process) { function ChannelBootstrap(process) {
var coordinatorLink = new CoordinatorLink(process); var coordinatorLink = new CoordinatorLink(process);
var channel = null; var channel = null;
process.on('message', function(message) { process.on('message', function(message) {
switch(message){ switch(message){
case 'CREATE': case 'CREATE':
channel = new Channel(coordinatorLink); channel = new Channel(coordinatorLink);
break; break;
case 'KILL': case 'KILL':
channel.destroy(); channel.destroy();
process.exit(0); process.exit(0);
break; break;
default: default:
coordinatorLink.receive(message); coordinatorLink.receive(message);
break; break;
} }
}); });
} }
return ChannelBootstrap; return ChannelBootstrap;
}); });

View file

@ -1,15 +1,15 @@
define([ define([
"Game/Client/Networker", "Game/Client/Networker",
"Lib/Vendor/SocketIO" "Lib/Vendor/SocketIO"
], ],
function(Networker, SocketIO) { function(Networker, SocketIO) {
function Client(location, options) { function Client(location, options) {
this.socket = SocketIO.connect(location, options); this.socket = SocketIO.connect(location, options);
this.networker = new Networker(this.socket); this.networker = new Networker(this.socket);
} }
return Client; return Client;
}); });

View file

@ -1,71 +1,71 @@
define([ define([
'http', 'http',
'node-static' 'node-static'
], ],
function(http, nodeStatic) { function(http, nodeStatic) {
function HttpServer(options) { function HttpServer(options) {
options.port = options.port || 1234; options.port = options.port || 1234;
options.caching = typeof options.caching != 'undefined' ? options.caching : true; options.caching = typeof options.caching != 'undefined' ? options.caching : true;
options.rootDirectory = options.rootDirectory || './'; options.rootDirectory = options.rootDirectory || './';
this.server = null; this.server = null;
this.init(options); this.init(options);
} }
HttpServer.prototype.init = function(options) { HttpServer.prototype.init = function(options) {
var self = this; var self = this;
var fileServer = new nodeStatic.Server(options.rootDirectory, { cache: options.caching }); var fileServer = new nodeStatic.Server(options.rootDirectory, { cache: options.caching });
this.server = http.createServer( this.server = http.createServer(
function(req, res){ function(req, res){
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);
break; 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;
case req.url == '/require.js': case req.url == '/require.js':
fileServer.serveFile('./node_modules/requirejs/require.js', 200, {}, req, res); fileServer.serveFile('./node_modules/requirejs/require.js', 200, {}, req, res);
break; 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)
}); });
break; break;
case new RegExp(/^\/static/).test(req.url): case new RegExp(/^\/static/).test(req.url):
fileServer.serve(req, res, function(){ fileServer.serve(req, res, function(){
self.handleFileError(res) self.handleFileError(res)
}); });
break; break;
default: default:
self.handleFileError(res); self.handleFileError(res);
break; break;
} }
}); });
} }
); );
this.server.listen(options.port); this.server.listen(options.port);
} }
HttpServer.prototype.getServer = function(){ HttpServer.prototype.getServer = function(){
return this.server; return this.server;
} }
HttpServer.prototype.handleFileError = function (res){ HttpServer.prototype.handleFileError = function (res){
res.writeHead(404, {'Content-Type': 'text/html'}); res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>404 not ... found</h1>'); res.end('<h1>404 not ... found</h1>');
} }
return HttpServer; return HttpServer;
}); });

View file

@ -1,16 +1,16 @@
define([ define([
"Bootstrap/HttpServer", "Bootstrap/HttpServer",
"Bootstrap/Socket", "Bootstrap/Socket",
"Lobby/Coordinator" "Lobby/Coordinator"
], ],
function(HttpServer, Socket, Coordinator) { function(HttpServer, Socket, Coordinator) {
function Server(options) { function Server(options) {
coordinator = new Coordinator(); coordinator = new Coordinator();
httpServer = new HttpServer(options); httpServer = new HttpServer(options);
this.socket = new Socket(httpServer.getServer(), options, coordinator); this.socket = new Socket(httpServer.getServer(), options, coordinator);
} }
return Server; return Server;
}); });

View file

@ -1,36 +1,36 @@
define([ define([
'socket.io' 'socket.io'
], ],
function(io) { function(io) {
function Socket(server, options, coordinator) { function Socket(server, options, coordinator) {
options.logLevel = typeof options.logLevel != 'undefined' options.logLevel = typeof options.logLevel != 'undefined'
? options.logLevel ? options.logLevel
: 0; : 0;
this.coordinator = coordinator; this.coordinator = coordinator;
this.socket = io.listen(server); this.socket = io.listen(server);
this.init(options); this.init(options);
} }
Socket.prototype.init = function(options){ Socket.prototype.init = function(options){
var self = this; var self = this;
this.socket.configure('development', function(){ this.socket.configure('development', function(){
this.set('log level', options.logLevel); this.set('log level', options.logLevel);
}); });
this.socket.on('connection', function(user){ this.socket.on('connection', function(user){
self.onConnection(user); self.onConnection(user);
}); });
} }
Socket.prototype.onConnection = function(socketLink){ Socket.prototype.onConnection = function(socketLink){
this.coordinator.createUser(socketLink); this.coordinator.createUser(socketLink);
} }
return Socket; return Socket;
}); });

View file

@ -1,24 +1,24 @@
define([ define([
"Lib/Vendor/Box2D", "Lib/Vendor/Box2D",
"Game/Core/Collision/Detector" "Game/Core/Collision/Detector"
], ],
function(Box2D, Parent) { function(Box2D, Parent) {
function Detector(me) { function Detector(me) {
Parent.call(this); Parent.call(this);
this.me = me; this.me = me;
} }
Detector.prototype = Object.create(Parent.prototype); Detector.prototype = Object.create(Parent.prototype);
Detector.prototype.handleStand = function(point, isColliding) { Detector.prototype.handleStand = function(point, isColliding) {
if (point.GetFixtureA().GetUserData() == Detector.IDENTIFIER.PLAYER_FOOT_SENSOR if (point.GetFixtureA().GetUserData() == Detector.IDENTIFIER.PLAYER_FOOT_SENSOR
|| point.GetFixtureB().GetUserData() == Detector.IDENTIFIER.PLAYER_FOOT_SENSOR) { || point.GetFixtureB().GetUserData() == Detector.IDENTIFIER.PLAYER_FOOT_SENSOR) {
this.me.onFootSensorDetection(isColliding); this.me.onFootSensorDetection(isColliding);
} }
} }
return Detector; return Detector;
}); });

View file

@ -1,76 +1,76 @@
define([ define([
"Game/Core/GameController", "Game/Core/GameController",
"Game/Client/Physics/Engine", "Game/Client/Physics/Engine",
"Game/Client/View/ViewController", "Game/Client/View/ViewController",
"Game/Client/Control/KeyboardController", "Game/Client/Control/KeyboardController",
"Game/Core/NotificationCenter", "Game/Core/NotificationCenter",
"Lib/Utilities/RequestAnimFrame" "Lib/Utilities/RequestAnimFrame"
], ],
function(Parent, PhysicsEngine, ViewController, KeyboardController, NotificationCenter, requestAnimFrame) { function(Parent, PhysicsEngine, ViewController, KeyboardController, NotificationCenter, requestAnimFrame) {
function GameController () { function GameController () {
this.viewController = new ViewController(); this.viewController = new ViewController();
Parent.call(this, new PhysicsEngine()); Parent.call(this, new PhysicsEngine());
this.me = null; this.me = null;
this.keyboardController = null; this.keyboardController = null;
//NotificationCenter.on('me/joined', this.meJoined, this) //NotificationCenter.on('me/joined', this.meJoined, this)
//this.update(); //this.update();
} }
GameController.prototype = Object.create(Parent.prototype); GameController.prototype = Object.create(Parent.prototype);
/* /*
GameController.prototype.getMe = function() { GameController.prototype.getMe = function() {
return this.me; return this.me;
} }
GameController.prototype.update = function() { GameController.prototype.update = function() {
requestAnimFrame(this.update.bind(this)); requestAnimFrame(this.update.bind(this));
this.physicsEngine.update(); this.physicsEngine.update();
this.viewController.update(); this.viewController.update();
if(this.me) { if(this.me) {
this.keyboardController.update(); this.keyboardController.update();
this.me.update(); this.me.update();
} }
} }
GameController.prototype.meJoined = function(user) { GameController.prototype.meJoined = function(user) {
this.me = this.userJoined(user); this.me = this.userJoined(user);
this.keyboardController = new KeyboardController(this.me, this); this.keyboardController = new KeyboardController(this.me, this);
} }
GameController.prototype.processGameCommand = function(command, options) { GameController.prototype.processGameCommand = function(command, options) {
if (command == "worldUpdate") { if (command == "worldUpdate") {
var body = this.physicsEngine.world.GetBodyList(); var body = this.physicsEngine.world.GetBodyList();
do { do {
var userData = body.GetUserData(); var userData = body.GetUserData();
if(userData && options[userData]) { if(userData && options[userData]) {
var update = options[userData]; var update = options[userData];
//console.log('position difference:', (body.GetPosition().y - update.p.y) * 30, body.GetLinearVelocity().y); //console.log('position difference:', (body.GetPosition().y - update.p.y) * 30, body.GetLinearVelocity().y);
body.SetAwake(true); body.SetAwake(true);
body.SetPosition(update.p); body.SetPosition(update.p);
body.SetAngle(update.a); body.SetAngle(update.a);
body.SetLinearVelocity(update.lv); body.SetLinearVelocity(update.lv);
body.SetAngularVelocity(update.av); body.SetAngularVelocity(update.av);
} }
} while (body = body.GetNext()); } while (body = body.GetNext());
} }
} }
*/ */
return GameController; return GameController;
}); });

View file

@ -1,112 +1,118 @@
define([ define([
"Game/Core/Protocol/Helper", "Game/Core/Protocol/Helper",
"Game/Client/GameController" "Game/Client/GameController"
], ],
function(ProtocolHelper, GameController) { function(ProtocolHelper, GameController) {
function Networker(socketLink) { function Networker(socketLink) {
this.socketLink = socketLink; this.socketLink = socketLink;
this.gameController = null; this.gameController = null;
this.init(); this.init();
} }
Networker.prototype.init = function() { Networker.prototype.init = function() {
var self = this; var self = this;
this.socketLink.on('connect', function() { this.socketLink.on('connect', function() {
self.onConnect(); self.onConnect();
}); });
/* /*
this.socketLink.on('message', function(message) { this.socketLink.on('message', function(message) {
self.onMessage(message); self.onMessage(message);
}); });
*/ */
this.socketLink.on('disconnect', function() { this.socketLink.on('disconnect', function() {
self.onDisconnect(); self.onDisconnect();
}); });
} }
Networker.prototype.onConnect = function() {
console.log('connected.')
this.join('dungeon');
}
Networker.prototype.onDisconnect = function() {
if(this.gameController) this.gameController.destruct();
this.gameController = null;
console.log('disconnected. game destroyed. no auto-reconnect');
}
Networker.prototype.join = function(channelName){
this.sendCommand('join', channelName);
}
Networker.prototype.onJoinSuccess = function(options) {
this.gameController = new GameController(options.id);
this.gameController.loadLevel("default.json");
/*
console.log("Joined " + options.channelName);
if (options.userIds && options.userIds.length > 0) {
for(var i = 0; i < options.userIds.length; i++) {
this.gameController.userJoined(options.userIds[i])
}
}
*/
}
Networker.prototype.sendCommand = function(command, options) {
var message = ProtocolHelper.encodeCommand(command, options);
this.socketLink.send(message);
}
Networker.prototype.onConnect = function() {
console.log('connected.')
this.join('dungeon');
}
/* /*
Networker.prototype.onMessage = function(message) { Networker.prototype.onMessage = function(message) {
var self = this; var self = this;
ProtocolHelper.runCommands(message, function(command, options) {
self.processControlCommand(command, options); ProtocolHelper.runCommands(message, function(command, options) {
}); self.processControlCommand(command, options);
} });
}
Networker.prototype.onUserJoined = function(userId) {
this.gameController.userJoined(userId);
console.log("User " + userId + " joined");
}
Networker.prototype.sendGameCommand = function(command, options) {
this.sendCommand('gameCommand', ProtocolHelper.assemble(command, options));
}
Networker.prototype.onUserLeft = function(userId) {
this.gameController.userLeft(userId);
}
Networker.prototype.processControlCommand = function(command, options) {
switch(command) {
case 'joinSuccess':
this.onJoinSuccess(options);
break;
case 'gameCommand':
for(var gameCommand in options) {
this.gameController.processGameCommand(gameCommand, options[gameCommand]);
}
break;
case 'userJoined':
this.onUserJoined(options);
break;
case 'userLeft':
this.onUserLeft(options);
break;
default:
break;
}
}
*/ */
Networker.prototype.onDisconnect = function() { return Networker;
if(this.gameController) this.gameController.destruct();
this.gameController = null;
console.log('disconnected. game destroyed. no auto-reconnect');
}
Networker.prototype.join = function(channelName){
this.sendCommand('join', channelName);
}
Networker.prototype.sendCommand = function(command, options) {
var message = ProtocolHelper.encodeCommand(command, options);
this.socketLink.send(message);
}
/*
Networker.prototype.onJoinSuccess = function(options) {
this.gameController = new GameController(options.id);
this.gameController.loadLevel("default.json")
console.log("Joined " + options.channelName);
if (options.userIds && options.userIds.length > 0) {
for(var i = 0; i < options.userIds.length; i++) {
this.gameController.userJoined(options.userIds[i])
}
}
}
Networker.prototype.onUserJoined = function(userId) {
this.gameController.userJoined(userId);
console.log("User " + userId + " joined");
}
Networker.prototype.sendGameCommand = function(command, options) {
this.sendCommand('gameCommand', ProtocolHelper.assemble(command, options));
}
Networker.prototype.onUserLeft = function(userId) {
this.gameController.userLeft(userId);
}
Networker.prototype.processControlCommand = function(command, options) {
switch(command) {
case 'joinSuccess':
this.onJoinSuccess(options);
break;
case 'gameCommand':
for(var gameCommand in options) {
this.gameController.processGameCommand(gameCommand, options[gameCommand]);
}
break;
case 'userJoined':
this.onUserJoined(options);
break;
case 'userLeft':
this.onUserLeft(options);
break;
default:
break;
}
}
*/
return Networker;
}); });

View file

@ -1,50 +1,50 @@
define(['Lib/Vendor/Three', 'Game/Config/Settings'], function(Three, Settings) { define(['Lib/Vendor/Three', 'Game/Config/Settings'], function(Three, Settings) {
function CameraController(isOrthographic) { function CameraController(isOrthographic) {
isOrthographic = typeof isOrthographic == 'undefined' isOrthographic = typeof isOrthographic == 'undefined'
? true ? true
: isOrthographic; : isOrthographic;
if(isOrthographic) { if(isOrthographic) {
this.camera = new Three.OrthographicCamera( this.camera = new Three.OrthographicCamera(
-Settings.STAGE_WIDTH/2, -Settings.STAGE_WIDTH/2,
Settings.STAGE_WIDTH/2, Settings.STAGE_WIDTH/2,
Settings.STAGE_HEIGHT/2, Settings.STAGE_HEIGHT/2,
-Settings.STAGE_HEIGHT/2, -Settings.STAGE_HEIGHT/2,
-2000, -2000,
1000 1000
); );
} else { } else {
this.camera = new Three.PerspectiveCamera( this.camera = new Three.PerspectiveCamera(
45, 45,
Settings.STAGE_WIDTH / Settings.STAGE_HEIGHT, Settings.STAGE_WIDTH / Settings.STAGE_HEIGHT,
-2000, -2000,
1000 1000
); );
} }
this.camera.position.z = 481; this.camera.position.z = 481;
} }
CameraController.prototype.getCamera = function(){ CameraController.prototype.getCamera = function(){
return this.camera; return this.camera;
} }
CameraController.prototype.setPosition = function(x, y){ CameraController.prototype.setPosition = function(x, y){
this.camera.position.x = x; this.camera.position.x = x;
this.camera.position.y = y; this.camera.position.y = y;
} }
CameraController.prototype.setZoom = function(z){ CameraController.prototype.setZoom = function(z){
this.camera.position.z = z; this.camera.position.z = z;
} }
return CameraController; return CameraController;
}); });

View file

@ -1,53 +1,53 @@
define(['Game/Config/Settings'], function(Settings) { define(['Game/Config/Settings'], function(Settings) {
var DomController = { var DomController = {
canvas: null, canvas: null,
debugCanvas: null debugCanvas: null
}; };
DomController.getCanvasContainer = function(){ DomController.getCanvasContainer = function(){
var container = document.getElementById(Settings.CANVAS_DOM_ID); var container = document.getElementById(Settings.CANVAS_DOM_ID);
if(container) { if(container) {
return container; return container;
} else { } else {
throw 'Canvas Container missing: #' + Settings.CANVAS_DOM_ID; throw 'Canvas Container missing: #' + Settings.CANVAS_DOM_ID;
} }
} }
DomController.getCanvas = function(){ DomController.getCanvas = function(){
return DomController.canvas; return DomController.canvas;
} }
DomController.setCanvas = function(canvas){ DomController.setCanvas = function(canvas){
var container = DomController.getCanvasContainer(); var container = DomController.getCanvasContainer();
if(DomController.canvas){ if(DomController.canvas){
container.removeChild(DomController.canvas); container.removeChild(DomController.canvas);
} }
DomController.canvas = canvas; DomController.canvas = canvas;
container.appendChild(canvas); container.appendChild(canvas);
} }
DomController.getDebugCanvas = function(){ DomController.getDebugCanvas = function(){
return DomController.debugCanvas; return DomController.debugCanvas;
} }
DomController.createDebugCanvas = function(){ DomController.createDebugCanvas = function(){
var container = DomController.getCanvasContainer(); var container = DomController.getCanvasContainer();
if(DomController.debugCanvas){ if(DomController.debugCanvas){
container.removeChild(DomController.debugCanvas); container.removeChild(DomController.debugCanvas);
} }
var canvas = document.createElement('canvas'); var canvas = document.createElement('canvas');
canvas.width = Settings.STAGE_WIDTH; canvas.width = Settings.STAGE_WIDTH;
canvas.height = Settings.STAGE_HEIGHT; canvas.height = Settings.STAGE_HEIGHT;
DomController.debugCanvas = canvas; DomController.debugCanvas = canvas;
container.appendChild(canvas); container.appendChild(canvas);
} }
return DomController; return DomController;
}); });

View file

@ -1,59 +1,59 @@
var requires = [ var requires = [
"Game/Client/View/DomController", "Game/Client/View/DomController",
"Lib/Vendor/Three", "Lib/Vendor/Three",
"Game/Config/Settings", "Game/Config/Settings",
"Game/Client/View/CameraController" "Game/Client/View/CameraController"
]; ];
define(requires, function(DomController, Three, Settings, CameraController){ define(requires, function(DomController, Three, Settings, CameraController){
function ViewController(){ function ViewController(){
this.mesh = null; this.mesh = null;
this.scene = null; this.scene = null;
this.renderer = null; this.renderer = null;
this.cameraController = new CameraController(); this.cameraController = new CameraController();
this.init(); this.init();
} }
function isWebGlEnabled () { function isWebGlEnabled () {
try { try {
return !! window.WebGLRenderingContext && !! document.createElement( 'canvas' ).getContext( 'experimental-webgl' ); return !! window.WebGLRenderingContext && !! document.createElement( 'canvas' ).getContext( 'experimental-webgl' );
} catch(e) { } catch(e) {
return false; return false;
} }
} }
ViewController.prototype.init = function(){ ViewController.prototype.init = function(){
var self = this; var self = this;
var rendererOptions = { var rendererOptions = {
antialias: true, antialias: true,
preserveDrawingBuffer: true preserveDrawingBuffer: true
}; };
if(isWebGlEnabled()) { if(isWebGlEnabled()) {
this.renderer = new Three.WebGLRenderer(rendererOptions); this.renderer = new Three.WebGLRenderer(rendererOptions);
} else { } else {
this.renderer = new Three.CanvasRenderer(rendererOptions); this.renderer = new Three.CanvasRenderer(rendererOptions);
} }
this.renderer.setClearColorHex(0x333333, 1); this.renderer.setClearColorHex(0x333333, 1);
this.renderer.setSize(Settings.STAGE_WIDTH, Settings.STAGE_HEIGHT); this.renderer.setSize(Settings.STAGE_WIDTH, Settings.STAGE_HEIGHT);
DomController.setCanvas(this.renderer.domElement); DomController.setCanvas(this.renderer.domElement);
if(Settings.DEBUG_MODE){ if(Settings.DEBUG_MODE){
DomController.createDebugCanvas(); DomController.createDebugCanvas();
} }
this.scene = new Three.Scene(); this.scene = new Three.Scene();
this.scene.add(this.cameraController.getCamera()); this.scene.add(this.cameraController.getCamera());
var ambientLight = new Three.AmbientLight(0xffffff); var ambientLight = new Three.AmbientLight(0xffffff);
this.scene.add(ambientLight); this.scene.add(ambientLight);
var directionalLight = new Three.DirectionalLight(0xffffff); var directionalLight = new Three.DirectionalLight(0xffffff);
@ -62,52 +62,52 @@ define(requires, function(DomController, Three, Settings, CameraController){
this.createMesh(100, 100, 100, 100, 'static/img/100.png', function(mesh){ this.createMesh(100, 100, 100, 100, 'static/img/100.png', function(mesh){
self.mesh = mesh; self.mesh = mesh;
self.scene.add(mesh); self.scene.add(mesh);
}); });
/* /*
this.createMesh(50, 50, 200, 100, 'static/img/100.png', function(mesh){ this.createMesh(50, 50, 200, 100, 'static/img/100.png', function(mesh){
self.scene.add(mesh); self.scene.add(mesh);
}); });
*/ */
//this.animate(this); //this.animate(this);
} }
ViewController.prototype.update = function() { ViewController.prototype.update = function() {
if(this.mesh) { if(this.mesh) {
this.mesh.rotation.z += .01; this.mesh.rotation.z += .01;
this.mesh.position.z += 1; this.mesh.position.z += 1;
this.mesh.position.x += .4; this.mesh.position.x += .4;
this.mesh.position.y += .4; this.mesh.position.y += .4;
} }
this.render(); this.render();
} }
ViewController.prototype.render = function() { ViewController.prototype.render = function() {
this.renderer.render(this.scene, this.cameraController.getCamera()); this.renderer.render(this.scene, this.cameraController.getCamera());
} }
ViewController.prototype.createMesh = function(width, height, x, y, imgPath, callback) { ViewController.prototype.createMesh = function(width, height, x, y, imgPath, callback) {
var textureImg = new Image(); var textureImg = new Image();
textureImg.onload = function(){ textureImg.onload = function(){
var material = new Three.MeshLambertMaterial({ var material = new Three.MeshLambertMaterial({
map: Three.ImageUtils.loadTexture(imgPath) map: Three.ImageUtils.loadTexture(imgPath)
}); });
var mesh = new Three.Mesh(new Three.PlaneGeometry(width, height), material); var mesh = new Three.Mesh(new Three.PlaneGeometry(width, height), material);
mesh.overdraw = true;/* mesh.overdraw = true;/*
mesh.position.z = 0; mesh.position.z = 0;
mesh.position.x = x; mesh.position.x = x;
mesh.position.y = y; mesh.position.y = y;
*/ */
callback(mesh); callback(mesh);
}; };
textureImg.src = imgPath; textureImg.src = imgPath;
} }
return ViewController; return ViewController;
}); });

View file

@ -1,50 +1,50 @@
define({ define({
STAGE_WIDTH: 600, STAGE_WIDTH: 600,
STAGE_HEIGHT: 400, STAGE_HEIGHT: 400,
// BOX2D INITIALATORS // BOX2D INITIALATORS
RATIO: 35, RATIO: 35,
BOX2D_WORLD_AABB_SIZE: 3000, BOX2D_WORLD_AABB_SIZE: 3000,
BOX2D_ALLOW_SLEEP: true, BOX2D_ALLOW_SLEEP: true,
BOX2D_GRAVITY: 16, BOX2D_GRAVITY: 16,
BOX2D_VELOCITY_ITERATIONS: 5, BOX2D_VELOCITY_ITERATIONS: 5,
BOX2D_POSITION_ITERATIONS: 5, BOX2D_POSITION_ITERATIONS: 5,
BOX2D_TIME_STEP: 1 / 60, BOX2D_TIME_STEP: 1 / 60,
// GRAPHIC PATHS // GRAPHIC PATHS
GRAPHICS_PATH: 'static/img/', GRAPHICS_PATH: 'static/img/',
GRAPHICS_SUBPATH_ITEMS: 'items/', GRAPHICS_SUBPATH_ITEMS: 'items/',
GRAPHICS_SUBPATH_CHARACTERS: 'characters/', GRAPHICS_SUBPATH_CHARACTERS: 'characters/',
TILE_SIZE: 15, TILE_SIZE: 15,
// GAME PLAY // GAME PLAY
WALK_SPEED: 2.5, WALK_SPEED: 2.5,
RUN_SPEED: 4.0, RUN_SPEED: 4.0,
FLY_SPEED: 3.2, FLY_SPEED: 3.2,
JUMP_SPEED: 3.0, JUMP_SPEED: 3.0,
JUMP_UPLIFT: 0.05, JUMP_UPLIFT: 0.05,
// restitution: bouncyness, friction: rubbing, density: mass // restitution: bouncyness, friction: rubbing, density: mass
TILE_FRICTION: 0.99, TILE_FRICTION: 0.99,
TILE_RESTITUTION: 0.1, TILE_RESTITUTION: 0.1,
PLAYER_DENSITY: 0.96, PLAYER_DENSITY: 0.96,
PLAYER_FRICTION: 5, PLAYER_FRICTION: 5,
PLAYER_MOTION_FRICTION: 0.1, PLAYER_MOTION_FRICTION: 0.1,
PLAYER_RESTITUTION: 0.0, PLAYER_RESTITUTION: 0.0,
PLAYER_LINEAR_DAMPING: .5, PLAYER_LINEAR_DAMPING: .5,
ITEM_DENSITY: 0.9, ITEM_DENSITY: 0.9,
ITEM_FRICTION: 0.99, ITEM_FRICTION: 0.99,
ITEM_RESTITUTION: 0.02, ITEM_RESTITUTION: 0.02,
// BROWSER // BROWSER
CANVAS_DOM_ID: 'canvasContainer', CANVAS_DOM_ID: 'canvasContainer',
IS_BROWSER_ENVIRONMENT: typeof window !== 'undefined', IS_BROWSER_ENVIRONMENT: typeof window !== 'undefined',
DEBUG_MODE: true, DEBUG_MODE: true,
// NETWORKING // NETWORKING
WORLD_UPDATE_BROADCAST_INTERVAL: 15 WORLD_UPDATE_BROADCAST_INTERVAL: 15
}) })

0
app/Game/Core/Control/InputController.js Normal file → Executable file
View file

View file

@ -1,36 +1,36 @@
define([ define([
"Game/Config/Settings", "Game/Config/Settings",
"Lib/Vendor/Box2D", "Lib/Vendor/Box2D",
"Game/Core/Collision/Detector" "Game/Core/Collision/Detector"
], ],
function(Settings, Box2D, CollisionDetector) { function(Settings, Box2D, CollisionDetector) {
function Engine () { function Engine () {
this.world = new Box2D.Dynamics.b2World( this.world = new Box2D.Dynamics.b2World(
new Box2D.Common.Math.b2Vec2(0, Settings.BOX2D_GRAVITY), new Box2D.Common.Math.b2Vec2(0, Settings.BOX2D_GRAVITY),
Settings.BOX2D_ALLOW_SLEEP Settings.BOX2D_ALLOW_SLEEP
); );
} }
Engine.prototype.getWorld = function() { Engine.prototype.getWorld = function() {
return this.world; return this.world;
} }
Engine.prototype.setCollisionDetector = function(me) { Engine.prototype.setCollisionDetector = function(me) {
var detector = new CollisionDetector(me); // FIXME: check if core collision detector works var detector = new CollisionDetector(me); // FIXME: check if core collision detector works
this.world.SetContactListener(detector.getListener()); this.world.SetContactListener(detector.getListener());
} }
Engine.prototype.createBody = function(bodyDef) { Engine.prototype.createBody = function(bodyDef) {
return this.world.CreateBody(bodyDef); return this.world.CreateBody(bodyDef);
} }
Engine.prototype.update = function() { Engine.prototype.update = function() {
this.world.Step(Settings.BOX2D_TIME_STEP, Settings.BOX2D_VELOCITY_ITERATIONS, Settings.BOX2D_POSITION_ITERATIONS); this.world.Step(Settings.BOX2D_TIME_STEP, Settings.BOX2D_VELOCITY_ITERATIONS, Settings.BOX2D_POSITION_ITERATIONS);
this.world.ClearForces(); this.world.ClearForces();
} }
return Engine; return Engine;
}); });

308
app/Game/Core/Player.js Normal file → Executable file
View file

@ -1,193 +1,193 @@
define([ define([
"Game/Core/Physics/Doll", "Game/Core/Physics/Doll",
"Game/Config/Settings" "Game/Config/Settings"
], ],
function(Doll, Settings) { function(Doll, Settings) {
function Player (id, physicsEngine, repository) { function Player (id, physicsEngine, repository) {
this.physicsEngine = physicsEngine; this.physicsEngine = physicsEngine;
this.id = id; this.id = id;
this.repository = repository; this.repository = repository;
this.standing = false; this.standing = false;
this.doll; this.doll;
this.mc; this.mc;
this.currentAnimationState = 'stand'; this.currentAnimationState = 'stand';
this.lookDirection = 1; this.lookDirection = 1;
this.moveDirection = 0; this.moveDirection = 0;
this.init(id); this.init(id);
} }
Player.prototype.init = function(id) { Player.prototype.init = function(id) {
this.doll = new Doll(this.physicsEngine, id); this.doll = new Doll(this.physicsEngine, id);
//this.mc = EmbedHandler.load(EmbedHandler.CHUCK); //this.mc = EmbedHandler.load(EmbedHandler.CHUCK);
//this.mc.stop(); //this.mc.stop();
//var mclp = new MovieClipLabelParser(); //var mclp = new MovieClipLabelParser();
//mclp.parse(this.mc); //mclp.parse(this.mc);
} }
Player.prototype.spawn = function(x, y) { Player.prototype.spawn = function(x, y) {
//this.repository.createModel(this.mc, this.doll.getBody()); //this.repository.createModel(this.mc, this.doll.getBody());
this.doll.spawn(x, y); this.doll.spawn(x, y);
} }
Player.prototype.getDoll = function() { Player.prototype.getDoll = function() {
return this.doll; return this.doll;
} }
Player.prototype.getBody = function() { Player.prototype.getBody = function() {
return this.doll.getBody(); return this.doll.getBody();
} }
Player.prototype.setStanding = function(isStanding) { Player.prototype.setStanding = function(isStanding) {
var resetStates = ['jump', 'jumploop']; var resetStates = ['jump', 'jumploop'];
if (resetStates.indexOf(this.currentAnimationState)>=0 && !this.standing && isStanding) { if (resetStates.indexOf(this.currentAnimationState)>=0 && !this.standing && isStanding) {
this.animate('stand'); this.animate('stand');
} }
this.standing = isStanding; this.standing = isStanding;
} }
Player.prototype.isStanding = function() { Player.prototype.isStanding = function() {
return this.standing; return this.standing;
} }
Player.prototype.move = function(direction) { Player.prototype.move = function(direction) {
this.moveDirection = direction; this.moveDirection = direction;
switch(true) { switch(true) {
case direction == this.lookDirection && this.isStanding(): case direction == this.lookDirection && this.isStanding():
this.doll.move(direction, Settings.RUN_SPEED); this.doll.move(direction, Settings.RUN_SPEED);
break; break;
case !this.isStanding(): case !this.isStanding():
this.doll.move(direction, Settings.FLY_SPEED); this.doll.move(direction, Settings.FLY_SPEED);
break; break;
default: default:
this.doll.move(direction, Settings.WALK_SPEED); this.doll.move(direction, Settings.WALK_SPEED);
break; break;
} }
if (this.isStanding()) { if (this.isStanding()) {
this.animate(this.calculateWalkAnimation()); this.animate(this.calculateWalkAnimation());
} }
} }
Player.prototype.stop = function() { Player.prototype.stop = function() {
this.moveDirection = 0; this.moveDirection = 0;
this.doll.stop(); this.doll.stop();
if (this.isWalking() || this.standing) { if (this.isWalking() || this.standing) {
this.animate('stand'); this.animate('stand');
} }
} }
Player.prototype.jump = function() { Player.prototype.jump = function() {
if (this.isStanding()) { if (this.isStanding()) {
this.doll.jump(); this.doll.jump();
this.animate('jump'); this.animate('jump');
this.setStanding(false); this.setStanding(false);
} }
} }
Player.prototype.jumping = function() { Player.prototype.jumping = function() {
if (!this.isStanding()) { if (!this.isStanding()) {
this.doll.jumping(); this.doll.jumping();
} }
} }
Player.prototype.duck = function() { Player.prototype.duck = function() {
if (this.standing && !this.isWalking()) { if (this.standing && !this.isWalking()) {
this.animate('duck'); this.animate('duck');
} }
} }
Player.prototype.standUp = function() { Player.prototype.standUp = function() {
if (this.standing) { if (this.standing) {
this.animate('standup'); this.animate('standup');
} }
} }
Player.prototype.animate = function(type) { Player.prototype.animate = function(type) {
if (type == this.currentAnimationState) { if (type == this.currentAnimationState) {
return; return;
} }
//this.mc.gotoAndPlay(type); //this.mc.gotoAndPlay(type);
this.currentAnimationState = type; this.currentAnimationState = type;
} }
Player.prototype.calculateWalkAnimation = function() { Player.prototype.calculateWalkAnimation = function() {
if (this.moveDirection == this.lookDirection) { if (this.moveDirection == this.lookDirection) {
return 'run'; return 'run';
} }
return 'walkback'; return 'walkback';
} }
Player.prototype.look = function(x, y) { Player.prototype.look = function(x, y) {
/* /*
var degree = Math.atan2(Settings.STAGE_WIDTH / 2 - x, Settings.STAGE_HEIGHT / 2 - 25 - y) / (Math.PI / 180); var degree = Math.atan2(Settings.STAGE_WIDTH / 2 - x, Settings.STAGE_HEIGHT / 2 - 25 - y) / (Math.PI / 180);
var lastLookDirection = this.lookDirection; var lastLookDirection = this.lookDirection;
if (x < Settings.STAGE_WIDTH / 2) { if (x < Settings.STAGE_WIDTH / 2) {
this.mc.scaleX = -1; this.mc.scaleX = -1;
this.lookDirection = -1; this.lookDirection = -1;
degree = (-45 + degree / 2); degree = (-45 + degree / 2);
this.mc.head.rotation = degree; this.mc.head.rotation = degree;
} else if (x >= Settings.STAGE_WIDTH / 2) { } else if (x >= Settings.STAGE_WIDTH / 2) {
this.mc.scaleX = 1; this.mc.scaleX = 1;
this.lookDirection = 1; this.lookDirection = 1;
degree = (45 + -degree / 2) - 90; degree = (45 + -degree / 2) - 90;
this.mc.head.rotation = degree; this.mc.head.rotation = degree;
} }
if (this.lookDirection != lastLookDirection && this.isWalking()) { if (this.lookDirection != lastLookDirection && this.isWalking()) {
this.animate(this.calculateWalkAnimation()); this.animate(this.calculateWalkAnimation());
}*/ }*/
} }
Player.prototype.isWalking = function() { Player.prototype.isWalking = function() {
var states = ['walk', 'walkback', 'run']; var states = ['walk', 'walkback', 'run'];
if (states.indexOf(this.currentAnimationState) >= 0) { if (states.indexOf(this.currentAnimationState) >= 0) {
return true; return true;
} }
return false; return false;
} }
// called by CollisionDetection // called by CollisionDetection
Player.prototype.onFootSensorDetection = function(isColliding) { Player.prototype.onFootSensorDetection = function(isColliding) {
if(isColliding) { if(isColliding) {
if(this.doll.getBody().GetLinearVelocity().y < -Settings.JUMP_SPEED && !this.isStanding()) { if(this.doll.getBody().GetLinearVelocity().y < -Settings.JUMP_SPEED && !this.isStanding()) {
return; return;
} }
this.setStanding(true); this.setStanding(true);
} else { } else {
// TODO This needs some more thought to it. // TODO This needs some more thought to it.
// maybe take a look at collision groups for collision detection, // maybe take a look at collision groups for collision detection,
// to group all tiles together // to group all tiles together
//this.setStanding(false); //this.setStanding(false);
//this.animate('jumploop'); //this.animate('jumploop');
} }
} }
Player.prototype.update = function() { Player.prototype.update = function() {
//this.mc.head.y = this.mc.head_posmask.y; //this.mc.head.y = this.mc.head_posmask.y;
if (this.doll.getBody().GetLinearVelocity().x == 0 && this.isWalking()) { if (this.doll.getBody().GetLinearVelocity().x == 0 && this.isWalking()) {
this.stop(); this.stop();
} }
if (!this.doll.getBody().IsAwake()) { if (!this.doll.getBody().IsAwake()) {
this.setStanding(true); this.setStanding(true);
} }
} }
Player.prototype.destroy = function() { Player.prototype.destroy = function() {
this.doll.destroy(); this.doll.destroy();
} }
return Player; return Player;
}); });

34
app/Game/Core/Protocol/Helper.js Normal file → Executable file
View file

@ -1,29 +1,29 @@
define([ define([
"Game/Core/Protocol/Parser" "Game/Core/Protocol/Parser"
], ],
function(Parser) { function(Parser) {
var Helper = {} var Helper = {}
Helper.encodeCommand = function(command, options){ Helper.encodeCommand = function(command, options){
return Parser.encode(Helper.assemble(command, options)); return Parser.encode(Helper.assemble(command, options));
} }
Helper.assemble = function(command, options){ Helper.assemble = function(command, options){
var commands = {}; var commands = {};
commands[command] = options || null; commands[command] = options || null;
return commands; return commands;
} }
Helper.runCommands = function(message, callback){ Helper.runCommands = function(message, callback){
var commands = Parser.decode(message); var commands = Parser.decode(message);
for(var command in commands) { for(var command in commands) {
callback(command, commands[command]); callback(command, commands[command]);
} }
} }
return Helper; return Helper;
}); });

16
app/Game/Core/Protocol/Parser.js Normal file → Executable file
View file

@ -3,15 +3,15 @@ define([
function() { function() {
var Parser = {}; var Parser = {};
Parser.encode = function(message){ Parser.encode = function(message){
return JSON.stringify(message); return JSON.stringify(message);
} }
Parser.decode = function(message){ Parser.decode = function(message){
return JSON.parse(message); return JSON.parse(message);
} }
return Parser; return Parser;
}); });

View file

@ -1,8 +1,8 @@
define(function() { define(function() {
function User(id) { function User(id) {
this.id = id; this.id = id;
} }
return User; return User;
}); });

View file

@ -1,108 +1,108 @@
define([ define([
"Game/Server/GameController", "Game/Server/GameController",
"Game/Core/NotificationCenter" "Game/Core/NotificationCenter"
], ],
function(GameController, NotificationCenter) { function(GameController, NotificationCenter) {
function Channel(coordinatorLink) { function Channel(coordinatorLink) {
var self = this; var self = this;
this.coordinatorLink = coordinatorLink; this.coordinatorLink = coordinatorLink;
this.coordinatorLink.receive = function(message) { self.onMessage(message) }; this.coordinatorLink.receive = function(message) { self.onMessage(message) };
this.users = {}; this.users = {};
this.gameController = new GameController(); this.gameController = new GameController();
this.gameController.loadLevel("default.json"); this.gameController.loadLevel("default.json");
/* /*
var self = this; var self = this;
NotificationCenter.on("processGameCommandFromUser", function(topic, args) { NotificationCenter.on("processGameCommandFromUser", function(topic, args) {
self.processGameCommandFromUser.apply(self, args); self.processGameCommandFromUser.apply(self, args);
}); });
*/ */
} }
Channel.validateName = function(name){ Channel.validateName = function(name){
return true; return true;
} }
// Messages look like: // Messages look like:
// {channel: {setName: 'foo'}} // {channel: {setName: 'foo'}}
// {user: {jupm: null}, id: 12} // {user: {jupm: null}, id: 12}
Channel.prototype.onMessage = function(message) { Channel.prototype.onMessage = function(message) {
for(var recipient in message) { for(var recipient in message) {
switch(recipient) { switch(recipient) {
case 'user': case 'user':
this.forward(this.users[message.id], message.user); this.forward(this.users[message.id], message.user);
break; break;
case 'id': // Do nothing, it is needed by the user case 'id': // Do nothing, it is needed by the user
break; break;
case 'channel': case 'channel':
this.forward(this, message.channel); this.forward(this, message.channel);
break; break;
default: default:
throw 'unknown recipient'; throw 'unknown recipient';
break; break;
} }
} }
}; };
Channel.prototype.forward = function(target, message) { Channel.prototype.forward = function(target, message) {
for(var command in message) { for(var command in message) {
if(typeof target[command] == 'function'){ if(typeof target[command] == 'function'){
target[command].call(target, message[command]); target[command].call(target, message[command]);
} else { } else {
throw 'trying to call undefined function ' + target[command]; throw 'trying to call undefined function ' + target[command];
} }
} }
}; };
Channel.prototype.setName = function(name) { Channel.prototype.setName = function(name) {
this.name = name; this.name = name;
console.log(' created channel ' + name); console.log(' created channel ' + name);
} }
/* /*
Channel.prototype.addUser = function(user){ Channel.prototype.addUser = function(user){
var userIds = Object.keys(this.users); var userIds = Object.keys(this.users);
this.users[user.id] = user; this.users[user.id] = user;
user.sendCommand('joinSuccess', {channelName: this.name, id: user.id, userIds: userIds}); user.sendCommand('joinSuccess', {channelName: this.name, id: user.id, userIds: userIds});
this.sendCommandToAllUsersExcept('userJoined', user.id, user); this.sendCommandToAllUsersExcept('userJoined', user.id, user);
NotificationCenter.trigger('user/joined', user); NotificationCenter.trigger('user/joined', user);
} }
Channel.prototype.releaseUser = function(user) { Channel.prototype.releaseUser = function(user) {
this.gameController.userIdLeft(user.id); this.gameController.userIdLeft(user.id);
this.sendCommandToAllUsersExcept("userLeft", user.id, user); this.sendCommandToAllUsersExcept("userLeft", user.id, user);
delete this.users[user.id]; delete this.users[user.id];
} }
Channel.prototype.sendCommandToAllUsers = function(command, options) { Channel.prototype.sendCommandToAllUsers = function(command, options) {
for(var id in this.users) { for(var id in this.users) {
this.users[id].sendCommand(command, options); this.users[id].sendCommand(command, options);
} }
} }
Channel.prototype.sendCommandToAllUsersExcept = function(command, options, except_user) { Channel.prototype.sendCommandToAllUsersExcept = function(command, options, except_user) {
for(var id in this.users) { for(var id in this.users) {
if (id != except_user.id) { if (id != except_user.id) {
this.users[id].sendCommand(command, options); this.users[id].sendCommand(command, options);
} }
} }
} }
Channel.prototype.processGameCommandFromUser = function(command, options, user) { Channel.prototype.processGameCommandFromUser = function(command, options, user) {
this.gameController.progressGameCommandFromUser(command, options, user); this.gameController.progressGameCommandFromUser(command, options, user);
} }
*/ */
return Channel; return Channel;
}); });

View file

@ -3,18 +3,18 @@ define([
function() { function() {
function CoordinatorLink(process) { function CoordinatorLink(process) {
this.process = process; this.process = process;
} }
CoordinatorLink.prototype.send = function(message) { CoordinatorLink.prototype.send = function(message) {
this.process.send(message); this.process.send(message);
}; };
CoordinatorLink.prototype.receive = function(message) { CoordinatorLink.prototype.receive = function(message) {
throw 'This method is abstract and must be overwritten by Channel'; throw 'This method is abstract and must be overwritten by Channel';
}; };
return CoordinatorLink; return CoordinatorLink;
}); });

View file

@ -1,84 +1,84 @@
define([ define([
"Game/Core/GameController", "Game/Core/GameController",
"Game/Core/Physics/Engine", "Game/Core/Physics/Engine",
"Game/Config/Settings", "Game/Config/Settings",
"Game/Core/Control/InputController", "Game/Core/Control/InputController",
"Lib/Utilities/RequestAnimFrame", "Lib/Utilities/RequestAnimFrame",
"Game/Core/NotificationCenter" "Game/Core/NotificationCenter"
], ],
function(Parent, PhysicsEngine, Settings, InputController, requestAnimFrame, NotificationCenter) { function(Parent, PhysicsEngine, Settings, InputController, requestAnimFrame, NotificationCenter) {
function GameController () { function GameController () {
Parent.call(this, new PhysicsEngine()); Parent.call(this, new PhysicsEngine());
this.inputControllers = {}; this.inputControllers = {};
//this.update(); //this.update();
//this.updateWorld(); //this.updateWorld();
//NotificationCenter.on('user/joined', this.userJoined, this); //NotificationCenter.on('user/joined', this.userJoined, this);
//NotificationCenter.on('user/left', this.userLeft, this); //NotificationCenter.on('user/left', this.userLeft, this);
} }
GameController.prototype = Object.create(Parent.prototype); GameController.prototype = Object.create(Parent.prototype);
/* /*
GameController.prototype.update = function() { GameController.prototype.update = function() {
requestAnimFrame(this.update.bind(this)); requestAnimFrame(this.update.bind(this));
this.physicsEngine.update(); this.physicsEngine.update();
for(var id in this.players) { for(var id in this.players) {
this.players[id].update(); this.players[id].update();
} }
} }
GameController.prototype.userJoined = function(user) { GameController.prototype.userJoined = function(user) {
Parent.prototype.userJoined.call(this, user); Parent.prototype.userJoined.call(this, user);
var id = user.id; var id = user.id;
var player = this.players[id]; var player = this.players[id];
this.inputControllers[id] = new InputController(player); this.inputControllers[id] = new InputController(player);
} }
GameController.prototype.userLeft = function(user) { GameController.prototype.userLeft = function(user) {
Parent.prototype.userLeft.call(this, user); Parent.prototype.userLeft.call(this, user);
delete this.inputControllers[user.id]; delete this.inputControllers[user.id];
} }
GameController.prototype.progressGameCommandFromUser = function(command, options, user) { GameController.prototype.progressGameCommandFromUser = function(command, options, user) {
var inputController = this.inputControllers[user.id]; var inputController = this.inputControllers[user.id];
if (typeof inputController[command] == 'function') { if (typeof inputController[command] == 'function') {
inputController[command](options); inputController[command](options);
} }
} }
GameController.prototype.updateWorld = function() { GameController.prototype.updateWorld = function() {
var update = {}; var update = {};
var isUpdateNeeded = false; var isUpdateNeeded = false;
var body = this.physicsEngine.world.GetBodyList(); var body = this.physicsEngine.world.GetBodyList();
do { do {
var userData = body.GetUserData(); var userData = body.GetUserData();
if(userData && body.IsAwake()){ if(userData && body.IsAwake()){
update[userData] = { update[userData] = {
p: body.GetPosition(), p: body.GetPosition(),
a: body.GetAngle(), a: body.GetAngle(),
lv: body.GetLinearVelocity(), lv: body.GetLinearVelocity(),
av: body.GetAngularVelocity() av: body.GetAngularVelocity()
}; };
isUpdateNeeded = true; isUpdateNeeded = true;
} }
} while (body = body.GetNext()); } while (body = body.GetNext());
if(isUpdateNeeded) { if(isUpdateNeeded) {
//NotificationCenter.trigger("sendCommandToAllUsers", ['gameCommand', {worldUpdate:update}]); //NotificationCenter.trigger("sendCommandToAllUsers", ['gameCommand', {worldUpdate:update}]);
} }
setTimeout(this.updateWorld.bind(this), Settings.WORLD_UPDATE_BROADCAST_INTERVAL); setTimeout(this.updateWorld.bind(this), Settings.WORLD_UPDATE_BROADCAST_INTERVAL);
} }
*/ */
return GameController; return GameController;
}); });

View file

@ -1,45 +1,45 @@
define([ define([
"Game/Core/User", "Game/Core/User",
"Game/Core/Protocol/Helper", "Game/Core/Protocol/Helper",
"Game/Core/NotificationCenter" "Game/Core/NotificationCenter"
], ],
function(Parent, ProtocolHelper, NotificationCenter) { function(Parent, ProtocolHelper, NotificationCenter) {
function User(id, coordinator) { function User(id, coordinator) {
Parent.call(this, id); Parent.call(this, id);
this.id = socketLink.id; this.id = socketLink.id;
this.socketLink = socketLink; this.socketLink = socketLink;
this.coordinator = coordinator; this.coordinator = coordinator;
this.channel = null; this.channel = null;
this.init(socketLink); this.init(socketLink);
} }
User.prototype = Object.create(Parent.prototype); User.prototype = Object.create(Parent.prototype);
User.prototype.init = function(socketLink){ User.prototype.init = function(socketLink){
var self = this; var self = this;
} }
/* /*
User.prototype.setChannel = function(channel) { User.prototype.setChannel = function(channel) {
this.channel = channel; this.channel = channel;
} }
User.prototype.sendCommand = function(command, options) { User.prototype.sendCommand = function(command, options) {
var message = ProtocolHelper.encodeCommand(command, options); var message = ProtocolHelper.encodeCommand(command, options);
this.socketLink.send(message); this.socketLink.send(message);
} }
User.prototype.toString = function() { User.prototype.toString = function() {
return "[User " + this.id + "]"; return "[User " + this.id + "]";
}; };
*/ */
return User; return User;
}); });

View file

@ -4,7 +4,7 @@ define([
function(Settings) { function(Settings) {
var requestAnimFrame = (function(){ var requestAnimFrame = (function(){
var _setTimeout = function( callback ){ var _setTimeout = function( callback ){
setTimeout(callback, Settings.BOX2D_TIME_STEP * 1000); setTimeout(callback, Settings.BOX2D_TIME_STEP * 1000);
@ -25,5 +25,5 @@ function(Settings) {
})(); })();
return requestAnimFrame; return requestAnimFrame;
}); });

View file

@ -1,74 +1,74 @@
define([ define([
"Lobby/User", "Lobby/User",
"Game/Server/Channel", "Game/Server/Channel",
"child_process" "child_process"
], ],
function(User, Channel, childProcess) { function(User, Channel, childProcess) {
var fork = childProcess.fork; var fork = childProcess.fork;
function Coordinator() { function Coordinator() {
this.channels = {}; this.channels = {};
this.lobbyUsers = {}; this.lobbyUsers = {};
} }
Coordinator.prototype.createUser = function(socketLink){ Coordinator.prototype.createUser = function(socketLink){
var user = new User(socketLink, this); var user = new User(socketLink, this);
this.assignUserToLobby(user); this.assignUserToLobby(user);
} }
Coordinator.prototype.assignUserToLobby = function(user){ Coordinator.prototype.assignUserToLobby = function(user){
if(user.channelProcess) { if(user.channelProcess) {
//user.channel.releaseUser(user); -> generate message //user.channel.releaseUser(user); -> generate message
} }
this.lobbyUsers[user.id] = user; this.lobbyUsers[user.id] = user;
} }
Coordinator.prototype.assignUserToChannel = function(user, channelName){ Coordinator.prototype.assignUserToChannel = function(user, channelName){
if(user.channelProcess) { if(user.channelProcess) {
//user.channel.releaseUser(user); -> generate message //user.channel.releaseUser(user); -> generate message
} }
if(!Channel.validateName(channelName)){ if(!Channel.validateName(channelName)){
//TODO send validation error //TODO send validation error
return false; return false;
} }
var channel = this.channels[channelName]; var channel = this.channels[channelName];
if(!channel) { if(!channel) {
try { try {
channel = fork('channel.js'); channel = fork('channel.js');
channel.send('CREATE'); channel.send('CREATE');
channel.send({ channel.send({
channel: { channel: {
setName: channelName setName: channelName
} }
}); });
} catch (err) { } catch (err) {
throw 'Failed to fork channel ' + channelName + '! (' + err + ')'; throw 'Failed to fork channel ' + channelName + '! (' + err + ')';
} }
this.channels[channelName] = channel; this.channels[channelName] = channel;
} }
//channel.addUser(user); //channel.addUser(user);
//user.setChannel(channel); //user.setChannel(channel);
delete this.lobbyUsers[user.id]; delete this.lobbyUsers[user.id];
} }
Coordinator.prototype.removeUser = function(user){ Coordinator.prototype.removeUser = function(user){
delete this.lobbyUsers[user.id]; delete this.lobbyUsers[user.id];
if(user.channelProcess) { if(user.channelProcess) {
//user.channel.releaseUser(user); -> generate message //user.channel.releaseUser(user); -> generate message
} }
} }
return Coordinator; return Coordinator;
}); });

View file

@ -1,66 +1,66 @@
define([ define([
"Game/Core/User", "Game/Core/User",
"Game/Core/Protocol/Helper" "Game/Core/Protocol/Helper"
], ],
function(Parent, ProtocolHelper) { function(Parent, ProtocolHelper) {
function User(socketLink, coordinator) { function User(socketLink, coordinator) {
Parent.call(this, socketLink.id); Parent.call(this, socketLink.id);
this.coordinator = coordinator; this.coordinator = coordinator;
this.channelProcess = null; this.channelProcess = null;
var self = this; var self = this;
socketLink.on('message', function(message){ socketLink.on('message', function(message){
self.onMessage(message); self.onMessage(message);
}); });
socketLink.on('disconnect', function(){ socketLink.on('disconnect', function(){
self.onDisconnect(); self.onDisconnect();
}); });
} }
User.prototype = Object.create(Parent.prototype); User.prototype = Object.create(Parent.prototype);
User.prototype.setChannelProcess = function(channelProcess) { User.prototype.setChannelProcess = function(channelProcess) {
this.channelProcess = channelProcess; this.channelProcess = channelProcess;
} }
User.prototype.onMessage = function(message){ User.prototype.onMessage = function(message){
var self = this; var self = this;
ProtocolHelper.runCommands(message, function(command, options){ ProtocolHelper.runCommands(message, function(command, options){
self.processControlCommand(command, options); self.processControlCommand(command, options);
}); });
} }
User.prototype.onDisconnect = function(){ User.prototype.onDisconnect = function(){
this.coordinator.removeUser(this); this.coordinator.removeUser(this);
} }
User.prototype.processControlCommand = function(command, options){ User.prototype.processControlCommand = function(command, options){
switch(command) { switch(command) {
case 'join': case 'join':
this.coordinator.assignUserToChannel(this, options); this.coordinator.assignUserToChannel(this, options);
break; break;
case 'leave': case 'leave':
this.coordinator.assignUserToLobby(this); this.coordinator.assignUserToLobby(this);
break; break;
case 'gameCommand': case 'gameCommand':
for(var gameCommand in options) { for(var gameCommand in options) {
//NotificationCenter.trigger("processGameCommandFromUser", [gameCommand, options[gameCommand], this]); //NotificationCenter.trigger("processGameCommandFromUser", [gameCommand, options[gameCommand], this]);
//this.channel.processGameCommandFromUser(gameCommand, options[gameCommand], this); //this.channel.processGameCommandFromUser(gameCommand, options[gameCommand], this);
} }
break; break;
default: default:
break; break;
} }
} }
return User; return User;
}); });

View file

@ -1,13 +1,13 @@
var requirejs = require('requirejs'); var requirejs = require('requirejs');
requirejs.config({ requirejs.config({
baseUrl: 'app' baseUrl: 'app'
}); });
var inspector = {}; var inspector = {};
requirejs(["Bootstrap/Channel"], function(ChannelBootstrap) { requirejs(["Bootstrap/Channel"], function(ChannelBootstrap) {
var channelBootstrap = new ChannelBootstrap(process); var channelBootstrap = new ChannelBootstrap(process);
inspector.channelBootstrap = channelBootstrap; inspector.channelBootstrap = channelBootstrap;
}); });

View file

@ -1,22 +1,22 @@
requirejs.config({ requirejs.config({
baseUrl: 'app' baseUrl: 'app'
}); });
var inspector = {}; var inspector = {};
requirejs(["Bootstrap/Client"], function(Client) { requirejs(["Bootstrap/Client"], function(Client) {
var options = { var options = {
"reconnect": false, "reconnect": false,
"reconnection delay": 500, "reconnection delay": 500,
"max reconnection attempts": 10, "max reconnection attempts": 10,
"transports": [ "transports": [
"websocket", "websocket",
"flashsocket" "flashsocket"
], ],
}; };
var client = new Client(location.href, options); var client = new Client(location.href, options);
inspector.client = client; inspector.client = client;
}); });

View file

@ -3,24 +3,24 @@ var requirejs = require('requirejs');
var inspector = {}; var inspector = {};
requirejs.config({ requirejs.config({
nodeRequire: require, nodeRequire: require,
baseUrl: 'app' baseUrl: 'app'
}); });
var port = process.argv[2] var port = process.argv[2]
|| process.env.PORT || process.env.PORT
|| process.env.npm_package_config_port; || process.env.npm_package_config_port;
var options = { var options = {
port: port, port: port,
rootDirectory: './', rootDirectory: './',
caching: false, caching: false,
logLevel: process.argv[3] || 0 logLevel: process.argv[3] || 0
}; };
requirejs(["Bootstrap/Server"], function(Server) { requirejs(["Bootstrap/Server"], function (Server) {
var server = new Server(options); var server = new Server(options);
inspector.server = server; inspector.server = server;
}); });
exports = module.exports = inspector; exports = module.exports = inspector;

View file

@ -3,24 +3,24 @@
<head> <head>
<title>Chuck</title> <title>Chuck</title>
<style> <style>
html, body { html, body {
margin: 0; margin: 0;
padding: 0; padding: 0;
display: table; display: table;
width: 100%; width: 100%;
height: 100%; height: 100%;
background: #000; background: #000;
} }
#canvasContainer { #canvasContainer {
text-align: center; text-align: center;
display: table-cell; display: table-cell;
vertical-align: middle; vertical-align: middle;
height: 100%; height: 100%;
} }
canvas { canvas {
background: #333; background: #333;
margin: 10px; margin: 10px;
} }
</style> </style>
</head> </head>
<body> <body>