-
Notifications
You must be signed in to change notification settings - Fork 2
/
win.js
87 lines (73 loc) · 2.78 KB
/
win.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
const usersStore = require('../stores/users');
const gamesStore = require('../stores/games');
const _ = require('lodash');
const async = require('async');
exports.description = '`!win [Team] {name}` - Report a win. Ex. `!win Team W`';
exports.matcher = /^\!win(?:\sTeam\s|\s)?(.*?)$/i;
exports.callback = function (route, message, response) {
const scope = `${message.team}_${message.channel}`;
if (!(message.channel in this.currentGames)) {
return response('No game in progress. Use `!start` to start a game.');
}
if(!route.matches[1] || !(route.matches[1].toUpperCase() in this.currentGames[message.channel])) {
return response('Please provide a valid team. For example `!win Team A`');
}
const winningTeam = route.matches[1].toUpperCase();
saveGame(scope, this.currentGames[message.channel][winningTeam === 'W' ? 'W' : 'M'], this.currentGames[message.channel][winningTeam === 'W' ? 'M' : 'W']);
response(`Congrats Team ${route.matches[1].toUpperCase()}!`);
async.parallel([].concat(
this.currentGames[message.channel]['W'].map(id => (callback) => incrementUserStats(scope, winningTeam === 'W' ? 'wins' : 'losses', id, callback)),
this.currentGames[message.channel]['M'].map(id => (callback) => incrementUserStats(scope, winningTeam === 'M' ? 'wins' : 'losses', id, callback))
), (error, result) => {
// Either way delete the game so it doesn't block
delete this.currentGames[message.channel];
if (error) {
return console.log(error);
}
usersStore.get(scope, (error, users) => {
if (error) {
return console.log(error);
}
const rankings = users.rank().reverse();
const top = rankings.slice(0, 3);
async.parallel(top.map(user => callback => this.web.users.info(user.id, callback)), (error, result) => {
if (error) {
return console.log(error);
}
const leaderboard = result.map((entry, index) => `${index + 1}) ${entry.user ? entry.user.real_name || entry.user.name : entry.error}`);
this.web.channels.setTopic(message.channel, leaderboard.join('\n'));
return;
});
});
});
};
function saveGame(scope, winner, loser) {
gamesStore.add(scope, {
winner,
loser,
timestamp: new Date().getTime()
}, (error) => {
if (error) {
console.log(error);
}
});
}
function incrementUserStats (scope, key, id, callback) {
usersStore.get(scope, (error, users) => {
if (error) {
return console.log(error);
}
const user = _.find(users, { id });
if (user) {
return usersStore.update(scope, { id }, Object.assign(user, {
[key]: user[key] + 1
}), callback);
} else {
return usersStore.add(scope, Object.assign({
id,
wins: 0,
losses: 0
}, { [key]: 1 }), callback);
}
});
}