Advertisement
Guest User

Untitled

a guest
Jul 2nd, 2016
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.06 KB | None | 0 0
  1. var express = require('express'),
  2. path = require('path'),
  3. favicon = require('serve-favicon'),
  4. logger = require('morgan'),
  5. cookieParser = require('cookie-parser'),
  6. bodyParser = require('body-parser'),
  7.  
  8. routes = require('./routes/index'),
  9. users = require('./routes/users'),
  10.  
  11. app = express(),
  12. server = require('http').Server(app),
  13. io = require('socket.io')(server),
  14. debug = require('debug')('http');
  15.  
  16. // view engine setup
  17. app.set('views', path.join(__dirname, 'views'));
  18. app.set('view engine', 'hjs');
  19.  
  20. // uncomment after placing your favicon in /public
  21. //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
  22. app.use(logger('dev'));
  23. app.use(bodyParser.json());
  24. app.use(bodyParser.urlencoded({ extended: false }));
  25. app.use(cookieParser());
  26. app.use(express.static(path.join(__dirname, 'public')));
  27.  
  28. app.use('/', routes);
  29. app.use('/users', users);
  30.  
  31. // catch 404 and forward to error handler
  32. app.use(function(req, res, next) {
  33. var err = new Error('Not Found');
  34. err.status = 404;
  35. next(err);
  36. });
  37.  
  38. // error handlers
  39.  
  40. // development error handler
  41. // will print stacktrace
  42. if (app.get('env') === 'development') {
  43. app.use(function(err, req, res, next) {
  44. res.status(err.status || 500);
  45. res.render('error', {
  46. message: err.message,
  47. error: err
  48. });
  49. });
  50. }
  51.  
  52. // production error handler
  53. // no stacktraces leaked to user
  54. app.use(function(err, req, res, next) {
  55. res.status(err.status || 500);
  56. res.render('error', {
  57. message: err.message,
  58. error: {}
  59. });
  60. });
  61.  
  62.  
  63.  
  64. // ===============================================
  65. // IMDb API LOGIC
  66. // ===============================================
  67.  
  68. var randomMovieRank = Math.floor((Math.random() * 250) + 1);
  69.  
  70. function dataRequest(){
  71. // API Key
  72. key = "4dba72b2-7558-4c0f-bd18-9ffcb0999c4e";
  73. // Url
  74. mainUrl = "http://api.myapifilms.com/imdb/top?token="+ key +"&format=json&data=0&start=1&end=250";
  75. // API Call
  76. var request = require('request');
  77.  
  78. request(mainUrl, function (error, response, body) {
  79. if (!error && response.statusCode == 200) {
  80.  
  81. // Storing data in an object
  82. var obj = JSON.parse(body), //JSON Parser
  83. movieArray = obj.data.movies, //Creating Array
  84. item = movieArray[randomMovieRank]; //Setting random movie variable
  85. itemArray = [item.ranking,item.title,item.year];
  86. }
  87. });
  88. return false;
  89. }
  90.  
  91.  
  92. // ===============================================
  93. // Functions
  94. // ===============================================
  95.  
  96. // To update the allUsers array when someone leaves or connects
  97. var serverFunctions = {
  98. playerOne : null,
  99. playerTwo : null,
  100. fullLobby : false,
  101.  
  102. updateUsernames: function(){
  103. io.sockets.emit('usernames', allUsers);
  104. },
  105. playerCheck: function() {
  106. playerOne = allUsers[0];
  107. playerTwo = allUsers[1];
  108. },
  109. lobbyCheck: function() {
  110. // Lobby Control (to deny access to more than two users per lobby)
  111. // Checking array length to see if game lobby is full
  112. if(allUsers.length > 2) {
  113. fullLobby = true;
  114. console.log("Lobby is now full");
  115. // If the lobby is full, send the players names who will ve vsing one another
  116. serverFunctions.playerCheck();
  117. } else {
  118. fullLobby = false;
  119. console.log("Lobby has one slot open");
  120. }
  121. io.sockets.emit("full_lobby_check", {lobbyStatus: fullLobby});
  122. }
  123. };
  124.  
  125. // ===============================================
  126. // SERVER SIDE LOGIC
  127. // ===============================================
  128.  
  129. var allUsers = [];
  130.  
  131. io.sockets.on("connection", function(socket){
  132.  
  133. console.log("Client connection, no username");
  134.  
  135. // ===============================================
  136. // NEW ANSWER LOGIC
  137. // ===============================================
  138. if(itemArray !== null)
  139. {
  140. io.sockets.emit("serverAnswer", {ranking: itemArray[0], title: itemArray[1], year: itemArray[2]});
  141. }
  142. else{
  143. //1.ajax request IMDB resource
  144. //2.set movies variables
  145. //3.emit message
  146. dataRequest();
  147. console.log(itemArray);
  148. io.sockets.emit("serverAnswer", {ranking: itemArray[0], title: itemArray[1], year: itemArray[2]});
  149. }
  150.  
  151. // ===============================================
  152. // NEW PLAYER LOGIC
  153. // ===============================================
  154.  
  155. // Player has connected
  156. // Checks if username is already been used
  157. socket.on("new user", function(data, callback){
  158. // If it exists return false, else add it to array of allUsers
  159. if (allUsers.indexOf(data) != -1) {
  160. callback(false);
  161. } else {
  162. callback(true);
  163. socket.username = data;
  164. allUsers.push(socket.username);
  165. // Tells all active users which users are active
  166. serverFunctions.updateUsernames();
  167. console.log("Player " + socket.username + " connected");
  168. }
  169. // Calls theplayer check in order to push through the player names client side
  170. serverFunctions.lobbyCheck();
  171. });
  172.  
  173. // ===============================================
  174. // DISCONNECTION
  175. // ===============================================
  176. socket.on('disconnect', function(data) {
  177. // Allows us to track if a unknown user has disconnected or if a known user has dosconnected
  178. if(!socket.username) {
  179. console.log("Client disconnected before username");
  180. } else {
  181. console.log("Player " + socket.username + " disconnected");
  182. serverFunctions.lobbyCheck();
  183. // Removes only one user
  184. allUsers.splice(allUsers.indexOf(socket.username), 1);
  185. }
  186. // Calls update usernames function
  187. serverFunctions.updateUsernames();
  188. });
  189.  
  190. // ===============================================
  191. // IN GAME CHAT
  192. // ===============================================
  193.  
  194. // Broadcasts a message
  195. socket.on("send message", function(data){
  196. io.sockets.emit("new message", {msg: data, user: socket.username});
  197. });
  198.  
  199. socket.on("begin_game", function(data, callback){
  200. serverFunctions.playerCheck();
  201. io.sockets.emit("event_new_user", {userOne: playerOne,userTwo: playerTwo});
  202. });
  203.  
  204. // ===============================================
  205. // Game Start Logic
  206. // ===============================================
  207.  
  208.  
  209.  
  210. // Will fire off once client has entered lobby
  211. io.sockets.emit('connected', {connected:'Yay!'});
  212.  
  213. // the client passes 'callback' as a function. When we invoke the callback on the server
  214. // the code on the client side will run
  215. socket.on('testmessage', function(data, callback){
  216. console.log('Socket (server-side): received message:', data);
  217. var responseData = { string1:'I like ', string2: 'bananas ', string3:' dude!' };
  218. //console.log('connection data:', evData);
  219. callback(responseData);
  220. });
  221.  
  222. });
  223.  
  224. module.exports = {app: app, server: server};
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement