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: {}
- });
- });
- // ===============================================
- // IMDb API LOGIC
- // ===============================================
- var randomMovieRank = Math.floor((Math.random() * 250) + 1);
- function dataRequest(){
- // 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];
- }
- });
- return false;
- }
- // ===============================================
- // Functions
- // ===============================================
- // To update the allUsers array when someone leaves or connects
- var serverFunctions = {
- playerOne : null,
- playerTwo : null,
- fullLobby : false,
- updateUsernames: function(){
- io.sockets.emit('usernames', allUsers);
- },
- playerCheck: function() {
- playerOne = allUsers[0];
- playerTwo = allUsers[1];
- },
- lobbyCheck: function() {
- // 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) {
- fullLobby = true;
- console.log("Lobby is now full");
- // If the lobby is full, send the players names who will ve vsing one another
- serverFunctions.playerCheck();
- } else {
- fullLobby = false;
- console.log("Lobby has one slot open");
- }
- io.sockets.emit("full_lobby_check", {lobbyStatus: fullLobby});
- }
- };
- // ===============================================
- // SERVER SIDE LOGIC
- // ===============================================
- var allUsers = [];
- io.sockets.on("connection", function(socket){
- console.log("Client connection, no username");
- // ===============================================
- // NEW ANSWER LOGIC
- // ===============================================
- if(itemArray !== null)
- {
- io.sockets.emit("serverAnswer", {ranking: itemArray[0], title: itemArray[1], year: itemArray[2]});
- }
- else{
- //1.ajax request IMDB resource
- //2.set movies variables
- //3.emit message
- dataRequest();
- console.log(itemArray);
- io.sockets.emit("serverAnswer", {ranking: itemArray[0], title: itemArray[1], year: itemArray[2]});
- }
- // ===============================================
- // NEW PLAYER LOGIC
- // ===============================================
- // Player has connected
- // Checks if username is already been used
- socket.on("new user", function(data, callback){
- // 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");
- }
- // Calls theplayer check in order to push through the player names client side
- serverFunctions.lobbyCheck();
- });
- // ===============================================
- // 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);
- }
- // 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});
- });
- socket.on("begin_game", function(data, callback){
- serverFunctions.playerCheck();
- io.sockets.emit("event_new_user", {userOne: playerOne,userTwo: playerTwo});
- });
- // ===============================================
- // Game Start Logic
- // ===============================================
- // Will fire off once client has entered lobby
- io.sockets.emit('connected', {connected:'Yay!'});
- // the client passes 'callback' as a function. When we invoke the callback on the server
- // the code on the client side will run
- socket.on('testmessage', function(data, callback){
- console.log('Socket (server-side): received message:', data);
- var responseData = { string1:'I like ', string2: 'bananas ', string3:' dude!' };
- //console.log('connection data:', evData);
- callback(responseData);
- });
- });
- module.exports = {app: app, server: server};
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement