From 55165839a50c6caeb7808d48430a7b7d9fbda7c8 Mon Sep 17 00:00:00 2001 From: tannerkrewson Date: Tue, 26 Jul 2016 22:55:13 -0500 Subject: [PATCH] Conform project to ESLint rules --- .eslintrc | 30 ++ app.js | 42 +- bin/www | 76 +-- drawphone.js | 993 +++++++++++++++++++------------------ package.json | 61 +-- public/js/client.js | 1153 +++++++++++++++++++++---------------------- routes/index.js | 16 +- routes/main.js | 22 +- routes/socketio.js | 163 +++--- words.js | 8 +- 10 files changed, 1298 insertions(+), 1266 deletions(-) create mode 100644 .eslintrc diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 00000000..1bd07c2c --- /dev/null +++ b/.eslintrc @@ -0,0 +1,30 @@ +{ + "env": { + "browser": true, + "es6": true, + "node": true + }, + "extends": "eslint:recommended", + "parserOptions": { + "sourceType": "module" + }, + "rules": { + "indent": [ + "error", + "tab" + ], + "linebreak-style": [ + "error", + "windows" + ], + "quotes": [ + "error", + "single" + ], + "semi": [ + "error", + "always" + ], + "no-console": "off" + } +} diff --git a/app.js b/app.js index 81b73faa..6aa8a7de 100644 --- a/app.js +++ b/app.js @@ -1,7 +1,7 @@ var express = require('express'); var socketio = require('socket.io'); var path = require('path'); -var favicon = require('serve-favicon'); +//var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); @@ -25,19 +25,21 @@ app.set('view engine', 'jade'); //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); if (devModeEnabled) { - app.use(logger('dev')); + app.use(logger('dev')); } app.use(bodyParser.json()); -app.use(bodyParser.urlencoded({ extended: false })); +app.use(bodyParser.urlencoded({ + extended: false +})); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); // catch 404 and forward to error handler -app.use(function(req, res, next) { - var err = new Error('Not Found'); - err.status = 404; - next(err); +app.use(function (req, res, next) { + var err = new Error('Not Found'); + err.status = 404; + next(err); }); // error handlers @@ -45,23 +47,23 @@ app.use(function(req, res, next) { // development error handler // will print stacktrace if (devModeEnabled) { - app.use(function(err, req, res, next) { - res.status(err.status || 500); - res.render('error', { - message: err.message, - error: err - }); - }); + app.use(function (err, req, res) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: err + }); + }); } // production error handler // no stacktraces leaked to user -app.use(function(err, req, res, next) { - res.status(err.status || 500); - res.render('error', { - message: err.message, - error: {} - }); +app.use(function (err, req, res) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: {} + }); }); diff --git a/bin/www b/bin/www index 7c2357e5..203bcebd 100644 --- a/bin/www +++ b/bin/www @@ -25,8 +25,8 @@ var server = http.createServer(app); * Attach Socket.IO to the Express server. */ - var io = app.io; - io.attach(server); +var io = app.io; +io.attach(server); /** * Listen on provided port, on all network interfaces. @@ -42,19 +42,19 @@ server.on('listening', onListening); */ function normalizePort(val) { - var port = parseInt(val, 10); + var port = parseInt(val, 10); - if (isNaN(port)) { - // named pipe - return val; - } + if (isNaN(port)) { + // named pipe + return val; + } - if (port >= 0) { - // port number - return port; - } + if (port >= 0) { + // port number + return port; + } - return false; + return false; } /** @@ -62,27 +62,27 @@ function normalizePort(val) { */ function onError(error) { - if (error.syscall !== 'listen') { - throw error; - } - - var bind = typeof port === 'string' - ? 'Pipe ' + port - : 'Port ' + port; - - // handle specific listen errors with friendly messages - switch (error.code) { - case 'EACCES': - console.error(bind + ' requires elevated privileges'); - process.exit(1); - break; - case 'EADDRINUSE': - console.error(bind + ' is already in use'); - process.exit(1); - break; - default: - throw error; - } + if (error.syscall !== 'listen') { + throw error; + } + + var bind = typeof port === 'string' ? + 'Pipe ' + port : + 'Port ' + port; + + // handle specific listen errors with friendly messages + switch (error.code) { + case 'EACCES': + console.error(bind + ' requires elevated privileges'); + process.exit(1); + break; + case 'EADDRINUSE': + console.error(bind + ' is already in use'); + process.exit(1); + break; + default: + throw error; + } } /** @@ -90,9 +90,9 @@ function onError(error) { */ function onListening() { - var addr = server.address(); - var bind = typeof addr === 'string' - ? 'pipe ' + addr - : 'port ' + addr.port; - debug('Listening on ' + bind); + var addr = server.address(); + var bind = typeof addr === 'string' ? + 'pipe ' + addr : + 'port ' + addr.port; + debug('Listening on ' + bind); } diff --git a/drawphone.js b/drawphone.js index ea67170a..7fb6db84 100644 --- a/drawphone.js +++ b/drawphone.js @@ -3,601 +3,600 @@ * By Tanner Krewson */ -var shuffle = require('knuth-shuffle').knuthShuffle +var shuffle = require('knuth-shuffle').knuthShuffle; var getRandomWord = require('./words.js'); function Drawphone(devModeEnabled) { - this.games = []; - - //add the dev game - if (devModeEnabled) { - this.newGame('ffff'); - } -} - -Drawphone.prototype.newGame = function(forceCode) { - - var newCode; - if (forceCode) { - newCode = forceCode; - } else { - newCode = this.generateCode(); - } - - var self = this; - var newGame = new Game(newCode, function() { - //will be ran when this game has 0 players left - self.removeGame(newCode); - }); - this.games.push(newGame); - console.log(newCode + ' created'); - return newGame; -} + this.games = []; + + //add the dev game + if (devModeEnabled) { + this.newGame('ffff'); + } +} + +Drawphone.prototype.newGame = function (forceCode) { + + var newCode; + if (forceCode) { + newCode = forceCode; + } else { + newCode = this.generateCode(); + } + + var self = this; + var newGame = new Game(newCode, function () { + //will be ran when this game has 0 players left + self.removeGame(newCode); + }); + this.games.push(newGame); + console.log(newCode + ' created'); + return newGame; +}; -Drawphone.prototype.findGame = function(code) { - for (var i = 0; i < this.games.length; i++) { - if (this.games[i].code === code.toLowerCase()) { - return this.games[i]; - } - } - return false; -} +Drawphone.prototype.findGame = function (code) { + for (var i = 0; i < this.games.length; i++) { + if (this.games[i].code === code.toLowerCase()) { + return this.games[i]; + } + } + return false; +}; -Drawphone.prototype.generateCode = function() { - var code; - do { - //generate 6 letter code - code = ""; - var possible = "abcdefghijklmnopqrstuvwxyz"; - for(var i=0; i < 4; i++ ) { - code += possible.charAt(Math.floor(Math.random() * possible.length)); - } - //make sure the code is not already in use - } while (this.findGame(code)); - return code; -} +Drawphone.prototype.generateCode = function () { + var code; + do { + //generate 6 letter code + code = ''; + var possible = 'abcdefghijklmnopqrstuvwxyz'; + for (var i = 0; i < 4; i++) { + code += possible.charAt(Math.floor(Math.random() * possible.length)); + } + //make sure the code is not already in use + } while (this.findGame(code)); + return code; +}; -Drawphone.prototype.removeGame = function(code) { - var game = this.findGame(code); +Drawphone.prototype.removeGame = function (code) { + var game = this.findGame(code); - var index = this.games.indexOf(game); - if (index > -1) { - this.games.splice(index, 1); - console.log(code + ' removed'); - } -} + var index = this.games.indexOf(game); + if (index > -1) { + this.games.splice(index, 1); + console.log(code + ' removed'); + } +}; function Game(code, onEmpty) { - this.code = code; - this.onEmpty = onEmpty; - this.players = []; - this.admin; - this.inProgress = false; - this.viewingResults = false; - this.currentRound; - - this.currentId = 1; - this.currentRoundNum = 1; -} + this.code = code; + this.onEmpty = onEmpty; + this.players = []; + this.admin; + this.inProgress = false; + this.viewingResults = false; + this.currentRound; -Game.prototype.newPlayer = function(name, socket) { - return new Player(name, socket, this.getNextId()); + this.currentId = 1; + this.currentRoundNum = 1; } -Game.prototype.addPlayer = function(name, socket) { - var newPlayer = this.newPlayer(name, socket); - this.initPlayer(newPlayer); - this.players.push(newPlayer); - this.sendUpdatedPlayersList(); - return newPlayer; -} +Game.prototype.newPlayer = function (name, socket) { + return new Player(name, socket, this.getNextId()); +}; -Game.prototype.initPlayer = function(newPlayer) { - //if this is the first user, make them admin - if (this.players.length === 0) { - this.admin = newPlayer; - newPlayer.makeAdmin(); - } - - //when this player disconnects, remove them from this game - var self = this; - newPlayer.socket.on('disconnect', function() { - newPlayer.isConnected = false; - if (self.inProgress) { - self.currentRound.findReplacementFor(newPlayer); - } else { - self.removePlayer(newPlayer.id); - } - self.onPlayerDisconnect(newPlayer); - self.sendUpdatedPlayersList(); - }); -} +Game.prototype.addPlayer = function (name, socket) { + var newPlayer = this.newPlayer(name, socket); + this.initPlayer(newPlayer); + this.players.push(newPlayer); + this.sendUpdatedPlayersList(); + return newPlayer; +}; -Game.prototype.onPlayerDisconnect = function(oldPlayer) { - //if the player was admin - if (oldPlayer.id === this.admin.id) { - //find the first connected player to be admin - for (var i = 0; i < this.players.length; i++) { - var thisPlayer = this.players[i]; - if (thisPlayer.isConnected) { - this.admin = thisPlayer; - thisPlayer.makeAdmin(); - break; - } - } - } - - //if someone leaves while viewing results, we need to check again - // or everyone will get stuck on the Thanks for playing screen - if (this.viewingResults) { - this.currentRound.end(); - } - - var allPlayersDisconnected = true; - for (var i = 0; i < this.players.length; i++) { - if (this.players[i].isConnected) { - allPlayersDisconnected = false; - break; - } - } - if (allPlayersDisconnected) { - this.onEmpty(); - } -} +Game.prototype.initPlayer = function (newPlayer) { + //if this is the first user, make them admin + if (this.players.length === 0) { + this.admin = newPlayer; + newPlayer.makeAdmin(); + } + + //when this player disconnects, remove them from this game + var self = this; + newPlayer.socket.on('disconnect', function () { + newPlayer.isConnected = false; + if (self.inProgress) { + self.currentRound.findReplacementFor(newPlayer); + } else { + self.removePlayer(newPlayer.id); + } + self.onPlayerDisconnect(newPlayer); + self.sendUpdatedPlayersList(); + }); +}; -Game.prototype.removePlayer = function(id) { - var player = this.getPlayer(id); +Game.prototype.onPlayerDisconnect = function (oldPlayer) { + //if the player was admin + if (oldPlayer.id === this.admin.id) { + //find the first connected player to be admin + for (var i = 0; i < this.players.length; i++) { + var thisPlayer = this.players[i]; + if (thisPlayer.isConnected) { + this.admin = thisPlayer; + thisPlayer.makeAdmin(); + break; + } + } + } + + //if someone leaves while viewing results, we need to check again + // or everyone will get stuck on the Thanks for playing screen + if (this.viewingResults) { + this.currentRound.end(); + } + + var allPlayersDisconnected = true; + for (var j = 0; j < this.players.length; j++) { + if (this.players[j].isConnected) { + allPlayersDisconnected = false; + break; + } + } + if (allPlayersDisconnected) { + this.onEmpty(); + } +}; - var index = this.players.indexOf(player); - if (index > -1) { - this.players.splice(index, 1); - } +Game.prototype.removePlayer = function (id) { + var player = this.getPlayer(id); - //if there are no players left - if (this.players.length === 0) { - this.onEmpty(); - } -} + var index = this.players.indexOf(player); + if (index > -1) { + this.players.splice(index, 1); + } -Game.prototype.getPlayer = function(id) { - for (var i = 0; i < this.players.length; i++) { - if (this.players[i].id === id) { - return this.players[i]; - } - } - return false; -} + //if there are no players left + if (this.players.length === 0) { + this.onEmpty(); + } +}; -Game.prototype.getNextId = function() { - return this.currentId++; -} +Game.prototype.getPlayer = function (id) { + for (var i = 0; i < this.players.length; i++) { + if (this.players[i].id === id) { + return this.players[i]; + } + } + return false; +}; -Game.prototype.getNextRoundNum = function() { - return this.currentRoundNum++; -} +Game.prototype.getNextId = function () { + return this.currentId++; +}; -Game.prototype.getJsonGame = function () { - var players = []; - this.players.forEach(function(player) { - players.push(player.getJson()); - }); +Game.prototype.getNextRoundNum = function () { + return this.currentRoundNum++; +}; - var jsonGame = { - code: this.code, - players, - inProgress: this.inProgress - }; - return jsonGame; +Game.prototype.getJsonGame = function () { + var players = []; + this.players.forEach(function (player) { + players.push(player.getJson()); + }); + + var jsonGame = { + code: this.code, + players, + inProgress: this.inProgress + }; + return jsonGame; }; -Game.prototype.sendUpdatedPlayersList = function() { - this.sendToAll('updatePlayerList', this.getJsonGame().players); -} +Game.prototype.sendUpdatedPlayersList = function () { + this.sendToAll('updatePlayerList', this.getJsonGame().players); +}; -Game.prototype.sendToAll = function(event, data) { - var self = this; - this.players.forEach(function(player) { - player.socket.emit(event, { - success: true, - gameCode: self.code, - player: player.getJson(), - data - }); - }); -} +Game.prototype.sendToAll = function (event, data) { + var self = this; + this.players.forEach(function (player) { + player.socket.emit(event, { + success: true, + gameCode: self.code, + player: player.getJson(), + data + }); + }); +}; -Game.prototype.startNewRound = function() { - this.inProgress = true; - - var self = this; - this.currentRound = new Round(this.getNextRoundNum(), this.players, function() { - //ran when results are sent - self.inProgress = false; - self.viewingResults = true; - }, function() { - //ran when everyone is done viewing results - self.sendUpdatedPlayersList(); - self.viewingResults = false; - }); - - this.currentRound.start(); -} +Game.prototype.startNewRound = function () { + this.inProgress = true; + + var self = this; + this.currentRound = new Round(this.getNextRoundNum(), this.players, function () { + //ran when results are sent + self.inProgress = false; + self.viewingResults = true; + }, function () { + //ran when everyone is done viewing results + self.sendUpdatedPlayersList(); + self.viewingResults = false; + }); + + this.currentRound.start(); +}; function Round(number, players, onResults, onEnd) { - this.number = number; - this.players = players; - this.onResults = onResults; - this.onEnd = onEnd; - this.chains = []; - this.disconnectedPlayers = []; - //on creation, chains will already have one link - this.shouldHaveThisManyLinks = 2; - - this.finalNumOfLinks; -} - -Round.prototype.start = function() { - //each player will have to complete one link for how many players there are - // the final number of links each chain should have at the end of this - // round is number of players + 1, because each chain has an extra link - // for the original word - this.finalNumOfLinks = this.players.length + 1; - - //shuffle the player list in place - shuffle(this.players); + this.number = number; + this.players = players; + this.onResults = onResults; + this.onEnd = onEnd; + this.chains = []; + this.disconnectedPlayers = []; + //on creation, chains will already have one link + this.shouldHaveThisManyLinks = 2; + + this.finalNumOfLinks; +} + +Round.prototype.start = function () { + //each player will have to complete one link for how many players there are + // the final number of links each chain should have at the end of this + // round is number of players + 1, because each chain has an extra link + // for the original word + this.finalNumOfLinks = this.players.length + 1; + + //shuffle the player list in place + shuffle(this.players); + + var currentChainId = 0; + var self = this; + this.players.forEach(function (player) { + //give each player a chain of their own + var thisChain = new Chain(getRandomWord(), player, currentChainId++); + self.chains.push(thisChain); + + //sends the link, then runs the function when the player sends it back + // when the 'finishedLink' event is received + thisChain.sendLastLinkToThen(player, self.finalNumOfLinks, function (data) { + self.receiveLink(player, data.link, thisChain.id); + }); + + }); - var currentChainId = 0; - var self = this; - this.players.forEach(function(player) { - //give each player a chain of their own - var thisChain = new Chain(getRandomWord(), player, currentChainId++); - self.chains.push(thisChain); - - //sends the link, then runs the function when the player sends it back - // when the 'finishedLink' event is received - thisChain.sendLastLinkToThen(player, self.finalNumOfLinks, function(data) { - self.receiveLink(player, data.link, thisChain.id); - }); - - }); - -} +}; -Round.prototype.receiveLink = function(player, receivedLink, chainId) { - var chain = this.getChain(chainId); +Round.prototype.receiveLink = function (player, receivedLink, chainId) { + var chain = this.getChain(chainId); - if (receivedLink.type === 'drawing') { - chain.addLink(new DrawingLink(player, receivedLink.data)); - } else if (receivedLink.type === 'word'){ - chain.addLink(new WordLink(player, receivedLink.data)); - } else { - console.log('receivedLink.type is ' + receivedLink.type); - } + if (receivedLink.type === 'drawing') { + chain.addLink(new DrawingLink(player, receivedLink.data)); + } else if (receivedLink.type === 'word') { + chain.addLink(new WordLink(player, receivedLink.data)); + } else { + console.log('receivedLink.type is ' + receivedLink.type); + } - this.updateWaitingList(); - this.nextLinkIfEveryoneIsDone(); -} + this.updateWaitingList(); + this.nextLinkIfEveryoneIsDone(); +}; -Round.prototype.nextLinkIfEveryoneIsDone = function() { - var listNotFinished = this.getListOfNotFinishedPlayers(); - var allFinished = listNotFinished.length === 0; - var noneDisconnected = this.disconnectedPlayers.length === 0; - - if (allFinished && noneDisconnected) { - //check if that was the last link - if (this.shouldHaveThisManyLinks === this.finalNumOfLinks) { - this.viewResults(); - } else { - this.startNextLink(); - } - } -} +Round.prototype.nextLinkIfEveryoneIsDone = function () { + var listNotFinished = this.getListOfNotFinishedPlayers(); + var allFinished = listNotFinished.length === 0; + var noneDisconnected = this.disconnectedPlayers.length === 0; + + if (allFinished && noneDisconnected) { + //check if that was the last link + if (this.shouldHaveThisManyLinks === this.finalNumOfLinks) { + this.viewResults(); + } else { + this.startNextLink(); + } + } +}; -Round.prototype.startNextLink = function() { - this.shouldHaveThisManyLinks++; +Round.prototype.startNextLink = function () { + this.shouldHaveThisManyLinks++; - //rotate the chains in place - // this is so that players get a chain they have not already had - this.chains.push(this.chains.shift()); + //rotate the chains in place + // this is so that players get a chain they have not already had + this.chains.push(this.chains.shift()); - //distribute the chains to each player - // players and chains will have the same length - var self = this; - for (var i = 0; i < this.players.length; i++) { - var thisChain = this.chains[i]; - var thisPlayer = this.players[i]; + //distribute the chains to each player + // players and chains will have the same length + var self = this; + for (var i = 0; i < this.players.length; i++) { + var thisChain = this.chains[i]; + var thisPlayer = this.players[i]; - thisChain.lastPlayerSentTo = thisPlayer.getJson(); + thisChain.lastPlayerSentTo = thisPlayer.getJson(); - //sends the link, then runs the function when the player sends it back - // when the 'finishedLink' event is received - (function(chain, player) { - chain.sendLastLinkToThen(player, self.finalNumOfLinks, function(data) { - self.receiveLink(player, data.link, chain.id); - }); - })(thisChain, thisPlayer); + //sends the link, then runs the function when the player sends it back + // when the 'finishedLink' event is received + (function (chain, player) { + chain.sendLastLinkToThen(player, self.finalNumOfLinks, function (data) { + self.receiveLink(player, data.link, chain.id); + }); + })(thisChain, thisPlayer); - } -} + } +}; -Round.prototype.getChain = function(id) { - for (var i = 0; i < this.chains.length; i++) { - if (this.chains[i].id === id) { - return this.chains[i]; - } - } - return false; -} +Round.prototype.getChain = function (id) { + for (var i = 0; i < this.chains.length; i++) { + if (this.chains[i].id === id) { + return this.chains[i]; + } + } + return false; +}; -Round.prototype.getChainByOwnerId = function(ownerId) { - for (var i = 0; i < this.chains.length; i++) { - if (this.chains[i].owner.id === ownerId) { - return this.chains[i]; - } - } - return false; -} +Round.prototype.getChainByOwnerId = function (ownerId) { + for (var i = 0; i < this.chains.length; i++) { + if (this.chains[i].owner.id === ownerId) { + return this.chains[i]; + } + } + return false; +}; -Round.prototype.viewResults = function() { - this.onResults(); +Round.prototype.viewResults = function () { + this.onResults(); - var self = this; - this.players.forEach(function(player) { - //get this player's chain, the one in which they drew the first picture - var chain = self.getChainByOwnerId(player.id); + var self = this; + this.players.forEach(function (player) { + //get this player's chain, the one in which they drew the first picture + var chain = self.getChainByOwnerId(player.id); - player.sendThen('viewResults', { - links: chain.links - }, 'doneViewingResults', function(data) { - player.doneViewingResults = true; - self.end(); - }); + player.sendThen('viewResults', { + links: chain.links + }, 'doneViewingResults', function () { + player.doneViewingResults = true; + self.end(); + }); - }); -} + }); +}; -Round.prototype.end = function() { - //check to see if all players are done viewing results - var allDone = true; - for (var i = 0; i < this.players.length; i++) { - var player = this.players[i]; - if (!player.doneViewingResults && player.isConnected) { - allDone = false; - break; - } - } - - if (allDone) { - this.onEnd(); - this.players.forEach(function(player) { - //set it back for the next round - player.doneViewingResults = false; - - player.send('roundOver', {}); - }); - } -} +Round.prototype.end = function () { + //check to see if all players are done viewing results + var allDone = true; + for (var i = 0; i < this.players.length; i++) { + var player = this.players[i]; + if (!player.doneViewingResults && player.isConnected) { + allDone = false; + break; + } + } + + if (allDone) { + this.onEnd(); + this.players.forEach(function (player) { + //set it back for the next round + player.doneViewingResults = false; + + player.send('roundOver', {}); + }); + } +}; -Round.prototype.findReplacementFor = function(player) { - this.disconnectedPlayers.push(player.getJson()); - this.updateWaitingList(); -} +Round.prototype.findReplacementFor = function (player) { + this.disconnectedPlayers.push(player.getJson()); + this.updateWaitingList(); +}; -Round.prototype.getPlayersThatNeedToBeReplaced = function() { - return this.disconnectedPlayers; -} +Round.prototype.getPlayersThatNeedToBeReplaced = function () { + return this.disconnectedPlayers; +}; -Round.prototype.canBeReplaced = function(playerToReplaceId) { - for (var i = 0; i < this.disconnectedPlayers.length; i++) { - if (this.disconnectedPlayers[i].id === playerToReplaceId) { - return true; - } - } - return false; -} +Round.prototype.canBeReplaced = function (playerToReplaceId) { + for (var i = 0; i < this.disconnectedPlayers.length; i++) { + if (this.disconnectedPlayers[i].id === playerToReplaceId) { + return true; + } + } + return false; +}; -Round.prototype.replacePlayer = function(playerToReplaceId, newPlayer) { - for (var i = 0; i < this.disconnectedPlayers.length; i++) { - if (this.disconnectedPlayers[i].id === playerToReplaceId) { - //give 'em the id of the old player - newPlayer.id = this.disconnectedPlayers[i].id; - - //replace 'em - var playerToReplaceIndex = this.getPlayerIndexById(playerToReplaceId); - this.players[playerToReplaceIndex] = newPlayer; - - //delete 'em from disconnectedPlayers - this.disconnectedPlayers.splice(i, 1); - - //check if the disconnectedPlayer (dp) had submitted their link - var dpChain = this.getChainByLastSentPlayerId(newPlayer.id); - var dpDidFinishTheirLink = dpChain.getLength() === this.shouldHaveThisManyLinks - if (dpDidFinishTheirLink) { - //send this player to the waiting for players page - newPlayer.socket.emit('showWaitingList', {}); - } else { - //send them the link they need to finish - var self = this; - dpChain.sendLastLinkToThen(newPlayer, this.finalNumOfLinks, function(data) { - self.receiveLink(newPlayer, data.link, dpChain.id); - }); - } - return this.players[playerToReplaceIndex]; - } - } -} +Round.prototype.replacePlayer = function (playerToReplaceId, newPlayer) { + for (var i = 0; i < this.disconnectedPlayers.length; i++) { + if (this.disconnectedPlayers[i].id === playerToReplaceId) { + //give 'em the id of the old player + newPlayer.id = this.disconnectedPlayers[i].id; + + //replace 'em + var playerToReplaceIndex = this.getPlayerIndexById(playerToReplaceId); + this.players[playerToReplaceIndex] = newPlayer; + + //delete 'em from disconnectedPlayers + this.disconnectedPlayers.splice(i, 1); + + //check if the disconnectedPlayer (dp) had submitted their link + var dpChain = this.getChainByLastSentPlayerId(newPlayer.id); + var dpDidFinishTheirLink = dpChain.getLength() === this.shouldHaveThisManyLinks; + if (dpDidFinishTheirLink) { + //send this player to the waiting for players page + newPlayer.socket.emit('showWaitingList', {}); + } else { + //send them the link they need to finish + var self = this; + dpChain.sendLastLinkToThen(newPlayer, this.finalNumOfLinks, function (data) { + self.receiveLink(newPlayer, data.link, dpChain.id); + }); + } + return this.players[playerToReplaceIndex]; + } + } +}; -Round.prototype.updateWaitingList = function() { - this.sendToAll('updateWaitingList', { - notFinished: this.getListOfNotFinishedPlayers(), - disconnected: this.disconnectedPlayers - }); -} +Round.prototype.updateWaitingList = function () { + this.sendToAll('updateWaitingList', { + notFinished: this.getListOfNotFinishedPlayers(), + disconnected: this.disconnectedPlayers + }); +}; -Round.prototype.getListOfNotFinishedPlayers = function() { - var playerList = []; +Round.prototype.getListOfNotFinishedPlayers = function () { + var playerList = []; - //check to make sure every chain is the same length - for (var i = 0; i < this.chains.length; i++) { - var thisChain = this.chains[i]; - var isLastPlayerSentToConnected = this.getPlayer(thisChain.lastPlayerSentTo.id).isConnected; + //check to make sure every chain is the same length + for (var i = 0; i < this.chains.length; i++) { + var thisChain = this.chains[i]; + var isLastPlayerSentToConnected = this.getPlayer(thisChain.lastPlayerSentTo.id).isConnected; - if (thisChain.getLength() !== this.shouldHaveThisManyLinks && isLastPlayerSentToConnected) { - playerList.push(thisChain.lastPlayerSentTo); - } - } + if (thisChain.getLength() !== this.shouldHaveThisManyLinks && isLastPlayerSentToConnected) { + playerList.push(thisChain.lastPlayerSentTo); + } + } - return playerList; -} + return playerList; +}; -Round.prototype.getPlayer = function(id) { - for (var i = 0; i < this.players.length; i++) { - if (this.players[i].id === id) { - return this.players[i]; - } - } - return false; -} +Round.prototype.getPlayer = function (id) { + for (var i = 0; i < this.players.length; i++) { + if (this.players[i].id === id) { + return this.players[i]; + } + } + return false; +}; -Round.prototype.getPlayerIndexById = function(id) { - for (var i = 0; i < this.players.length; i++) { - if (this.players[i].id === id) { - return i; - } - } - return false; -} +Round.prototype.getPlayerIndexById = function (id) { + for (var i = 0; i < this.players.length; i++) { + if (this.players[i].id === id) { + return i; + } + } + return false; +}; -Round.prototype.getChainByLastSentPlayerId = function(id) { - for (var i = 0; i < this.chains.length; i++) { - if (this.chains[i].lastPlayerSentTo.id === id) { - return this.chains[i]; - } - } - return false; -} +Round.prototype.getChainByLastSentPlayerId = function (id) { + for (var i = 0; i < this.chains.length; i++) { + if (this.chains[i].lastPlayerSentTo.id === id) { + return this.chains[i]; + } + } + return false; +}; -Round.prototype.sendToAll = function(event, data) { - this.players.forEach(function(player) { - player.send(event, data); - }); -} +Round.prototype.sendToAll = function (event, data) { + this.players.forEach(function (player) { + player.send(event, data); + }); +}; // A chain is the 'chain' of drawings and words. // A link is the individual drawing or word in the chain. function Chain(firstWord, owner, id) { - this.owner = owner; - this.links = []; - this.id = id; + this.owner = owner; + this.links = []; + this.id = id; - this.lastPlayerSentTo = owner.getJson(); + this.lastPlayerSentTo = owner.getJson(); - this.addLink(new WordLink(this.owner, firstWord)); + this.addLink(new WordLink(this.owner, firstWord)); } -Chain.prototype.addLink = function(link) { - this.links.push(link); -} +Chain.prototype.addLink = function (link) { + this.links.push(link); +}; -Chain.prototype.getLastLink = function() { - return this.links[this.links.length - 1]; -} +Chain.prototype.getLastLink = function () { + return this.links[this.links.length - 1]; +}; -Chain.prototype.getLength = function() { - return this.links.length; -} +Chain.prototype.getLength = function () { + return this.links.length; +}; //returns true if the player has a link in this chain already -Chain.prototype.playerHasLink = function(player) { - for (var i = 0; i < this.links.length; i++) { - if (this.links[i].player.id === player.id) { - return true; - } - } - return false; -} +Chain.prototype.playerHasLink = function (player) { + for (var i = 0; i < this.links.length; i++) { + if (this.links[i].player.id === player.id) { + return true; + } + } + return false; +}; -Chain.prototype.sendLastLinkToThen = function(player, finalCount, next) { - //sends the link, then runs the second function - // when the 'finishedLink' event is received - player.sendThen('nextLink', { - link: this.getLastLink(), - chainId: this.id, - count: this.getLength(), - finalCount: finalCount - 1 - }, 'finishedLink', next); -} +Chain.prototype.sendLastLinkToThen = function (player, finalCount, next) { + //sends the link, then runs the second function + // when the 'finishedLink' event is received + player.sendThen('nextLink', { + link: this.getLastLink(), + chainId: this.id, + count: this.getLength(), + finalCount: finalCount - 1 + }, 'finishedLink', next); +}; function DrawingLink(player, drawing) { - Link.call(this, player, drawing); - this.type = 'drawing'; + Link.call(this, player, drawing); + this.type = 'drawing'; } DrawingLink.prototype = Object.create(Link.prototype); function WordLink(player, word) { - Link.call(this, player, word); - this.type = 'word'; + Link.call(this, player, word); + this.type = 'word'; } WordLink.prototype = Object.create(Link.prototype); function Link(player, data) { - this.player = player.getJson(); - this.data = data; + this.player = player.getJson(); + this.data = data; } function Player(name, socket, id) { - this.name = name; - this.socket = socket; - this.id = id; - this.doneViewingResults = false; - this.isAdmin = false; - this.isConnected = true; -} - -Player.prototype.getJson = function() { - return newPlayer = { - name: this.name, - id: this.id, - isAdmin: this.isAdmin, - isConnected: this.isConnected - } -} + this.name = name; + this.socket = socket; + this.id = id; + this.doneViewingResults = false; + this.isAdmin = false; + this.isConnected = true; +} + +Player.prototype.getJson = function () { + return { + name: this.name, + id: this.id, + isAdmin: this.isAdmin, + isConnected: this.isConnected + }; +}; -Player.prototype.send = function(event, data) { - this.socket.emit(event, { - you: this.getJson(), - data - }); -} +Player.prototype.send = function (event, data) { + this.socket.emit(event, { + you: this.getJson(), + data + }); +}; -Player.prototype.sendThen = function(event, data, onEvent, next) { - this.send(event, data); - this.socket.once(onEvent, next); -} +Player.prototype.sendThen = function (event, data, onEvent, next) { + this.send(event, data); + this.socket.once(onEvent, next); +}; -Player.prototype.sendViewResults = function(thisPlayersChainLinks, next) { - this.socket.emit('viewResults', { - links: thisPlayersChainLinks - }); +Player.prototype.sendViewResults = function (thisPlayersChainLinks, next) { + this.socket.emit('viewResults', { + links: thisPlayersChainLinks + }); - //when the player clicks the done button - var self = this; - this.socket.once('doneViewingResults', function(data) { - next(); - }); -} + //when the player clicks the done button + this.socket.once('doneViewingResults', function () { + next(); + }); +}; -Player.prototype.makeAdmin = function() { - this.isAdmin = true; -} +Player.prototype.makeAdmin = function () { + this.isAdmin = true; +}; module.exports = Drawphone; diff --git a/package.json b/package.json index 4d28a968..626374df 100644 --- a/package.json +++ b/package.json @@ -1,31 +1,34 @@ { - "name": "drawphone", - "version": "1.0.0", - "description": "Telephone with pictures", - "main": "app.js", - "scripts": { - "start": "node ./bin/www", - "test": "echo \"Error: no test specified\" && exit 1" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/tannerkrewson/drawphone.git" - }, - "author": "Tanner Krewson", - "license": "MIT", - "bugs": { - "url": "https://github.com/tannerkrewson/drawphone/issues" - }, - "homepage": "https://github.com/tannerkrewson/drawphone#readme", - "dependencies": { - "body-parser": "~1.15.1", - "cookie-parser": "~1.4.3", - "debug": "~2.2.0", - "express": "~4.13.4", - "jade": "~1.11.0", - "knuth-shuffle": "^1.0.1", - "morgan": "~1.7.0", - "serve-favicon": "~2.3.0", - "socket.io": "^1.4.8" - } + "name": "drawphone", + "version": "1.0.0", + "description": "Telephone with pictures", + "main": "app.js", + "scripts": { + "start": "node ./bin/www", + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/tannerkrewson/drawphone.git" + }, + "author": "Tanner Krewson", + "license": "MIT", + "bugs": { + "url": "https://github.com/tannerkrewson/drawphone/issues" + }, + "homepage": "https://github.com/tannerkrewson/drawphone#readme", + "dependencies": { + "body-parser": "~1.15.1", + "cookie-parser": "~1.4.3", + "debug": "~2.2.0", + "express": "~4.13.4", + "jade": "~1.11.0", + "knuth-shuffle": "^1.0.1", + "morgan": "~1.7.0", + "serve-favicon": "~2.3.0", + "socket.io": "^1.4.8" + }, + "devDependencies": { + "eslint": "^3.1.1" + } } diff --git a/public/js/client.js b/public/js/client.js index 40713673..026703e2 100644 --- a/public/js/client.js +++ b/public/js/client.js @@ -1,20 +1,24 @@ -/* - * Drawphone Client - * By Tanner Krewson - */ +// +// Drawphone Client +// By Tanner Krewson +// + +/* global $, swal, fabric, io */ //blocks use of https, required for the uploads.im api, // as it does not have https -window.onload = function(){ - $(function(){ - if(window.location.protocol==="https:") - window.location.protocol="http"; - }); -} +window.onload = function () { + $(function () { + if (window.location.protocol === 'https:') + window.location.protocol = 'http'; + }); +}; //prevent page from refreshing when Join game buttons are pressed -$(function() { - $("form").submit(function() { return false; }); +$(function () { + $('form').submit(function () { + return false; + }); }); @@ -23,33 +27,33 @@ $(function() { // function hideAll() { - $('#mainmenu').addClass('hidden'); - $('#joinmenu').addClass('hidden'); - $('#newmenu').addClass('hidden'); - $('#lobby').addClass('hidden'); - $('#game').addClass('hidden'); - $('#result').addClass('hidden'); - $('#waiting').addClass('hidden'); - $('#replace').addClass('hidden'); + $('#mainmenu').addClass('hidden'); + $('#joinmenu').addClass('hidden'); + $('#newmenu').addClass('hidden'); + $('#lobby').addClass('hidden'); + $('#game').addClass('hidden'); + $('#result').addClass('hidden'); + $('#waiting').addClass('hidden'); + $('#replace').addClass('hidden'); } function showElement(jq) { - $(jq).removeClass('hidden'); + $(jq).removeClass('hidden'); } function oppositeLinkType(linkType) { - if (linkType === 'drawing') { - return 'word'; - } else { - return 'drawing'; - } + if (linkType === 'drawing') { + return 'word'; + } else { + return 'drawing'; + } } function getDataUrlAsync(canvas, next) { - setTimeout(function() { - var dataUrl = canvas.toDataURL(); - next(dataUrl); - }, 10); + setTimeout(function () { + var dataUrl = canvas.toDataURL(); + next(dataUrl); + }, 10); } //sorry @@ -61,647 +65,642 @@ var globalGameCode = ''; // function Drawphone() { - this.screens = []; - - var self = this; - this.mainMenu = new MainMenu(function() { - //ran when Join Game button is pressed - self.joinMenu.show(); - }, function() { - //ran when New Game button is pressed - self.newMenu.show(); - }); - - this.joinMenu = new JoinMenu(function() { - //ran when Back button is pressed - self.mainMenu.show(); - }); - - this.newMenu = new NewMenu(function() { - //ran when Back button is pressed - self.mainMenu.show(); - }); - - this.lobby = new Lobby(); - - this.game = new Game(function() { - //ran when the round ends - self.lobby.show(); - }, function() { - //ran when the player sends - self.waiting.show(); - }); - - this.results = new Results(); - - this.waiting = new Waiting(); - - this.replace = new Replace(); - - this.screens.push(this.mainMenu); - this.screens.push(this.joinMenu); - this.screens.push(this.newMenu); - this.screens.push(this.lobby); - this.screens.push(this.game); - this.screens.push(this.results); - this.screens.push(this.waiting); - this.screens.push(this.replace); -} + this.screens = []; + + var self = this; + this.mainMenu = new MainMenu(function () { + //ran when Join Game button is pressed + self.joinMenu.show(); + }, function () { + //ran when New Game button is pressed + self.newMenu.show(); + }); + + this.joinMenu = new JoinMenu(function () { + //ran when Back button is pressed + self.mainMenu.show(); + }); + + this.newMenu = new NewMenu(function () { + //ran when Back button is pressed + self.mainMenu.show(); + }); + + this.lobby = new Lobby(); + + this.game = new Game(function () { + //ran when the round ends + self.lobby.show(); + }, function () { + //ran when the player sends + self.waiting.show(); + }); + + this.results = new Results(); + + this.waiting = new Waiting(); -Drawphone.prototype.initializeAll = function() { - this.screens.forEach(function(screen) { - screen.initialize(); - }); + this.replace = new Replace(); - this.attachSocketListeners(); + this.screens.push(this.mainMenu); + this.screens.push(this.joinMenu); + this.screens.push(this.newMenu); + this.screens.push(this.lobby); + this.screens.push(this.game); + this.screens.push(this.results); + this.screens.push(this.waiting); + this.screens.push(this.replace); } -Drawphone.prototype.attachSocketListeners = function() { - socket.on('disconnect', function() { - swal("Connection lost!", "Reloading...", "error"); - //refresh the page - location.reload(); - }); +Drawphone.prototype.initializeAll = function () { + this.screens.forEach(function (screen) { + screen.initialize(); + }); - socket.on('joinGameRes', this.lobby.show.bind(this.lobby)); + this.attachSocketListeners(); +}; - socket.on('updatePlayerList', this.lobby.update.bind(this.lobby)); +Drawphone.prototype.attachSocketListeners = function () { + socket.on('disconnect', function () { + swal('Connection lost!', 'Reloading...', 'error'); + //refresh the page + location.reload(); + }); - socket.on('gameStart', this.game.show.bind(this.game)); + socket.on('joinGameRes', this.lobby.show.bind(this.lobby)); - socket.on('nextLink', this.game.newLink.bind(this.game)); + socket.on('updatePlayerList', this.lobby.update.bind(this.lobby)); - socket.on('roundOver', this.game.roundOver.bind(this.game)); + socket.on('gameStart', this.game.show.bind(this.game)); - socket.on('viewResults', this.results.show.bind(this.results)); + socket.on('nextLink', this.game.newLink.bind(this.game)); - socket.on('showWaitingList', this.waiting.show.bind(this.waiting)); + socket.on('roundOver', this.game.roundOver.bind(this.game)); - socket.on('updateWaitingList', this.waiting.updateWaitingList.bind(this.waiting)); + socket.on('viewResults', this.results.show.bind(this.results)); - socket.on('replacePlayer', this.replace.show.bind(this.replace)); -} + socket.on('showWaitingList', this.waiting.show.bind(this.waiting)); -Drawphone.prototype.begin = function() { - this.mainMenu.show(); -} + socket.on('updateWaitingList', this.waiting.updateWaitingList.bind(this.waiting)); + + socket.on('replacePlayer', this.replace.show.bind(this.replace)); +}; + +Drawphone.prototype.begin = function () { + this.mainMenu.show(); +}; function Screen() { - this.id = ''; - this.title = 'Loading Drawphone...'; - this.subtitle = 'Just a moment!'; + this.id = ''; + this.title = 'Loading Drawphone...'; + this.subtitle = 'Just a moment!'; - this.defaultTitle = 'Drawphone'; - this.defaultSubtitle = 'Telephone with pictures'; + this.defaultTitle = 'Drawphone'; + this.defaultSubtitle = 'Telephone with pictures'; } -Screen.prototype.initialize = function() {} +Screen.prototype.initialize = function () {}; -Screen.prototype.show = function() { - hideAll(); - showElement(this.id); +Screen.prototype.show = function () { + hideAll(); + showElement(this.id); - $('#title').html(this.title); - $('#subtitle').text(this.subtitle); -} + $('#title').html(this.title); + $('#subtitle').text(this.subtitle); +}; -Screen.prototype.setTitle = function(title) { - this.title = title; - $('#title').html(this.title); -} +Screen.prototype.setTitle = function (title) { + this.title = title; + $('#title').html(this.title); +}; -Screen.prototype.setSubtitle = function(subtitle) { - this.subtitle = subtitle; - $('#subtitle').html(this.subtitle); -} +Screen.prototype.setSubtitle = function (subtitle) { + this.subtitle = subtitle; + $('#subtitle').html(this.subtitle); +}; -Screen.prototype.showTitles = function() { - $('#title').html(this.title); - $('#subtitle').html(this.subtitle); -} +Screen.prototype.showTitles = function () { + $('#title').html(this.title); + $('#subtitle').html(this.subtitle); +}; -Screen.prototype.setDefaultTitles = function() { - this.setTitle(this.defaultTitle); - this.setSubtitle(this.defaultSubtitle); -} +Screen.prototype.setDefaultTitles = function () { + this.setTitle(this.defaultTitle); + this.setSubtitle(this.defaultSubtitle); +}; MainMenu.prototype = Object.create(Screen.prototype); function MainMenu(onJoin, onNew) { - Screen.call(this); + Screen.call(this); - this.id = '#mainmenu'; - this.joinButton = $('#joinbtn'); - this.newButton = $('#newbtn'); - this.onJoin = onJoin; - this.onNew = onNew; + this.id = '#mainmenu'; + this.joinButton = $('#joinbtn'); + this.newButton = $('#newbtn'); + this.onJoin = onJoin; + this.onNew = onNew; - Screen.prototype.setDefaultTitles.call(this); + Screen.prototype.setDefaultTitles.call(this); } -MainMenu.prototype.initialize = function() { - Screen.prototype.initialize.call(this); +MainMenu.prototype.initialize = function () { + Screen.prototype.initialize.call(this); - this.joinButton.click(this.onJoin); - this.newButton.click(this.onNew); -} + this.joinButton.click(this.onJoin); + this.newButton.click(this.onNew); +}; JoinMenu.prototype = Object.create(Screen.prototype); function JoinMenu(onBack) { - Screen.call(this); + Screen.call(this); - this.id = '#joinmenu'; - this.backButton = $('#joinmenu-back'); - this.goButton = $('#joinmenu-go'); - this.codeInput = $('#joinincode'); - this.onBack = onBack; + this.id = '#joinmenu'; + this.backButton = $('#joinmenu-back'); + this.goButton = $('#joinmenu-go'); + this.codeInput = $('#joinincode'); + this.onBack = onBack; - Screen.prototype.setDefaultTitles.call(this); + Screen.prototype.setDefaultTitles.call(this); } -JoinMenu.prototype.initialize = function() { - Screen.prototype.initialize.call(this); +JoinMenu.prototype.initialize = function () { + Screen.prototype.initialize.call(this); - this.backButton.click(this.onBack); - this.goButton.click(function() { - var code = $('#joinincode').val(); - var name = $('#joininname').val(); + this.backButton.click(this.onBack); + this.goButton.click(function () { + var code = $('#joinincode').val(); + var name = $('#joininname').val(); - socket.emit('joinGame', { - code, - name - }); - }); + socket.emit('joinGame', { + code, + name + }); + }); - var self = this; - this.codeInput.on('keyup', function(e) { - self.codeInput.val(self.codeInput.val().toLowerCase()); - }); + var self = this; + this.codeInput.on('keyup', function () { + self.codeInput.val(self.codeInput.val().toLowerCase()); + }); - Screen.prototype.setDefaultTitles.call(this); -} + Screen.prototype.setDefaultTitles.call(this); +}; NewMenu.prototype = Object.create(Screen.prototype); function NewMenu(onBack) { - Screen.call(this); + Screen.call(this); - this.id = '#newmenu'; - this.backButton = $('#newmenu-back'); - this.goButton = $('#newmenu-go'); - this.onBack = onBack; + this.id = '#newmenu'; + this.backButton = $('#newmenu-back'); + this.goButton = $('#newmenu-go'); + this.onBack = onBack; - Screen.prototype.setDefaultTitles.call(this); + Screen.prototype.setDefaultTitles.call(this); } -NewMenu.prototype.initialize = function() { - Screen.prototype.initialize.call(this); +NewMenu.prototype.initialize = function () { + Screen.prototype.initialize.call(this); - this.backButton.click(this.onBack); - this.goButton.click(function() { - var name = $('#newinname').val(); + this.backButton.click(this.onBack); + this.goButton.click(function () { + var name = $('#newinname').val(); - socket.emit('newGame', { - name - }); - }); -} + socket.emit('newGame', { + name + }); + }); +}; Lobby.prototype = Object.create(Screen.prototype); function Lobby() { - Screen.call(this); - - this.id = '#lobby'; - this.leaveButton = $('#lobby-leave'); - this.startButton = $('#lobby-start'); - this.gameCode = ''; - - this.userList = new UserList($('#lobby-players')); -} - -Lobby.prototype.initialize = function() { - Screen.prototype.initialize.call(this); - - this.leaveButton.click(function() { - //refresh the page - location.reload(); - }); - this.startButton.click(function() { - socket.emit('tryStartGame', {}); - }); -} - -Lobby.prototype.show = function(data) { - //if this was called by a socket.io event - if (data) { - if (data.success) { - globalGameCode = '' + data.game.code + ''; - this.update({ - success: true, - gameCode: data.game.code, - player: data.you, - data: data.game.players - }); - - } else { - swal(data.error, '', "error"); - return; - } - } - Screen.prototype.show.call(this); -} - -Lobby.prototype.update = function(res) { - if (res.success) { - globalGameCode = '' + res.gameCode + ''; - this.title = 'Game Code: ' + res.gameCode + ''; - this.subtitle = 'Waiting for players...'; - this.userList.update(res.data); - if (res.player.isAdmin) { - //show the start game button - this.startButton.removeClass('hidden'); - } else { - this.startButton.addClass('hidden'); - } - } else { - swal("Error updating lobby", res.error, "error") - } -} - -Lobby.prototype.updatePlayerList = function(list) { - this.userList.update(list); -} + Screen.call(this); + + this.id = '#lobby'; + this.leaveButton = $('#lobby-leave'); + this.startButton = $('#lobby-start'); + this.gameCode = ''; + + this.userList = new UserList($('#lobby-players')); +} + +Lobby.prototype.initialize = function () { + Screen.prototype.initialize.call(this); + + this.leaveButton.click(function () { + //refresh the page + location.reload(); + }); + this.startButton.click(function () { + socket.emit('tryStartGame', {}); + }); +}; + +Lobby.prototype.show = function (data) { + //if this was called by a socket.io event + if (data) { + if (data.success) { + globalGameCode = '' + data.game.code + ''; + this.update({ + success: true, + gameCode: data.game.code, + player: data.you, + data: data.game.players + }); + + } else { + swal(data.error, '', 'error'); + return; + } + } + Screen.prototype.show.call(this); +}; + +Lobby.prototype.update = function (res) { + if (res.success) { + globalGameCode = '' + res.gameCode + ''; + this.title = 'Game Code: ' + res.gameCode + ''; + this.subtitle = 'Waiting for players...'; + this.userList.update(res.data); + if (res.player.isAdmin) { + //show the start game button + this.startButton.removeClass('hidden'); + } else { + this.startButton.addClass('hidden'); + } + } else { + swal('Error updating lobby', res.error, 'error'); + } +}; + +Lobby.prototype.updatePlayerList = function (list) { + this.userList.update(list); +}; Game.prototype = Object.create(Screen.prototype); function Game(onRoundEnd, onWait) { - Screen.call(this); - - this.id = '#game'; - this.onRoundEnd = onRoundEnd; - this.onWait = onWait; - - //initialize fabric.js - this.canvas = new fabric.Canvas('game-drawing-canvas'); - this.canvas.isDrawingMode = true; - this.isCanvasBlank = true; - - window.addEventListener('resize', this.resizeCanvas.bind(this), false); -} - -Game.prototype.initialize = function() { - Screen.prototype.initialize.call(this); - var doneButton = $("#game-send"); - - //bind clear canvas to clear drawing button - var self = this; - $('#game-cleardrawing').click(function() { - self.canvas.clear(); - self.isCanvasBlank = true; - }); - - //if user touches the canvas, it not blank no more - $('#game-drawing').on('mousedown touchstart', function() { - self.isCanvasBlank = false; - }); - - doneButton.click(function() { - self.onDone(); - }); - - //run done when enter key is pressed in word input - $('#game-word-in').keypress(function(e) { - var key = e.which; - if (key === 13) { - self.onDone(); - } - }); - -} - -Game.prototype.show = function() { - Screen.prototype.show.call(this); - Screen.prototype.setSubtitle.call(this, 'Game code: ' + globalGameCode); -} + Screen.call(this); + + this.id = '#game'; + this.onRoundEnd = onRoundEnd; + this.onWait = onWait; + + //initialize fabric.js + this.canvas = new fabric.Canvas('game-drawing-canvas'); + this.canvas.isDrawingMode = true; + this.isCanvasBlank = true; + + window.addEventListener('resize', this.resizeCanvas.bind(this), false); +} + +Game.prototype.initialize = function () { + Screen.prototype.initialize.call(this); + var doneButton = $('#game-send'); + + //bind clear canvas to clear drawing button + var self = this; + $('#game-cleardrawing').click(function () { + self.canvas.clear(); + self.isCanvasBlank = true; + }); + + //if user touches the canvas, it not blank no more + $('#game-drawing').on('mousedown touchstart', function () { + self.isCanvasBlank = false; + }); + + doneButton.click(function () { + self.onDone(); + }); + + //run done when enter key is pressed in word input + $('#game-word-in').keypress(function (e) { + var key = e.which; + if (key === 13) { + self.onDone(); + } + }); + +}; + +Game.prototype.show = function () { + Screen.prototype.show.call(this); + Screen.prototype.setSubtitle.call(this, 'Game code: ' + globalGameCode); +}; + +Game.prototype.showDrawing = function () { + showElement('#game-drawing'); + this.showButtons(true); + this.show(); +}; + +Game.prototype.showWord = function () { + showElement('#game-word'); + this.showButtons(false); + this.show(); +}; + +Game.prototype.showButtons = function (showClearButton) { + if (showClearButton) { + showElement('#game-cleardrawing'); + } else { + $('#game-cleardrawing').addClass('hidden'); + } + showElement('#game-buttons'); +}; + +Game.prototype.hideBoth = function () { + $('#game-drawing').addClass('hidden'); + $('#game-word').addClass('hidden'); + $('#game-buttons').addClass('hidden'); +}; + +Game.prototype.newLink = function (res) { + var lastLink = res.data.link; + var lastLinkType = lastLink.type; + var count = res.data.count; + var finalCount = res.data.finalCount; + var newLinkType = oppositeLinkType(lastLinkType); + + if (lastLinkType === 'drawing') { + //show the previous drawing + $('#game-word-drawingtoname').attr('src', lastLink.data); + + Screen.prototype.setTitle.call(this, 'What is this a drawing of?'); + + //show the word creator + this.showWord(); + } else if (lastLinkType === 'word') { + //clear the previous drawing + this.canvas.clear(); + + Screen.prototype.setTitle.call(this, 'Please draw: ' + lastLink.data); + + //show drawing creator + this.showDrawing(); + + //calculate size of canvas dynamically + this.resizeCanvas(); + } + + Screen.prototype.setSubtitle.call(this, this.subtitle + '   -   ' + count + '/' + finalCount); + + //this will be ran when the done button is clicked, or + // the enter key is pressed in the word input + this.onDone = function () { + this.checkIfDone(newLinkType); + }; +}; + +Game.prototype.checkIfDone = function (newLinkType) { + //hide the drawing + this.hideBoth(); + + var newLink; + var self = this; + if (newLinkType === 'drawing') { + if (this.isCanvasBlank) { + self.showDrawing(); + swal('Your picture is blank!', 'Please draw a picture, then try again.', 'info'); + } else { + self.uploadCanvas(function (url) { + //ran if upload was successful + newLink = url; + self.sendLink(newLinkType, newLink); + }, function () { + //ran if upload was unsuccessful + //reshow the canvas and allow the user to try again + self.showDrawing(); + swal('Upload failed.', 'Try again.', 'error'); + Screen.prototype.setTitle.call(self, 'Upload failed, try again.'); + }); + } + } else if (newLinkType === 'word') { + newLink = $('#game-word-in').val().trim(); + //check if it is blank + if (newLink === '') { + self.showWord(); + swal('Your guess is blank!', 'Please enter a guess, then try again.', 'info'); + } else { + //clear the input + $('#game-word-in').val(''); + this.sendLink(newLinkType, newLink); + } + } +}; + +Game.prototype.uploadCanvas = function (next, err) { + // this code was sourced from: + // http://community.mybb.com/thread-150592.html + // https://github.com/blueimp/JavaScript-Canvas-to-Blob#usage + try { + Screen.prototype.setTitle.call(this, 'Processing...'); + getDataUrlAsync(this.canvas, function (file) { + var blob = window.dataURLtoBlob(file); + var formData = new FormData(); + formData.append('upload', blob, 'drawing.png'); + var xhr = new XMLHttpRequest(); + xhr.open('POST', 'http://uploads.im/api', true); + xhr.onload = function () { + var res = JSON.parse(xhr.responseText); + if (res.status_code === 200) { + var url = res.data.img_url; + next(url); + } else { + err(); + } + }; + xhr.onerror = err; + xhr.send(formData); + Screen.prototype.setTitle.call(this, 'Uploading...'); + }); + } catch (e) { + err(); + } +}; + +Game.prototype.sendLink = function (type, data) { + Screen.prototype.setTitle.call(this, 'Sending...'); + + socket.emit('finishedLink', { + link: { + type, + data + } + }); + this.onWait(); +}; + +Game.prototype.roundOver = function () { + this.onRoundEnd(); +}; + +Game.prototype.resizeCanvas = function () { + var container = $('#game-drawing'); + this.canvas.setHeight(container.width()); + this.canvas.setWidth(container.width()); + this.canvas.renderAll(); +}; -Game.prototype.showDrawing = function() { - showElement('#game-drawing'); - this.showButtons(true); - this.show(); -} - -Game.prototype.showWord = function() { - showElement('#game-word'); - this.showButtons(false); - this.show(); -} - -Game.prototype.showButtons = function(showClearButton) { - if (showClearButton) { - showElement('#game-cleardrawing'); - } - else { - $('#game-cleardrawing').addClass('hidden'); - } - showElement('#game-buttons'); -} - -Game.prototype.hideBoth = function() { - $('#game-drawing').addClass('hidden'); - $('#game-word').addClass('hidden'); - $('#game-buttons').addClass('hidden'); -} - -Game.prototype.newLink = function(res) { - var lastLink = res.data.link; - var lastLinkType = lastLink.type; - var count = res.data.count; - var finalCount = res.data.finalCount; - var newLinkType = oppositeLinkType(lastLinkType); - - if (lastLinkType === 'drawing') { - //show the previous drawing - $('#game-word-drawingtoname').attr("src", lastLink.data); - - Screen.prototype.setTitle.call(this, 'What is this a drawing of?'); - - //show the word creator - this.showWord(); - } - else if (lastLinkType === 'word'){ - //clear the previous drawing - this.canvas.clear(); - - Screen.prototype.setTitle.call(this, 'Please draw: ' + lastLink.data); - //show drawing creator - this.showDrawing(); - - //calculate size of canvas dynamically - this.resizeCanvas(); - } - - Screen.prototype.setSubtitle.call(this, this.subtitle + '   -   ' + count + '/' + finalCount); - - //this will be ran when the done button is clicked, or - // the enter key is pressed in the word input - this.onDone = function() { - this.checkIfDone(newLinkType); - } -} - -Game.prototype.checkIfDone = function(newLinkType) { - //hide the drawing - this.hideBoth(); - - var newLink; - var self = this; - if (newLinkType === 'drawing') { - if (this.isCanvasBlank) { - self.showDrawing(); - swal("Your picture is blank!", "Please draw a picture, then try again.", "info"); - } - else { - self.uploadCanvas(function(url) { - //ran if upload was successful - newLink = url; - self.sendLink(newLinkType, newLink); - }, function() { - //ran if upload was unsuccessful - //reshow the canvas and allow the user to try again - self.showDrawing(); - swal("Upload failed.", "Try again.", "error"); - Screen.prototype.setTitle.call(self, 'Upload failed, try again.'); - }); - } - } - else if (newLinkType === 'word') { - newLink = $('#game-word-in').val().trim(); - //check if it is blank - if (newLink === '') { - self.showWord(); - swal("Your guess is blank!", "Please enter a guess, then try again.", "info") - } - else { - //clear the input - $('#game-word-in').val('') - this.sendLink(newLinkType, newLink); - } - } -} - -Game.prototype.uploadCanvas = function(next, err) { - // this code was sourced from: - // http://community.mybb.com/thread-150592.html - // https://github.com/blueimp/JavaScript-Canvas-to-Blob#usage - try { - Screen.prototype.setTitle.call(this, 'Processing...'); - getDataUrlAsync(this.canvas, function(file) { - var blob = window.dataURLtoBlob(file); - var formData = new FormData(); - formData.append('upload', blob, 'drawing.png'); - var xhr = new XMLHttpRequest(); - xhr.open("POST", "http://uploads.im/api", true); - xhr.onload = function() { - var res = JSON.parse(xhr.responseText); - if (res.status_code === 200) { - var url = res.data.img_url; - next(url); - } else { - err(); - } - } - xhr.onerror = err; - xhr.send(formData); - Screen.prototype.setTitle.call(this, 'Uploading...'); - }); - } catch (e) { - err(); - } -} - -Game.prototype.sendLink = function(type, data) { - Screen.prototype.setTitle.call(this, 'Sending...'); - - socket.emit('finishedLink', { - link: { - type, - data - } - }); - this.onWait(); -} +Results.prototype = Object.create(Screen.prototype); -Game.prototype.roundOver = function() { - this.onRoundEnd(); -} +function Results() { + Screen.call(this); -Game.prototype.resizeCanvas = function() { - var container = $('#game-drawing'); - this.canvas.setHeight(container.width()); - this.canvas.setWidth(container.width()); - this.canvas.renderAll(); + this.id = '#result'; } +Results.prototype.initialize = function () { + $('#result-done').on('click', function () { + hideAll(); + Screen.prototype.setTitle.call(this, 'Thanks for playing Drawphone!'); + Screen.prototype.setSubtitle.call(this, 'Waiting for other players...'); + socket.emit('doneViewingResults', {}); + }); +}; -Results.prototype = Object.create(Screen.prototype); +Results.prototype.show = function (res) { + var ourChain = res.data.links; + var ourName = res.you.name; -function Results() { - Screen.call(this); + Screen.prototype.setTitle.call(this, ourName + '\'s Drawphone results'); + Screen.prototype.setSubtitle.call(this, 'Show everyone how it turned out!'); - this.id = '#result'; -} + var results = $('#result-content'); + results.empty(); -Results.prototype.initialize = function() { - $('#result-done').on('click', function() { - hideAll(); - Screen.prototype.setTitle.call(this, 'Thanks for playing Drawphone!'); - Screen.prototype.setSubtitle.call(this, 'Waiting for other players...'); - socket.emit('doneViewingResults', {}); - }); -} + for (var i = 0; i < ourChain.length; i++) { + var link = ourChain[i]; + if (i === 0) { + results.append('

The first word:

' + link.data + '

'); + } else if (link.type === 'drawing') { + results.append('

' + link.player.name + ' drew:

'); + } else if (link.type === 'word') { + results.append('

' + link.player.name + ' thought that was:

' + link.data + '

'); + } else { + console.log('Results: We should never get here'); + } + } -Results.prototype.show = function(res) { - var ourChain = res.data.links; - var ourName = res.you.name; - - Screen.prototype.setTitle.call(this, ourName + "'s Drawphone results"); - Screen.prototype.setSubtitle.call(this, 'Show everyone how it turned out!'); - - var results = $('#result-content'); - results.empty(); - - for (var i = 0; i < ourChain.length; i++) { - var link = ourChain[i]; - if (i === 0) { - results.append('

The first word:

' + link.data + '

'); - } else if (link.type === 'drawing') { - results.append('

' + link.player.name + ' drew:

'); - } else if (link.type === 'word') { - results.append('

' + link.player.name + ' thought that was:

' + link.data + '

'); - } else { - console.log('Results: We should never get here'); - } - } - - Screen.prototype.show.call(this); -} + Screen.prototype.show.call(this); +}; Waiting.prototype = Object.create(Screen.prototype); function Waiting() { - Screen.call(this); + Screen.call(this); - this.id = '#waiting'; - Screen.prototype.setTitle.call(this, 'Waiting for other players...'); - this.userList = new UserList($('#waiting-players')); + this.id = '#waiting'; + Screen.prototype.setTitle.call(this, 'Waiting for other players...'); + this.userList = new UserList($('#waiting-players')); } -Waiting.prototype.show = function() { - Screen.prototype.setSubtitle.call(this, $('subtitle').html()); - Screen.prototype.show.call(this); -} +Waiting.prototype.show = function () { + Screen.prototype.setSubtitle.call(this, $('subtitle').html()); + Screen.prototype.show.call(this); +}; -Waiting.prototype.updateWaitingList = function(res) { - //show/hide the admin notice - if (res.you.isAdmin) { - $('#waiting-adminmsg').removeClass('hidden'); - } else { - $('#waiting-adminmsg').addClass('hidden'); - } - var notFinished = res.data.notFinished; - var disconnected = res.data.disconnected; - this.userList.update(notFinished, disconnected); -} +Waiting.prototype.updateWaitingList = function (res) { + //show/hide the admin notice + if (res.you.isAdmin) { + $('#waiting-adminmsg').removeClass('hidden'); + } else { + $('#waiting-adminmsg').addClass('hidden'); + } + var notFinished = res.data.notFinished; + var disconnected = res.data.disconnected; + this.userList.update(notFinished, disconnected); +}; Replace.prototype = Object.create(Screen.prototype); function Replace() { - Screen.call(this); - this.id = '#replace' - Screen.prototype.setTitle.call(this, 'Choose a player to replace'); -} - -Replace.prototype.initialize = function() { - $('#replace-leave').click(function() { - //refresh the page - location.reload(); - }); - Screen.prototype.initialize.call(this); -} - -Replace.prototype.show = function(data) { - globalGameCode = '' + data.gameCode + ''; - Screen.prototype.setSubtitle.call(this, 'Ready to join game...'); - - var choices = $('#replace-choices'); - var players = data.players; - - choices.empty(); - - var self = this; - players.forEach(function(player) { - var button = $(''); - button.addClass('btn btn-default btn-lg'); - button.click(function() { - self.sendChoice(player); - }); - choices.append(button); - choices.append('
'); - }); - Screen.prototype.show.call(this); -} - -Replace.prototype.sendChoice = function(playerToReplace) { - socket.emit('tryReplacePlayer', { - playerToReplace - }); -} + Screen.call(this); + this.id = '#replace'; + Screen.prototype.setTitle.call(this, 'Choose a player to replace'); +} + +Replace.prototype.initialize = function () { + $('#replace-leave').click(function () { + //refresh the page + location.reload(); + }); + Screen.prototype.initialize.call(this); +}; + +Replace.prototype.show = function (data) { + globalGameCode = '' + data.gameCode + ''; + Screen.prototype.setSubtitle.call(this, 'Ready to join game...'); + + var choices = $('#replace-choices'); + var players = data.players; + + choices.empty(); + + var self = this; + players.forEach(function (player) { + var button = $(''); + button.addClass('btn btn-default btn-lg'); + button.click(function () { + self.sendChoice(player); + }); + choices.append(button); + choices.append('
'); + }); + Screen.prototype.show.call(this); +}; + +Replace.prototype.sendChoice = function (playerToReplace) { + socket.emit('tryReplacePlayer', { + playerToReplace + }); +}; function UserList(ul) { - this.ul = ul; -} - -UserList.prototype.update = function(newList, disconnectedList) { - //clear all of the user boxes using jquery - this.ul.empty(); - - this.draw(newList, false); - if (disconnectedList) { - if (disconnectedList.length > 0) { - $('#waiting-disconnectedmsg').removeClass('hidden'); - this.draw(disconnectedList, true); - } else { - $('#waiting-disconnectedmsg').addClass('hidden'); - } - } -} - -UserList.prototype.draw = function(list, makeBoxDark) { - for (var i = 0; i < list.length; i++) { - var listBox = $('') - var listItem = $('
  • ' + list[i].name + '
  • ').appendTo(listBox); - listItem.addClass('user'); - if (makeBoxDark) { - listItem.addClass('disconnected'); - } - listBox.addClass('col-xs-6'); - listBox.addClass('user-container'); - listBox.appendTo(this.ul); - } -} + this.ul = ul; +} + +UserList.prototype.update = function (newList, disconnectedList) { + //clear all of the user boxes using jquery + this.ul.empty(); + + this.draw(newList, false); + if (disconnectedList) { + if (disconnectedList.length > 0) { + $('#waiting-disconnectedmsg').removeClass('hidden'); + this.draw(disconnectedList, true); + } else { + $('#waiting-disconnectedmsg').addClass('hidden'); + } + } +}; + +UserList.prototype.draw = function (list, makeBoxDark) { + for (var i = 0; i < list.length; i++) { + var listBox = $(''); + var listItem = $('
  • ' + list[i].name + '
  • ').appendTo(listBox); + listItem.addClass('user'); + if (makeBoxDark) { + listItem.addClass('disconnected'); + } + listBox.addClass('col-xs-6'); + listBox.addClass('user-container'); + listBox.appendTo(this.ul); + } +}; // @@ -712,11 +711,11 @@ var socket = io(); //try to join the dev game var relativeUrl = window.location.pathname + window.location.search; -if (relativeUrl === "/dev") { - socket.emit('joinGame', { - code: 'ffff', - name: Math.random().toString() - }); +if (relativeUrl === '/dev') { + socket.emit('joinGame', { + code: 'ffff', + name: Math.random().toString() + }); } var drawphone = new Drawphone(); diff --git a/routes/index.js b/routes/index.js index 1fc0af5c..9be911f7 100644 --- a/routes/index.js +++ b/routes/index.js @@ -1,10 +1,10 @@ var fs = require('fs'); -module.exports = function(app) { - fs.readdirSync(__dirname).forEach(function(file) { - if (file === "index.js" || file.substr(file.lastIndexOf('.') + 1) !== 'js') - return; - var name = file.substr(0, file.indexOf('.')); - require('./' + name)(app); - }); -} +module.exports = function (app) { + fs.readdirSync(__dirname).forEach(function (file) { + if (file === 'index.js' || file.substr(file.lastIndexOf('.') + 1) !== 'js') + return; + var name = file.substr(0, file.indexOf('.')); + require('./' + name)(app); + }); +}; diff --git a/routes/main.js b/routes/main.js index 3ed2773f..5ed8dfa0 100644 --- a/routes/main.js +++ b/routes/main.js @@ -1,14 +1,14 @@ -module.exports = function(app) { +module.exports = function (app) { - var dp = app.drawphone; + //var dp = app.drawphone; - app.get('/', function(req, res) { - res.render('index'); - }); + app.get('/', function (req, res) { + res.render('index'); + }); - if (app.get('env') === 'development') { - app.get('/dev', function(req, res) { - res.render('index'); - }); - } -} + if (app.get('env') === 'development') { + app.get('/dev', function (req, res) { + res.render('index'); + }); + } +}; diff --git a/routes/socketio.js b/routes/socketio.js index f6669f0f..978b6ace 100644 --- a/routes/socketio.js +++ b/routes/socketio.js @@ -1,92 +1,91 @@ -module.exports = function(app){ +module.exports = function (app) { - var dp = app.drawphone; + var dp = app.drawphone; - app.io.on('connection', function(socket) { + app.io.on('connection', function (socket) { - var thisGame; - var thisUser; + var thisGame; + var thisUser; - socket.on('joinGame', onJoinGame); + socket.on('joinGame', onJoinGame); - socket.on('newGame', function(data) { - if (data.name.length > 2 && data.name.length <= 16) { - thisGame = dp.newGame(); - thisUser = thisGame.addPlayer(data.name, socket); - socket.emit('joinGameRes', { - success: true, - game: thisGame.getJsonGame(), - you: thisUser.getJson() - }) - } else { - socket.emit('joinGameRes', { - success: false, - error: 'Name too short/long' - }) - } - }); + socket.on('newGame', function (data) { + if (data.name.length > 2 && data.name.length <= 16) { + thisGame = dp.newGame(); + thisUser = thisGame.addPlayer(data.name, socket); + socket.emit('joinGameRes', { + success: true, + game: thisGame.getJsonGame(), + you: thisUser.getJson() + }); + } else { + socket.emit('joinGameRes', { + success: false, + error: 'Name too short/long' + }); + } + }); - socket.on('tryStartGame', function(data) { - if (thisUser.isAdmin) { - thisGame.sendToAll('gameStart', {}); - thisGame.startNewRound(); - } - }); + socket.on('tryStartGame', function () { + if (thisUser.isAdmin) { + thisGame.sendToAll('gameStart', {}); + thisGame.startNewRound(); + } + }); - socket.on('tryReplacePlayer', function(data) { - var thisRound = thisGame.currentRound; - var toReplaceId = data.playerToReplace.id; - if (thisUser && thisRound.canBeReplaced(toReplaceId)) { - thisUser = thisRound.replacePlayer(toReplaceId, thisUser); - thisGame.initPlayer(thisUser); - thisRound.updateWaitingList(); - thisRound.nextLinkIfEveryoneIsDone(); - } - else { - //give the user semi-useful error message, - // instead of literally nothing happening - onJoinGame({ - code: thisGame.code, - name: thisUser.name - }); - } - }); + socket.on('tryReplacePlayer', function (data) { + var thisRound = thisGame.currentRound; + var toReplaceId = data.playerToReplace.id; + if (thisUser && thisRound.canBeReplaced(toReplaceId)) { + thisUser = thisRound.replacePlayer(toReplaceId, thisUser); + thisGame.initPlayer(thisUser); + thisRound.updateWaitingList(); + thisRound.nextLinkIfEveryoneIsDone(); + } else { + //give the user semi-useful error message, + // instead of literally nothing happening + onJoinGame({ + code: thisGame.code, + name: thisUser.name + }); + } + }); - function onJoinGame(data) { - thisGame = dp.findGame(data.code); - if (!thisGame) { - socket.emit('joinGameRes', { - success: false, - error: 'Game not found' - }); - } else if (data.name.length <= 2 || data.name.length > 16) { - socket.emit('joinGameRes', { - success: false, - error: 'Name too short/long' - }); - } else { - if (!thisGame.inProgress) { - thisUser = thisGame.addPlayer(data.name, socket); - socket.emit('joinGameRes', { - success: true, - game: thisGame.getJsonGame(), - you: thisUser.getJson() - }) - } else if (thisGame.currentRound.disconnectedPlayers.length > 0){ - thisUser = thisGame.newPlayer(data.name, socket); - socket.emit('replacePlayer', { - gameCode: thisGame.code, - players: thisGame.currentRound.getPlayersThatNeedToBeReplaced() - }); - } else { - socket.emit('joinGameRes', { - success: false, - error: 'Game in progress' - }); - } - } - } + function onJoinGame(data) { + thisGame = dp.findGame(data.code); + if (!thisGame) { + socket.emit('joinGameRes', { + success: false, + error: 'Game not found' + }); + } else if (data.name.length <= 2 || data.name.length > 16) { + socket.emit('joinGameRes', { + success: false, + error: 'Name too short/long' + }); + } else { + if (!thisGame.inProgress) { + thisUser = thisGame.addPlayer(data.name, socket); + socket.emit('joinGameRes', { + success: true, + game: thisGame.getJsonGame(), + you: thisUser.getJson() + }); + } else if (thisGame.currentRound.disconnectedPlayers.length > 0) { + thisUser = thisGame.newPlayer(data.name, socket); + socket.emit('replacePlayer', { + gameCode: thisGame.code, + players: thisGame.currentRound.getPlayersThatNeedToBeReplaced() + }); + } else { + socket.emit('joinGameRes', { + success: false, + error: 'Game in progress' + }); + } + } + } - }); + }); -} +}; diff --git a/words.js b/words.js index bc379d90..15426e7a 100644 --- a/words.js +++ b/words.js @@ -1,4 +1,4 @@ -module.exports = function() { - var words = ['book', 'moon', 'bunk bed', 'carrot', 'milk', 'bowl', 'finger', 'cloud', 'pen', 'mouth', 'octopus', 'lemon', 'water', 'house', 'elephant', 'airplane', 'beach', 'computer', 'lips', 'tail', 'helicopter', 'snowman', 'cookie', 'slide', 'bee', 'snowflake', 'orange', 'worm', 'cow', 'socks', 'ear', 'pizza', 'person', 'boy', 'monster', 'bridge', 'bat', 'balloon', 'light', 'eye', 'bus', 'giraffe', 'duck', 'butterfly', 'corn', 'dinosaur', 'flower', 'truck', 'nose', 'basketball', 'horse', 'heart', 'bone', 'branch', 'apple', 'football', 'car', 'egg', 'ocean', 'spoon', 'ice cream cone', 'drum', 'mountain', 'hat', 'shoe', 'cherry', 'spider', 'swing', 'jar', 'oval', 'bread', 'coat', 'grass', 'ring', 'snail', 'blocks', 'motorcycle', 'girl', 'kite', 'leaf', 'sun', 'snake', 'head', 'cheese', 'hippo', 'boat', 'star', 'baby', 'purse', 'turtle', 'chicken', 'lamp', 'lizard', 'whale', 'ghost', 'clock', 'robot', 'candle', 'hamburger', 'bike', 'monkey', 'bunny', 'mouse', 'pencil', 'glasses', 'circle', 'broom', 'cup', 'legs', 'caterpillar', 'lollipop', 'chair', 'door', 'rocket', 'pig', 'spider web', 'ant', 'shirt', 'jacket', 'bracelet', 'bird', 'wheel', 'sunglasses', 'ball', 'stairs', 'seashell', 'inchworm', 'square', 'alligator', 'banana', 'bug', 'crab', 'bench', 'bell', 'bear', 'Mickey Mouse', 'desk', 'pie', 'train', 'hand', 'skateboard', 'pants', 'table', 'grapes', 'dragon', 'doll', 'bed', 'eyes', 'frog', 'face', 'cat', 'lion', 'dog', 'smile', 'blanket', 'jellyfish', 'tree', 'ears', 'cupcake', 'key', 'spare', 'pizza', 'hopscotch', 'sprinkler', 'snowflake', 'chimney', 'wing', 'easel', 'queen', 'sea turtle', 'rolly polly', 'face', 'forehead', 't-shirt', 'lid', 'rhinoceros', 'rake', 'coin', 'banana split', 'toe', 'snowball', 'unicorn', 'sidewalk', 'jewelry', 'eagle', 'password', 'tennis', 'crayon', 'mouth', 'railroad', 'hill', 'curtains', 'net', 'pirate', 'lipstick', 'skunk', 'puzzle', 'rain', 'ship', 'cheeseburger', 'spine', 'cell phone', 'mail', 'radish', 'tulip', 'shoulder', 'torch', 'fur', 'teapot', 'iPad', 'dolphin', 'golf', 'tiger', 'calendar', 'ice', 'flute', 'sunflower', 'salt and pepper', 'suitcase', 'bathroom scale', 'frog', 'round', 'ski', 'base', 'laundry basket', 'nature', 'nut', 'baseball', 'hospital', 'towel', 'top hat', 'saw', 'artist', 'mailbox', 'button', 'pinwheel', 'fist', 'candle', 'carpet', 'clam', 'gift', 'hippopotamus', 'globe', 'knee', 'cello', 'song', 'garbage', 'peanut', 'flagpole', 'dragonfly', 'spider web', 'boot', 'church', 'elbow', 'ironing board', 'blue jeans', 'pan', 'piano', 'hot dog', 'umbrella', 'maze', 'cheetah', 'surfboard', 'rainbow', 'cockroach', 'mini blinds', 'garden', 'photograph', 'toast', 'shovel', 'deer', 'printer', 'rose', 'chin', 'zebra', 'table', 'cucumber', 'mushroom', 'skirt', 'roof', 'drums', 'wax', 'spoon', 'basket', 'belt', 'aircraft', 'potato', 'glove', 'porcupine', 'computer', 'crib', 'tape', 'tadpole', 'stove', 'address', 'soda', 'crack', 'America', 'map', 'strawberry', 'penguin', 'light bulb', 'log', 'platypus', 'thief', 'bell pepper', 'stapler', 'paint', 'bubble', 'doghouse', 'cast', 'scar', 'lobster', 'sink', 'trash can', 'doorknob', 'chocolate chip cookie', 'batteries', 'TV', 'sheep', 'king', 'bagel', 'refrigerator', 'room', 'bicycle', 'broccoli', 'yo-yo', 'astronaut', 'dog leash', 'apple pie', 'camera', 'watch', 'popsicle', 'catfish', 'shallow', 'cricket', 'storm', 'half', 'page', 'pumpkin', 'skate', 'banana peel', 'picture frame', 'pond', 'shelf', 'box', 'maid', 'electricity', 'bib', 'doormat', 'mailman', 'eraser', 'purse', 'wreath', 'back', 'pelican', 'flamingo', 'salt', 'wood', 'violin', 'mouse', 'headband', 'silverware', 'jelly', 'window', 'scissors', 'watering can', 'state', 'tongue', 'mitten', 'river', 'school', 'ladybug', 'fang', 'trumpet', 'gingerbread man', 'toothbrush', 'airport', 'seahorse', 'wall', 'shark', 'hairbrush', 'fishing pole', 'telephone', 'baby', 'vase', 'forest', 'bag', 'corndog', 'chameleon', 'toaster', 'coal', 'dress', 'teeth', 'cowboy', 'pineapple', 'tire', 'pajamas', 'french fries', 'pine tree', 'park', 'paw', 'tissue', 'milk', 'poodle', 'smile', 'napkin', 'grill', 'pear', 'dock', 'treasure', 'daddy longlegs', 'electrical outlet', 'braid', 'blimp', 'video camera', 'volcano', 'dominoes', 'paperclip', 'owl', 'claw', 'pretzel', 'happy', 'chain', 'popcorn', 'stork', 'beaver', 'dollar', 'onion', 'plate', 'bucket', 'pen', 'stamp', 'ticket', 'newspaper', 'hip', 'waist', 'knot', 'stomach', 'clown', 'hula hoop', 'lightsaber', 'chalk', 'bottle', 'lock', 'seesaw', 'wallet', 'hook', 'tent', 'gumball', 'fork', 'cake', 'family', 'magazine', 'bathtub', 'match', 'cheek', 'three-toed sloth', 'city', 'brain', 'music', 'lunchbox', 'smoke', 'attic', 'hair dryer', 'spring', 'light switch', 'hair', 'birthday cake', 'bomb', 'dustpan', 'cobra', 'peach', 'gate', 'sailboat', 'alarm clock', 'palace', 'backbone', 'battery', 'lighthouse', 'beach', 'horse', 'deep', 'blowfish', 'mop', 'quilt', 'rug', 'jungle', 'cage', 'hummingbird', 'jar', 'stump', 'barn', 'eel', 'stingray', 'corner', 'lawn mower', 'door', 'neck', 'beehive', 'hoof', 'tank', 'whistle', 'soap', 'pencil', 'trip', 'paper', 'food', 'circus', 'hockey', 'money', 'dimple', 'harp', 'hug', 'front porch', 'lawnmower', 'campfire', 'mattress', 'muffin', 'rocking chair', 'garage', 'spaceship', 'washing machine', 'shadow', 'bowtie', 'pogo stick', 'spool', 'ladder', 'flashlight', 'outside', 'heel', 'ring', 'nest', 'starfish', 'desk', 'brick', 'roller blading', 'lemon', 'stoplight', 'lake', 'tusk', 'swimming pool', 'fox']; - return words[Math.floor(Math.random() * words.length)]; -} +module.exports = function () { + var words = ['book', 'moon', 'bunk bed', 'carrot', 'milk', 'bowl', 'finger', 'cloud', 'pen', 'mouth', 'octopus', 'lemon', 'water', 'house', 'elephant', 'airplane', 'beach', 'computer', 'lips', 'tail', 'helicopter', 'snowman', 'cookie', 'slide', 'bee', 'snowflake', 'orange', 'worm', 'cow', 'socks', 'ear', 'pizza', 'person', 'boy', 'monster', 'bridge', 'bat', 'balloon', 'light', 'eye', 'bus', 'giraffe', 'duck', 'butterfly', 'corn', 'dinosaur', 'flower', 'truck', 'nose', 'basketball', 'horse', 'heart', 'bone', 'branch', 'apple', 'football', 'car', 'egg', 'ocean', 'spoon', 'ice cream cone', 'drum', 'mountain', 'hat', 'shoe', 'cherry', 'spider', 'swing', 'jar', 'oval', 'bread', 'coat', 'grass', 'ring', 'snail', 'blocks', 'motorcycle', 'girl', 'kite', 'leaf', 'sun', 'snake', 'head', 'cheese', 'hippo', 'boat', 'star', 'baby', 'purse', 'turtle', 'chicken', 'lamp', 'lizard', 'whale', 'ghost', 'clock', 'robot', 'candle', 'hamburger', 'bike', 'monkey', 'bunny', 'mouse', 'pencil', 'glasses', 'circle', 'broom', 'cup', 'legs', 'caterpillar', 'lollipop', 'chair', 'door', 'rocket', 'pig', 'spider web', 'ant', 'shirt', 'jacket', 'bracelet', 'bird', 'wheel', 'sunglasses', 'ball', 'stairs', 'seashell', 'inchworm', 'square', 'alligator', 'banana', 'bug', 'crab', 'bench', 'bell', 'bear', 'Mickey Mouse', 'desk', 'pie', 'train', 'hand', 'skateboard', 'pants', 'table', 'grapes', 'dragon', 'doll', 'bed', 'eyes', 'frog', 'face', 'cat', 'lion', 'dog', 'smile', 'blanket', 'jellyfish', 'tree', 'ears', 'cupcake', 'key', 'spare', 'pizza', 'hopscotch', 'sprinkler', 'snowflake', 'chimney', 'wing', 'easel', 'queen', 'sea turtle', 'rolly polly', 'face', 'forehead', 't-shirt', 'lid', 'rhinoceros', 'rake', 'coin', 'banana split', 'toe', 'snowball', 'unicorn', 'sidewalk', 'jewelry', 'eagle', 'password', 'tennis', 'crayon', 'mouth', 'railroad', 'hill', 'curtains', 'net', 'pirate', 'lipstick', 'skunk', 'puzzle', 'rain', 'ship', 'cheeseburger', 'spine', 'cell phone', 'mail', 'radish', 'tulip', 'shoulder', 'torch', 'fur', 'teapot', 'iPad', 'dolphin', 'golf', 'tiger', 'calendar', 'ice', 'flute', 'sunflower', 'salt and pepper', 'suitcase', 'bathroom scale', 'frog', 'round', 'ski', 'base', 'laundry basket', 'nature', 'nut', 'baseball', 'hospital', 'towel', 'top hat', 'saw', 'artist', 'mailbox', 'button', 'pinwheel', 'fist', 'candle', 'carpet', 'clam', 'gift', 'hippopotamus', 'globe', 'knee', 'cello', 'song', 'garbage', 'peanut', 'flagpole', 'dragonfly', 'spider web', 'boot', 'church', 'elbow', 'ironing board', 'blue jeans', 'pan', 'piano', 'hot dog', 'umbrella', 'maze', 'cheetah', 'surfboard', 'rainbow', 'cockroach', 'mini blinds', 'garden', 'photograph', 'toast', 'shovel', 'deer', 'printer', 'rose', 'chin', 'zebra', 'table', 'cucumber', 'mushroom', 'skirt', 'roof', 'drums', 'wax', 'spoon', 'basket', 'belt', 'aircraft', 'potato', 'glove', 'porcupine', 'computer', 'crib', 'tape', 'tadpole', 'stove', 'address', 'soda', 'crack', 'America', 'map', 'strawberry', 'penguin', 'light bulb', 'log', 'platypus', 'thief', 'bell pepper', 'stapler', 'paint', 'bubble', 'doghouse', 'cast', 'scar', 'lobster', 'sink', 'trash can', 'doorknob', 'chocolate chip cookie', 'batteries', 'TV', 'sheep', 'king', 'bagel', 'refrigerator', 'room', 'bicycle', 'broccoli', 'yo-yo', 'astronaut', 'dog leash', 'apple pie', 'camera', 'watch', 'popsicle', 'catfish', 'shallow', 'cricket', 'storm', 'half', 'page', 'pumpkin', 'skate', 'banana peel', 'picture frame', 'pond', 'shelf', 'box', 'maid', 'electricity', 'bib', 'doormat', 'mailman', 'eraser', 'purse', 'wreath', 'back', 'pelican', 'flamingo', 'salt', 'wood', 'violin', 'mouse', 'headband', 'silverware', 'jelly', 'window', 'scissors', 'watering can', 'state', 'tongue', 'mitten', 'river', 'school', 'ladybug', 'fang', 'trumpet', 'gingerbread man', 'toothbrush', 'airport', 'seahorse', 'wall', 'shark', 'hairbrush', 'fishing pole', 'telephone', 'baby', 'vase', 'forest', 'bag', 'corndog', 'chameleon', 'toaster', 'coal', 'dress', 'teeth', 'cowboy', 'pineapple', 'tire', 'pajamas', 'french fries', 'pine tree', 'park', 'paw', 'tissue', 'milk', 'poodle', 'smile', 'napkin', 'grill', 'pear', 'dock', 'treasure', 'daddy longlegs', 'electrical outlet', 'braid', 'blimp', 'video camera', 'volcano', 'dominoes', 'paperclip', 'owl', 'claw', 'pretzel', 'happy', 'chain', 'popcorn', 'stork', 'beaver', 'dollar', 'onion', 'plate', 'bucket', 'pen', 'stamp', 'ticket', 'newspaper', 'hip', 'waist', 'knot', 'stomach', 'clown', 'hula hoop', 'lightsaber', 'chalk', 'bottle', 'lock', 'seesaw', 'wallet', 'hook', 'tent', 'gumball', 'fork', 'cake', 'family', 'magazine', 'bathtub', 'match', 'cheek', 'three-toed sloth', 'city', 'brain', 'music', 'lunchbox', 'smoke', 'attic', 'hair dryer', 'spring', 'light switch', 'hair', 'birthday cake', 'bomb', 'dustpan', 'cobra', 'peach', 'gate', 'sailboat', 'alarm clock', 'palace', 'backbone', 'battery', 'lighthouse', 'beach', 'horse', 'deep', 'blowfish', 'mop', 'quilt', 'rug', 'jungle', 'cage', 'hummingbird', 'jar', 'stump', 'barn', 'eel', 'stingray', 'corner', 'lawn mower', 'door', 'neck', 'beehive', 'hoof', 'tank', 'whistle', 'soap', 'pencil', 'trip', 'paper', 'food', 'circus', 'hockey', 'money', 'dimple', 'harp', 'hug', 'front porch', 'lawnmower', 'campfire', 'mattress', 'muffin', 'rocking chair', 'garage', 'spaceship', 'washing machine', 'shadow', 'bowtie', 'pogo stick', 'spool', 'ladder', 'flashlight', 'outside', 'heel', 'ring', 'nest', 'starfish', 'desk', 'brick', 'roller blading', 'lemon', 'stoplight', 'lake', 'tusk', 'swimming pool', 'fox']; + return words[Math.floor(Math.random() * words.length)]; +};