Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var express = require('express'),
- path = require('path'),
- favicon = require('serve-favicon'),
- logger = require('morgan'),
- cookieParser = require('cookie-parser'),
- bodyParser = require('body-parser'),
- routes = require('./routes/index'),
- users = require('./routes/users'),
- app = express(),
- server = require('http').Server(app),
- io = require('socket.io')(server),
- debug = require('debug')('http');
- // view engine setup
- app.set('views', path.join(__dirname, 'views'));
- app.set('view engine', 'hjs');
- // uncomment after placing your favicon in /public
- //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
- app.use(logger('dev'));
- app.use(bodyParser.json());
- app.use(bodyParser.urlencoded({ extended: false }));
- app.use(cookieParser());
- app.use(express.static(path.join(__dirname, 'public')));
- app.use('/', routes);
- app.use('/users', users);
- // catch 404 and forward to error handler
- app.use(function(req, res, next) {
- var err = new Error('Not Found');
- err.status = 404;
- next(err);
- });
- // error handlers
- // development error handler
- // will print stacktrace
- if (app.get('env') === 'development') {
- app.use(function(err, req, res, next) {
- 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: {}
- });
- });
- // ===============================================
- // Functions
- // ===============================================
- // To update the allUsers array when someone leaves or connects
- var serverFunctions = {
- playerOne : null,
- playerTwo : null,
- updateUsernames: function(){
- io.sockets.emit('usernames', allUsers);
- },
- playerCheck: function() {
- playerOne = allUsers[0];
- playerTwo = allUsers[1];
- }
- };
- // ===============================================
- // IMDb API LOGIC
- // ===============================================
- function randomIntFromInterval(min,max){
- return Math.floor(Math.random()*(max-min+1)+min);
- }
- function dataRequest(){
- var randomMovieRank = randomIntFromInterval(1,250);
- // API Key
- key = "4dba72b2-7558-4c0f-bd18-9ffcb0999c4e";
- // Url
- mainUrl = "http://api.myapifilms.com/imdb/top?token="+ key +"&format=json&data=0&start=1&end=250";
- // API Call
- var request = require('request');
- request(mainUrl, function (error, response, body) {
- if (!error && response.statusCode == 200) {
- // Storing data in an object
- var obj = JSON.parse(body), //JSON Parser
- movieArray = obj.data.movies, //Creating Array
- item = movieArray[randomMovieRank]; //Setting random movie variable
- itemArray = [item.ranking,item.title,item.year];
- io.sockets.emit("server answer", {ranking: itemArray[0], title: itemArray[1], year: itemArray[2]});
- console.log(itemArray);
- }
- });
- return false;
- }
- // ===============================================
- // SERVER SIDE LOGIC
- // ===============================================
- var allUsers = [],
- allowAccess = true;
- readyStatus = true;
- // Global variables for maintaining game states
- var responses = [];
- var validR = [];
- io.sockets.on("connection", function(socket){
- // ===============================================
- // NEW PLAYER LOGIC
- // ===============================================
- // Player has connected
- // Checks if username is already been used
- socket.on("new user", function(data, callback){
- // Lobby Control (to deny access to more than two users per lobby)
- // Checking array length to see if game lobby is full
- if(allUsers.length > 2) {
- allowAccess = false;
- console.log("has no space");
- // If the lobby is full, send the players names who will ve vsing one another
- } else if (allUsers.length != 2){
- allowAccess = true;
- // If it exists return false, else add it to array of allUsers
- if (allUsers.indexOf(data) != -1) {
- callback(false);
- } else {
- callback(true);
- socket.username = data;
- allUsers.push(socket.username);
- // Tells all active users which users are active
- serverFunctions.updateUsernames();
- console.log("Player " + socket.username + " connected");
- }
- }
- // ===============================================
- // START GAME
- // ===============================================
- // Checks if there are two players in the lobby. If there are it will let the game know to play
- // Change == 2 to one to enter single player mode
- if(allUsers.length == 2) {
- allowAccess = true;
- console.log("Is full");
- // Send true that it is ready
- readyStatus = true;
- // Request a movie
- dataRequest();
- // Log competitors
- serverFunctions.playerCheck();
- io.sockets.emit("event_new_user", {userOne: playerOne,userTwo: playerTwo});
- } else {
- readyStatus = false;
- }
- // This is called in order to tell the client side that they can proceed to the waiting room
- io.sockets.emit("full_lobby_check", {lobbyStatus: allowAccess});
- // Once there are two users they are then able to access the main lobby
- io.sockets.emit("ready_status", {readyStatus: readyStatus});
- });
- // ===============================================
- // DISCONNECTION
- // ===============================================
- socket.on('disconnect', function(data) {
- // Allows us to track if a unknown user has disconnected or if a known user has dosconnected
- if(!socket.username) {
- console.log("Client disconnected before username");
- } else {
- console.log("Player " + socket.username + " disconnected");
- // serverFunctions.lobbyCheck();
- // Removes only one user
- allUsers.splice(allUsers.indexOf(socket.username), 1);
- // setTimeout(function () {
- // for(var i = 0; i < allUsers.length; i++) {
- // io.sockets.socket(users[i]).disconnect();
- // }
- // }, 3000);
- }
- // Calls update usernames function
- serverFunctions.updateUsernames();
- });
- // ===============================================
- // IN GAME CHAT
- // ===============================================
- // Broadcasts a message
- socket.on("send message", function(data){
- io.sockets.emit("new message", {msg: data, user: socket.username});
- });
- // ===============================================
- // GAME LOGIC
- // ===============================================
- // .1 Checks if there are two players connected
- // .2 Generates a question
- // .3 Recieves both player answers
- responses[socket.id] = {responses:[]};
- socket.on("playerCorrect",function(data){
- responses[socket.id].responses.push(data);
- answerValidation(socket);
- });
- socket.on("playerWrong",function(data){
- responses[socket.id].responses.push(data);
- answerValidation(socket);
- });
- function answerValidation(socket) {
- var connectedC = responses.length;
- responses.forEach(function(client, index){
- // check if number of responses is equal to 2
- if (client.responses.length === 2) {
- validR.push(socket.id);
- }
- if (validR.length === connectedC) {
- console.log("working");
- }
- });
- }
- });
- module.exports = {app: app, server: server};
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement