Created
September 7, 2016 11:55
-
-
Save tandat2209/cc4fa81d82c653aae4a0d0670def9c6a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var currentClick = 0; | |
var num = 1; | |
// list of all connected users | |
var users = []; | |
io.on('connection', function(socket){ | |
var newUser = { | |
name: 'user'+(num++), | |
numOfClicks: 0 | |
} | |
// add newUser | |
users.push(newUser); | |
// send info of newUser to the client | |
socket.emit('currentUser', newUser); | |
// send all users to all socket | |
io.sockets.emit('user joined', users); | |
// send current click to all socket | |
io.sockets.emit('update currentClick', currentClick); | |
// when a socket emit click => increase currentClick, increase num click of that socket | |
socket.on('click', function(){ | |
currentClick += 1; | |
newUser.numOfClicks +=1; | |
// emit event to update counter to all socket | |
io.sockets.emit('update user', newUser); | |
io.sockets.emit('update currentClick', currentClick) | |
}); | |
// remove user when socket disconnect | |
socket.on('disconnect', function(){ | |
users.splice(users.indexOf(newUser), 1); | |
}) | |
// check if user on socket is not the one has least click. | |
socket.on('win', function(){ | |
// sort users depend on num of click of user; | |
var sortedUsers = users.sort(function(a, b){ return a.numOfClicks - b.numOfClicks; }); | |
// if user has least click => no win | |
if(sortedUsers.indexOf(newUser) === 0){ | |
io.sockets.emit('no win', newUser) | |
} else{ | |
io.sockets.emit('win', newUser); | |
} | |
// reset all num of click of all socket | |
users = users.map(function(user){ return { name: user.name, numOfClicks: 0 }}) | |
// io.sockets.emit('user joined', users); | |
// reset current click | |
currentClick = 0; | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment