-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdumb-bot.js
75 lines (62 loc) · 1.84 KB
/
dumb-bot.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
/**
* Module dependencies
*/
var hyperagent = require('hyperagent');
module.exports = function(root, name, secret) {
var client = hyperagent(root);
client.submit('.login', {name: name, secret: secret}, function(err) {
if (err) throw err;
client.set('authorization', 'Bearer ' + secret);
client('.games.open', function(err, games) {
if (games.length !== 0) return join(games[0]);
create();
});
});
function join(game) {
client
.submit('game.join', {})
.scope({game: game})
.get(function(err, value) {
if (err) throw err;
console.log('Joining game: ', game);
ready(game);
});
}
function create() {
var game = name + "'s game";
console.log('Creating game: ' + game);
client
.submit('.games.create', {name: game}, function(err, value) {
if (err) throw err;
ready(value);
});
}
function ready(game) {
client('game.state')
.scope({game: game})
.get(function(err, state) {
// no one has joined our game yet
if (!state) return setTimeout(ready.bind(null, game), 5000);
var shuffled = shuffle(state);
var piece, move;
for (var i = 0; i < shuffled.length; i++) {
piece = shuffled[i];
if (!piece.move) continue;
move = piece.move;
break;
}
if (!move) return setTimeout(ready.bind(null, game), 2000);
var position = shuffle(move.input.position.options)[0].value;
client
.submit('move', {position: position})
.scope({move: move})
.get(function(err) {
if (err) console.error(err.stack || err.message);
setTimeout(ready.bind(null, game), 2000);
});
});
}
};
function shuffle(arr) {
return arr.sort(function() {return Math.random() > .5 ? 1 : -1;});
}