-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
72 lines (58 loc) · 1.87 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
// app.get('/', function(req, res){
// res.sendFile(__dirname + '/index.html');
// });
app.use(express.static(__dirname));
io.on('connection', function(socket){
var name = gu(); //generate username for new user
console.log('user connected and was granted the name: ' + name);
socket.broadcast.emit('system message', 'User <' + name + '> has connected.');
socket.on('disconnect', function(){
console.log('user <' + name + '> disconnected: freeing username');
socket.broadcast.emit('system message', 'User <' + name + '> has disconnected.');
free_username(name);
});
socket.on('chat message', function(msg){
//console.log('message: ' + msg);
//could use io.emit(someevent, {for: 'everyone'});
//socket.broadcast.emit('hi');
io.emit('chat message', msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
})
//Helper functions
function gu(){
if(gu.numOfNames<gu.MAX_NAMES){
while(true){
var name = gu.base[getRandomInt(0, gu.base.length)] + gu.suffix[getRandomInt(0, gu.suffix.length)];
if(!gu.get[name]){
gu.get[name]=true;
gu.numOfNames+=1;
return name;
}
}
}else{
console.log('failed to generate name: all names taken');
}
}
gu.numOfNames = 0;
gu.get = new Object();
gu.base = ['bard', 'ranger', 'fighter', 'mage', 'acolyte', 'rogue']
gu.suffix = ['jade', 'ruby', 'amber','topaz', 'diamond']
gu.MAX_NAMES = gu.base.length * gu.suffix.length;
function free_username(name){
if(gu.get[name]){
gu.get[name]=undefined;
gu.numOfNames-=1;
console.log('username: ' + name + ' freed.')
console.log('Currently there are: ' + gu.numOfNames + ' names in use.');
}
}
function getRandomInt(min, max) { //[min, max)
return Math.floor(Math.random() * (max - min)) + min;
}