-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstupidclient.js
123 lines (119 loc) · 2.64 KB
/
stupidclient.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
var PROTOCOL_VERSION = 11;
var ws = require('ws');
var defaults = {
url: "ws://localhost:5000",
ai: false,
rejoin: true,
log: true
};
var runBot = function(opts) {
var kaint, mint;
for(var k in defaults) {
if(!(k in opts)) {
opts[k] = defaults[k];
}
}
var ai = null;
var s = new ws(opts.url);
s.onopen = function() {
if("username" in opts) {
s.send("auth:"+opts.username+":"+opts.password+":"+PROTOCOL_VERSION);
}
else {
s.send("auth:"+PROTOCOL_VERSION);
}
kaint = setInterval(function() {
s.send("keepalive");
}, 10000);
};
var joined = false;
var users;
var maybeStart = function() {
if(users.length > 1 && users[0] == opts.username) {
s.send("gamestart");
}
};
var endGame = function() {
clearInterval(kaint);
clearInterval(mint);
s.close();
console.log("ending");
};
s.onmessage = function(d) {
if(opts.log) {console.log(d.data);}
var ileft = d.data == "leave:"+opts.username;
if(!joined || (ileft && opts.rejoin)) {
s.send("join:"+opts.room);
joined = true;
users = [];
ai = null;
}
else if(d.data.indexOf("join") == 0) {
users.push(d.data.substring(5));
maybeStart();
}
else if(d.data.indexOf("leave") == 0) {
users.splice(users.indexOf(d.data.substring(6)),1);
if(ileft && !opts.rejoin) {
endGame();
}
}
else if(d.data.indexOf("win") == 0) {
ai = null;
maybeStart();
}
else if(d.data.indexOf("update") == 0) {
var sp = d.data.substring(7).split(",");
if(sp[1] == "owner" && ai) {
var id = parseInt(sp[0]);
if(sp[2] == users.indexOf(opts.username)) {
ai.mynodes.push(id);
}
else {
var ind = ai.mynodes.indexOf(id);
if(ind > -1) {
ai.mynodes.splice(ind,1);
}
}
}
}
if(opts.ai && d.data.indexOf("gameinfo") == 0) {
var pos = users.indexOf(opts.username);
var j = JSON.parse(d.data.substring(9));
ai = {
mynodes: [],
nodecount: j.nodes.length
};
for(var i = 0; i < j.nodes.length; i++) {
if(j.nodes[i].owner == pos) {
ai.mynodes.push(i);
}
}
}
else if(ai && d.data == "gamestart") {
ai.active = true;
}
};
s.onclose = function() {
if(opts.log) {console.log("Lost connection");}
endGame();
};
var mint = setInterval(function(){
if(ai && ai.active) {
if(opts.log) {console.log(ai.mynodes);}
s.send("attack:"+ai.mynodes[Math.floor(Math.random()*ai.mynodes.length)]+","+Math.floor(Math.random()*ai.nodecount));
}
},1000);
};
if(require.main === module) {
var parseArgs = require('minimist');
var opts = parseArgs(process.argv, {
default: defaults,
alias: {
"u": "username",
"p": "password"
}
});
runBot(opts);
}
module.exports = runBot;