-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapi.js
367 lines (330 loc) · 10.2 KB
/
api.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
var game = require('./game.js');
var utils = require('./utils.js');
var debug = require('./debug.js');
function Api(io, db) {
this.io = io;
this.db = db;
// circular dependency with api
// set with setGameManager()
this.gm = undefined;
}
Api.prototype = {
/**
* @param {Object} gm
*/
setGameManager : function(gm){
this.gm = gm;
},
setCampusManager : function (cm) {
this.cm = cm;
},
/**
* add a user
* call on completion callback(<boolean> success)
*/
addUser : function(data, callback) {
var id = data.id;
var name = data.name;
var school = data.campus;
var pw = data.pw;
var img_url = data.img_url || "";
if (id === undefined || name === undefined
|| school === undefined
|| pw === undefined) {
callback(false);
return;
}
var query = "INSERT INTO \"global\".\"users\" (id, \"name\", school, img_url, password, last_signin) VALUES (\'"+id+"\', \'"+name+"\',\'"+school+"\',\'"+img_url+"\',\'"+pw+"\', CURRENT_TIMESTAMP);";
this.db.query(query, function(err, result) {
callback(err === null);
});
},
confirmCredentials : function(id, pw, callback) {
var query = "SELECT (id, password) FROM global.users WHERE id='"+id+"'";
this.db(query, function(err, result) {
if(err) {
utils.logErr(err)
}
});
},
createGame : function(data, callback) {
console.log(data);
if (data.game_id == undefined) {
return false;
}
var GAME_ID = data.game_id;
var GAME_DESC = data.game_desc || "";
var GAME_PRIVACY = 2; //data.privacy
var GAME_CAMPUS = data.campus;
var GAME_MAP = data.map || "default";
var options = {};
options.quick_start = data.quick_start === "on";
var campus = this.cm.getCampusData(GAME_CAMPUS);
var query = "\
INSERT INTO \"global\".\"games\" (id, \"desc\", privacy,stage,campus,map) VALUES (\'"+GAME_ID+"\', \'"+GAME_DESC+"\', "+GAME_PRIVACY+",'grab',\'"+GAME_CAMPUS+"',\'"+GAME_MAP+"\');\
\
SET search_path = teams, pg_catalog;\
\
CREATE TABLE \""+GAME_ID+"\"(\
index smallint NOT NULL,\
id text,\
player_count smallint DEFAULT 1,\
waiting_on boolean DEFAULT true,\
password text DEFAULT ''\
);\
\
ALTER TABLE teams.\""+GAME_ID+"\" OWNER TO ccadmin;\
\
SET search_path = state, pg_catalog;\
\
CREATE TABLE \""+GAME_ID+"\"(\
piece_name text NOT NULL,\
team smallint DEFAULT -1,\
units smallint DEFAULT 0 NOT NULL,\
player text DEFAULT '',\
\"timestamp\" timestamp with time zone DEFAULT now() NOT NULL\
);\
\
ALTER TABLE state.\""+GAME_ID+"\" OWNER TO ccadmin;\
";
var pieces = campus.getPieceList();
for (var i = 0; i < pieces.length; i++) {
query += "INSERT INTO \""+GAME_ID+"\" (piece_name) VALUES ('"+pieces[i]+"');";
}
this.db.query(query, function(err, result) {
if (err) {
console.log(query);
console.log(err);
} else {
var all_teams = campus.getTeamList();
var GAME_TEAMS = [];
for (var i = 0; i < all_teams.length; i++) {
if (data[all_teams[i]]) {
GAME_TEAMS.push(all_teams[i]);
}
}
utils.shuffle(GAME_TEAMS);
for (var i = 0; i < GAME_TEAMS.length; i++) {
var query = "INSERT INTO teams.\"" + GAME_ID + "\" VALUES (" + i + ",'"+ GAME_TEAMS[i] + "',1,TRUE,'')";
this.db.query(query, function(err) {
if (err) {
console.log('ERROR CREATING GAME');
console.log(query);
console.log(err);
}
});
}
// XXX TODO FIXME game manage requires game be in db
// db requires it be in game manager...
// CIRCULAR DEPENDENCY!! :'(
this.getDbState(GAME_ID, function(state) {
var new_game = this.gm.createGame(state, options);
callback(new_game);
}.bind(this));
}
}.bind(this));
},
forkGame : function(GAME_ID) {
var game_info = {game_id : GAME_ID + " - copy" , game_desc: "Copy of " + GAME_ID};
this.getState(GAME_ID, function(state_to_copy) {
console.log('forkGame: state_to_copy', state_to_copy);
// avoid name collisions for multiple copies of same game
while (this.gm.gameExists(game_info.game_id)) {
game_info.game_id += "*";
}
this.createGame(game_info, function(new_game) {
new_game.updateGameData(state_to_copy);
}.bind(this));
}.bind(this));
},
deleteGame : function(GAME_ID){
var query = "\
DELETE FROM \"global\".\"games\" WHERE id = \'"+GAME_ID+ "\';\
DROP TABLE IF EXISTS teams.\""+GAME_ID+"\";\
DROP TABLE IF EXISTS state.\""+GAME_ID+"\";\
";
this.db.query(query, function(err, result) {
if (err) {
console.log(err);
} else{
console.log("Dropped Game " + GAME_ID);
}
});
},
getOpenGames : function(callback){
this.db.query('SELECT "id","desc" FROM "global"."games"', function(err, result){
var ret = result.rows;
ret.sort(function(a,b) {
return a.id > b.id;
});
callback(ret);
});
},
// gets the current state of game id <string> and runs callback(state) when done
// includes data in memory like waiting_on
getState : function(id, callback) {
this.getDbState(id, function(data){
data.waiting_on = this.gm.getGame(id).getWaitingOn();
callback(data);
}.bind(this));
},
// gets the state from the DB,
// does not include temp info like whose turn it is
getDbState : function(id, callback) {
var ret = {
status : 200
};
this.db.query('SELECT * FROM "global"."games" WHERE id=\'' + id + '\'', function(err, result) {
var data = result.rows[0];
if (err || data === undefined) {
callback({
status : 500,
message : "game not found",
});
return;
}
ret.id = data.id;
ret.campus = data.campus;
ret.map = data.map;
ret.stage = data.stage;
ret.turn = data.turn;
ret.team_order = {};
ret.current_team = data.cur_team;
// add the key in the object for better layout of getState()
ret.waiting_on = undefined;
this.db.query('SELECT * FROM "state"."' + id + '"', function(err, result) {
if (err) {
callback({
status : 500
});
return;
}
ret.state = {};
for (var i = 0; i < result.rows.length; i++) {
var piece = result.rows[i];
ret.state[piece.piece_name] = {
team : piece.team,
units : piece.units,
}
}
this.db.query('SELECT * FROM "teams"."' + id + '"', function(err, result) {
if (err) {
callback({
status : 500
});
return;
}
ret.team_order = [];
var order = ret.team_order;
for (var i = 0; i < result.rows.length; i++) {
var r = result.rows[i];
order[r.index] = r.id;
}
callback(ret);
}.bind(this));
}.bind(this));
}.bind(this));
},
// XXX TODO duplicated code in game.js
getReinforcements : function(game_id, team_id, callback){
if(!this.gm.gameExists(game_id)){
console.log('GAME DOES NOT EXIST');
callback({status: 500, error: "game not found"});
}
var game = this.gm.getGame(game_id);
var team_index = game.getTeamIndexFromId(team_id);
if(team_index < 0) {
callback({status: 500, error: "team id not found"});
} else {
var state = game.state;
var reinforcements = {};
// contribution from number of pieces owned
var piece_count = 0;
for (var id in state) {
if (state.hasOwnProperty(id)) {
s = state[id];
if (s.team === team_index) {
piece_count++;
}
}
}
reinforcements.piece_count = {name : "Territory Count Bonus", count: Math.ceil(piece_count / 3)};
// contribution from regions
var regions = game.campus.map.regions;
var keys = Object.keys(regions);
for (var i = 0; i < keys.length; i++) {
var pieces = regions[keys[i]].pieces;
var bonus = regions[keys[i]].value;
for (var j = 0; j < pieces.length; j++) {
if (state[pieces[j]].team !== team_index) {
bonus = 0;
break;
}
}
if (bonus !== 0) {
var region_id = keys[i];
reinforcements[keys[i]] = {name : regions[region_id].name, count: bonus};
}
}
// contribution from contiguous
// contribution from other
var total = 0;
var keys = Object.keys(reinforcements);
for (var i = 0; i < keys.length; i++) {
total += reinforcements[keys[i]].count;
}
// always have at least 1 reinforcement
if (total === 0) {
reinforcements.other = {name : "Other", count : 1};
total++;
}
reinforcements.total = {name : "Total", count : total};
callback({status: 200, id: game_id, team: team_index, reinforcements : reinforcements});
}
},
moveAI : function(data, callback) {
console.log(data);
var game_id = data.id;
var team_index = data.team;
console.log(game_id);
var g = this.gm.getGame(game_id);
var move = g.moveAI(team_index);
callback(move);
},
/**
* A set of overrides for debugging
*/
handleMasterRequest : function(req, callback) {
console.log("MASTER REQUEST RECEIVED");
var game_id = req.game_id;
if(!this.gm.gameExists(game_id)){
console.log('GAME DOES NOT EXIST');
callback({success: false});
}
var g = this.gm.getGame(game_id);
var key = req.key;
var command = req.command;
var data = req.data;
this.io.to(game_id).emit('override');
switch (command){
case "reset-turn":
g.forceResetTurn();
break;
case "next-turn":
g.forceNextTurn();
break;
case "set-piece-state":
var p = data.piece;
var new_state = {};
new_state[p] = {
"units": parseInt(data.units),
"team": parseInt(data.team),
};
g.updatePartialState(new_state);
this.io.to(game_id).emit('update partial state', new_state);
break;
}
callback({success: true});
},
}
module.exports = Api;