This repository has been archived by the owner on Jan 9, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
105 lines (86 loc) · 2.36 KB
/
server.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
var express = require('express')
, socket = require('socket.io')
, dictionary = require('./dictionary')
var app = express.createServer();
app.use(express.static(__dirname + '/public'));
app.listen(3000, function () {
var addr = app.address();
console.log(' app listening on http://' + addr.address + ':' + addr.port);
});
var io = socket.listen(app)
var players = {},
playedWords = {},
losers = []
var count = 0;
var playerId = 0;
var gameStarted = false;
io.sockets.on('connection', function (socket) {
playerId += 1;
count += 1;
players[socket.id] = {
words: {},
name: 'Player' + playerId
}
io.sockets.emit('players', players)
socket.emit('used', playedWords)
socket.on('attack', function (word, fn) {
word = word.toUpperCase()
var id = socket.id;
if (dictionary.hasOwnProperty(word)) {
if (players[id].words.hasOwnProperty(word)) {
delete players[id].words[word];
io.sockets.emit('block', word, id)
fn(null)
} else {
if (!playedWords.hasOwnProperty(word)) {
playedWords[word] = true;
io.sockets.emit('attack', word, id)
Object.keys(players).forEach(function(_id) {
if (id !== _id) {
players[_id].words[word] = true;
}
})
fn(null)
} else {
fn('Word has been played')
}
}
} else {
fn('Not a valid word')
}
});
socket.on('disconnect', function() {
delete players[socket.id]
io.sockets.emit('players', players)
count -= 1;
if (count <= 1) {
io.sockets.emit('gameOver')
gameStarted = false;
}
})
});
setInterval(function() {
if (Object.keys(players).length >= 2 && !gameStarted) {
io.sockets.emit('start', true);
gameStarted = true;
}
Object.keys(players).forEach(function(_id) {
if (Object.keys(players[_id].words).length >= 11) {
losers.push(_id);
io.sockets.emit('lose', _id)
}
})
if ((losers.length >= 1) && ((Object.keys(players).length - losers.length) === 1)) {
Object.keys(players).forEach(function(_id) {
if (losers.indexOf(_id) == -1) {
io.sockets.emit('win', _id)
Object.keys(players).forEach(function(_id) {
players[_id].words = {}
})
playedWords = {}
losers = []
gameStarted = false;
}
})
}
}, 5*1000)