-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgameState.js
More file actions
125 lines (104 loc) · 3.24 KB
/
gameState.js
File metadata and controls
125 lines (104 loc) · 3.24 KB
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
var Q = require('q');
var db = require('mongojs').connect('quiz', ['scores', 'players']);
function Quiz () {
this.startQuiz();
}
Quiz.prototype = {
gameState: 'starting',
startQuiz: function() {
// Continue previous quiz, or start new one if none found
Q.ninvoke(db.scores, 'findOne', {})
.done(function (scores) {
if (!scores) {
var scores = {
red: 0,
blue: 0,
green: 0,
yellow: 0
};
db.scores.insert(scores);
}
});
},
addPlayer: function (details) {
return Q.invoke(this, 'validatePlayer', details)
.then(function (result) {
if (result.success) {
return Q.ninvoke(db.players,'insert', details)
.then(function () {
return result;
});
} else {
return result;
}
});
},
modifyPlayer: function (details) {
return Q.invoke(this, 'validatePlayer', details)
.then(function (result) {
if (result.success) {
return Q.ninvoke(db.players, 'update', {uuid: details.uuid}, {$set: {name: details.name, team: details.team}}, {upsert: true})
.then(function () {
return result;
});
} else {
return result;
}
});
},
validatePlayer: function (details) {
var errors = {
name: [],
team: []
};
var validTeams = ['red', 'blue', 'green', 'yellow'];
var success = true;
if (validTeams.indexOf(details.team) === -1) {
errors.team.push('Please choose a valid team');
success = false;
}
if (!details.name) {
errors.name.push('Name is a mandatory field');
success = false;
}
return Q.ninvoke(db.players, 'find', {
team: details.team,
name: details.name,
uuid: {$ne: details.uuid}
})
.then(function (players) {
if (players.length) {
success = false;
errors.name.push('Someone on your team already has that name - please choose another');
}
return {success: success, errors: errors};
});
},
removePlayer: function (uuid) {
return Q.ninvoke(db.players, 'remove', {uuid: uuid});
},
getAllPlayers: function () {
return Q.ninvoke(db.players, 'find', {});
},
updateState: function (state) {
this.gameState = state;
return state;
},
getState: function () {
return this.gameState;
},
getScores: function () {
return Q.ninvoke(db.scores, 'findOne', {});
},
changeScore: function (data) {
var incDec = data.direction === 'up' ? 1 : -1;
var team = data.team
var self = this;
var updateSubObject = {};
updateSubObject[team] = incDec;
var updateObject = {$inc: updateSubObject};
return Q.ninvoke(db.scores, 'update', {}, updateObject)
.then(self.getScores);
}
};
exports.Quiz = Quiz;