Advertisement
Guest User

Untitled

a guest
Jul 3rd, 2016
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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.  
  17. // view engine setup
  18. app.set('views', path.join(__dirname, 'views'));
  19. app.set('view engine', 'hjs');
  20.  
  21. // uncomment after placing your favicon in /public
  22. //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
  23. app.use(logger('dev'));
  24. app.use(bodyParser.json());
  25. app.use(bodyParser.urlencoded({ extended: false }));
  26. app.use(cookieParser());
  27. app.use(express.static(path.join(__dirname, 'public')));
  28.  
  29. app.use('/', routes);
  30. app.use('/users', users);
  31.  
  32. // catch 404 and forward to error handler
  33. app.use(function(req, res, next) {
  34.     var err = new Error('Not Found');
  35.     err.status = 404;
  36.     next(err);
  37. });
  38.  
  39. // error handlers
  40.  
  41. // development error handler
  42. // will print stacktrace
  43. if (app.get('env') === 'development') {
  44.     app.use(function(err, req, res, next) {
  45.         res.status(err.status || 500);
  46.         res.render('error', {
  47.             message: err.message,
  48.             error: err
  49.         });
  50.     });
  51. }
  52.  
  53. // production error handler
  54. // no stacktraces leaked to user
  55. app.use(function(err, req, res, next) {
  56.     res.status(err.status || 500);
  57.     res.render('error', {
  58.         message: err.message,
  59.         error: {}
  60.     });
  61. });
  62.  
  63. // ===============================================
  64. // Functions
  65. // ===============================================
  66.  
  67. // To update the allUsers array when someone leaves or connects
  68. var serverFunctions = {
  69.     playerOne : null,
  70.     playerTwo : null,
  71.  
  72.     updateUsernames: function(){
  73.         io.sockets.emit('usernames', allUsers);
  74.     },
  75.     playerCheck: function()   {
  76.         playerOne = allUsers[0];
  77.         playerTwo = allUsers[1];
  78.     }
  79. };
  80.  
  81. // ===============================================
  82. // IMDb API LOGIC
  83. // ===============================================
  84. function randomIntFromInterval(min,max){
  85.     return Math.floor(Math.random()*(max-min+1)+min);
  86. }
  87.  
  88. function dataRequest(){
  89.     var randomMovieRank = randomIntFromInterval(1,250);
  90.     // API Key
  91.     key = "4dba72b2-7558-4c0f-bd18-9ffcb0999c4e";
  92.     // Url
  93.     mainUrl = "http://api.myapifilms.com/imdb/top?token="+ key +"&format=json&data=0&start=1&end=250";
  94.     // API Call
  95.     var request = require('request');
  96.  
  97.     request(mainUrl, function (error, response, body) {
  98.         if (!error && response.statusCode == 200) {
  99.  
  100.         // Storing data in an object
  101.         var obj         = JSON.parse(body), //JSON Parser
  102.             movieArray  = obj.data.movies, //Creating Array
  103.             item        = movieArray[randomMovieRank]; //Setting random movie variable
  104.             itemArray  = [item.ranking,item.title,item.year];
  105.             io.sockets.emit("server answer", {ranking: itemArray[0], title: itemArray[1], year: itemArray[2]});
  106.             console.log(itemArray);
  107.       }
  108.     });
  109.     return false;
  110. }
  111. // ===============================================
  112. // SERVER SIDE LOGIC
  113. // ===============================================
  114.  
  115. var allUsers = [],
  116.     allowAccess = true;
  117.     readyStatus = true;
  118.  
  119. // Global variables for maintaining game states
  120.     var responses = [];
  121.     var validR = [];
  122.    
  123. io.sockets.on("connection", function(socket){
  124.  
  125. // ===============================================
  126. // NEW PLAYER LOGIC
  127. // ===============================================
  128.  
  129.     // Player has connected
  130.     // Checks if username is already been used
  131.     socket.on("new user", function(data, callback){
  132.         // Lobby Control  (to deny access to more than two users per lobby)
  133.         // Checking array length to see if game lobby is full
  134.         if(allUsers.length > 2) {
  135.             allowAccess = false;
  136.             console.log("has no space");
  137.             // If the lobby is full, send the players names who will ve vsing one another
  138.         } else if (allUsers.length != 2){
  139.             allowAccess = true;
  140.             // If it exists return false, else add it to array of allUsers
  141.             if (allUsers.indexOf(data) != -1) {
  142.                 callback(false);
  143.             } else {
  144.                 callback(true);
  145.                 socket.username = data;
  146.                 allUsers.push(socket.username);
  147.                 // Tells all active users which users are active
  148.                 serverFunctions.updateUsernames();
  149.                 console.log("Player " + socket.username + " connected");
  150.             }
  151.         }
  152.  
  153.         // ===============================================
  154.         // START GAME
  155.         // ===============================================
  156.         // Checks if there are two players in the lobby. If there are it will let the game know to play
  157.         // Change == 2 to one to enter single player mode
  158.         if(allUsers.length == 2) {
  159.             allowAccess = true;
  160.             console.log("Is full");
  161.             // Send true that it is ready
  162.             readyStatus = true;
  163.             // Request a movie
  164.             dataRequest();
  165.             // Log competitors
  166.             serverFunctions.playerCheck();
  167.             io.sockets.emit("event_new_user", {userOne: playerOne,userTwo: playerTwo});  
  168.         } else {
  169.             readyStatus = false;
  170.         }
  171.  
  172.         // This is called in order to tell the client side that they can proceed to the waiting room
  173.         io.sockets.emit("full_lobby_check", {lobbyStatus: allowAccess});
  174.         // Once there are two users they are then able to access the main lobby
  175.         io.sockets.emit("ready_status", {readyStatus: readyStatus});
  176.     });
  177.    
  178. // ===============================================
  179. // DISCONNECTION
  180. // ===============================================
  181.     socket.on('disconnect', function(data) {
  182.         // Allows us to track if a unknown user has disconnected or if a known user has dosconnected
  183.         if(!socket.username) {
  184.             console.log("Client disconnected before username");
  185.         } else {
  186.             console.log("Player " + socket.username + " disconnected");
  187.             // serverFunctions.lobbyCheck();
  188.             // Removes only one user
  189.             allUsers.splice(allUsers.indexOf(socket.username), 1);
  190.             // setTimeout(function () {
  191.             //     for(var i = 0; i < allUsers.length; i++) {
  192.             //         io.sockets.socket(users[i]).disconnect();
  193.             //     }    
  194.             // }, 3000);
  195.         }
  196.         // Calls update usernames function
  197.         serverFunctions.updateUsernames();
  198.     });
  199.  
  200. // ===============================================
  201. // IN GAME CHAT
  202. // ===============================================
  203.  
  204.     // Broadcasts a message
  205.     socket.on("send message", function(data){
  206.         io.sockets.emit("new message", {msg: data, user: socket.username});
  207.     });
  208.  
  209. // ===============================================
  210. // GAME LOGIC
  211. // ===============================================
  212.     // .1 Checks if there are two players connected
  213.     // .2 Generates a question
  214.     // .3 Recieves both player answers
  215.  
  216.     responses[socket.id] = {responses:[]};
  217.     socket.on("playerCorrect",function(data){
  218.       responses[socket.id].responses.push(data);
  219.       answerValidation(socket);
  220.      });
  221.  
  222.      socket.on("playerWrong",function(data){
  223.       responses[socket.id].responses.push(data);
  224.        answerValidation(socket);
  225.      });
  226.  
  227.     function answerValidation(socket) {
  228.       var connectedC = responses.length;
  229.       responses.forEach(function(client, index){
  230.        // check if number of responses is equal to 2
  231.        if (client.responses.length === 2) {
  232.         validR.push(socket.id);
  233.        }
  234.        if (validR.length === connectedC) {
  235.             console.log("working");
  236.        }
  237.       });
  238.     }
  239.  
  240. });
  241.  
  242.  
  243.  
  244. module.exports = {app: app, server: server};
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement