Skip to content

Commit

Permalink
add code comments
Browse files Browse the repository at this point in the history
  • Loading branch information
Mahmoud Ben Hassine committed Dec 2, 2014
1 parent cc6f89e commit ae4f888
Show file tree
Hide file tree
Showing 2 changed files with 115 additions and 20 deletions.
52 changes: 38 additions & 14 deletions config/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,51 +2,63 @@ module.exports = function (server) {

var io = require('socket.io').listen(server);

var ch = require('chess.js');
var chess = require('chess.js');

/*
* live show of top rated game
*/
var trg = new ch.Chess();
var topRatedGame = new chess.Chess(); // fake game (playing random moves). It should be a real game being played on the server

var tv = io.of('/tv');
var tv = io.of('/tv'); // Socket to broadcast top rated game moves to index and tv pages

setInterval(function() {
var possibleMoves = trg.moves();
var possibleMoves = topRatedGame.moves();
// if the game is over, reload a new game
if (trg.game_over() === true || trg.in_draw() === true || possibleMoves.length === 0) {
trg = new ch.Chess();
possibleMoves = trg.moves();
if (topRatedGame.game_over() === true || topRatedGame.in_draw() === true || possibleMoves.length === 0) {
topRatedGame = new chess.Chess();
possibleMoves = topRatedGame.moves();
}

var m = possibleMoves[Math.floor(Math.random() * possibleMoves.length)];
trg.move(m);
tv.emit('newTrgMove', { fen: trg.fen(), pgn: trg.pgn(), turn: trg.turn() });
var move = possibleMoves[Math.floor(Math.random() * possibleMoves.length)];
topRatedGame.move(move);
tv.emit('new-top-rated-game-move', { fen: topRatedGame.fen(), pgn: topRatedGame.pgn(), turn: topRatedGame.turn() });
}, 3000);

tv.on('connection', function(socket){
socket.emit('newTrgMove', { fen: trg.fen(), pgn: trg.pgn(), turn: trg.turn() });
socket.emit('new-top-rated-game-move', { fen: topRatedGame.fen(), pgn: topRatedGame.pgn(), turn: topRatedGame.turn() });
});
//end live show of top rated game
/*
* End of live show of top rated game
*/

var games = {};
var users = 0;

/*
* Socket to use to broadcast monitoring events
*/
var monitor = io.of('/monitor');
monitor.on('connection', function(socket){
socket.emit('update', {nbUsers: users, nbGames: Object.keys(games).length});
});

/*
* Socket IO event handlers
*/
io.sockets.on('connection', function (socket) {

var username = socket.handshake.query.user;

users++;
monitor.emit('update', {nbUsers: users, nbGames: Object.keys(games).length});

/*
* A player joins a game
*/
socket.on('join', function (data) {
var room = data.token;

// If the player is the first to join, initialize the game and players array
if (!(room in games)) {
var players = [{
socket: socket,
Expand All @@ -68,13 +80,13 @@ module.exports = function (server) {
};

socket.join(room);
socket.emit('wait');
socket.emit('wait'); // tell the game creator to wait until a opponent joins the game
return;
}

var game = games[room];

/* todo: handle full case
/* TODO: handle full case, a third player attempts to join the game after already 2 players has joined the game
if (game.status === "ready") {
socket.emit('full');
}*/
Expand All @@ -88,10 +100,16 @@ module.exports = function (server) {

});

/*
* A player makes a new move => broadcast that move to the opponent
*/
socket.on('new-move', function(data) {
socket.broadcast.to(data.token).emit('new-move', data);
});

/*
* A player resigns => notify opponent, leave game room and delete the game
*/
socket.on('resign', function (data) {
var room = data.token;
if (room in games) {
Expand All @@ -105,6 +123,9 @@ module.exports = function (server) {
}
});

/*
* A player disconnects => notify opponent, leave game room and delete the game
*/
socket.on('disconnect', function(data){
users--;
monitor.emit('update', {nbUsers: users, nbGames: Object.keys(games).length});
Expand All @@ -123,6 +144,9 @@ module.exports = function (server) {

});

/*
* Utility function to find the player name of a given side.
*/
function getPlayerName(room, side) {
var game = games[room];
for (var p in game.players) {
Expand Down
83 changes: 77 additions & 6 deletions public/javascripts/chesshub.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,34 @@
$( document ).ready(function() {

/*
* When the user is logged in, it's name is loaded in the "data" attribute of the "#loggedUser" element.
* This name is then passed to the socket connection handshake query
*/
var username;
if($("#loggedUser").length) {
username = $("#loggedUser").data("user");
} else {
username = "Anonymous";
}

// socket used for real time games
var socket = io('http://localhost:3000', { query: 'user=' + username });

//socket used to broadcast live games on tv page
var tvSocket = io('http://localhost:3000/tv');

// socket used to broadcast events to monitoring page
var monitorSocket = io('http://localhost:3000/monitor');

// Puzzle of the day: initialize a chess board with puzzle data
if ($("#pod").length) {
var pod = new ChessBoard('pod', $("#pod").data('fen'));
$('#podSolution').popover();
}

/*
* Show error message on login failure
*/
if ($("#loginError").length && !$("#loginError").is(':empty')) {

Messenger({
Expand All @@ -28,6 +41,9 @@ $( document ).ready(function() {
});
}

/*
* Show error message on registration failure
*/
if ($("#registerError").length && !$("#registerError").is(':empty')) {

Messenger({
Expand All @@ -40,6 +56,9 @@ $( document ).ready(function() {
});
}

/*
* Show message on successful logout
*/
if ($("#logoutSuccess").length && !$("#logoutSuccess").is(':empty')) {

Messenger({
Expand All @@ -52,6 +71,9 @@ $( document ).ready(function() {
});
}

/*
* Show welcome message on registration success
*/
if ($("#registerSuccess").length && !$("#registerSuccess").is(':empty')) {

Messenger({
Expand All @@ -64,6 +86,9 @@ $( document ).ready(function() {
});
}

/*
* Show welcome message on login success
*/
if ($("#welcomeMessage").length && !$("#welcomeMessage").is(':empty')) {

Messenger({
Expand All @@ -76,6 +101,9 @@ $( document ).ready(function() {
});
}

/*
* Show message on account update success
*/
if ($("#updateStatus").length && !$("#updateStatus").is(':empty')) {

var ok = $("#updateStatus").data('ok');
Expand All @@ -96,12 +124,18 @@ $( document ).ready(function() {
*/
if ($("#board").length) {

/*
* Initialize a new game
*/
var game = new Chess();
var pgnEl = $('#pgn');
var token = $("#board").data('token');
var side = $("#board").data('side');
var opponentSide = side === "black" ? "white" : "black";

/*
* When a piece is dragged, check if it the current player has the turn
*/
var onDragStart = function(source, piece, position, orientation) {
if (game.game_over() === true ||
(game.turn() === 'w' && piece.search(/^b/) !== -1) ||
Expand All @@ -111,6 +145,9 @@ $( document ).ready(function() {
}
};

/*
* When a piece is dropped, check if the move is legal
*/
var onDrop = function(source, target, piece, newPos, oldPos, orientation) {
// see if the move is legal
var move = game.move({
Expand Down Expand Up @@ -140,6 +177,9 @@ $( document ).ready(function() {
board.position(game.fen());
};

/*
* Initialize a new board
*/
var cfg = {
draggable: true,
position: 'start',
Expand All @@ -153,27 +193,39 @@ $( document ).ready(function() {
};
var board = new ChessBoard('board', cfg);

/*
* When the game page is loaded, fire a join event to join the game room
*/
socket.emit('join', {
'token': token,
'side': side
});

socket.on('wait', function (data) {
/*
* When a new game is created, the game creator should wait for an opponent to join the game
*/
socket.on('wait', function () {
var url = "http:/localhost:3000/game/" + token + "/" + opponentSide;
$('#gameUrl').html(url);
$('#gameUrlPopup').modal({
$('#gameUrlPopup').modal({ // show modal popup to wait for opponent
keyboard: false,
backdrop: 'static'
});
});

/*
* A second player has joined the game => the game can start
*/
socket.on('ready', function (data) {
$('#turn-w').addClass("fa fa-spinner");
$('#player-white').html(data.white);
$('#player-black').html(data.black);
$('#gameUrlPopup').modal('hide');
});

/*
* A new move has been made by a player => update the UI
*/
socket.on('new-move', function(data){
game.move({ from: data.source, to: data.target });
board.position( game.fen() );
Expand All @@ -182,6 +234,9 @@ $( document ).ready(function() {
$('#turn-' + game.turn()).addClass("fa fa-spinner");
});

/*
* A player resigns the game
*/
$('#resignButton').click(function (ev) {
ev.preventDefault();
socket.emit('resign', {
Expand All @@ -190,6 +245,9 @@ $( document ).ready(function() {
});
});

/*
* Notify opponent resignation
*/
socket.on('player-resigned', function (data) {
$('#gameResult').html(data.side + ' resigned.');
$('#gameResultPopup').modal({
Expand All @@ -198,15 +256,21 @@ $( document ).ready(function() {
});
});

socket.on('opponent-disconnected', function (data) {
/*
* Notify opponent disconnection
*/
socket.on('opponent-disconnected', function () {
$('#gameResult').html('Your opponent has been disconnected.');
$('#gameResultPopup').modal({
keyboard: false,
backdrop: 'static'
});
});

socket.on('full', function (data) {
/*
* Notify that the game is full => impossible to join the game
*/
socket.on('full', function () {
alert("This game has been already joined by another person.");
window.location = '/';
});
Expand All @@ -217,8 +281,8 @@ $( document ).ready(function() {
* TV page
*/
if ($("#trg").length) {
var trg = new ChessBoard('trg', 'start');
tvSocket.on('newTrgMove', function(data){
var trg = new ChessBoard('trg', 'start'); // initialize a chess board with the top rated live game
tvSocket.on('new-top-rated-game-move', function(data){
trg.position(data.fen);
if ($("#tv-game-details").length) {
$("#pgn").html(data.pgn);
Expand All @@ -237,12 +301,19 @@ $( document ).ready(function() {
var nbUsers, nbGames, totalGames;

monitorSocket.on('update', function(data) {
/*
* load monitoring event data
*/
nbUsers = data.nbUsers;
nbGames = data.nbGames;
totalGames = nbGames; // todo: should be set from data.totalGames;
$("#nbUsers").html(nbUsers);
$("#nbGames").html(nbGames);
$("#totalGames").html(totalGames);

/*
* Update the status chart
*/
var chart = $('#chart').highcharts();
chart.series[0].addPoint(nbUsers, true, true);
chart.series[1].addPoint(nbGames, true, true);
Expand Down

0 comments on commit ae4f888

Please sign in to comment.