This repository has been archived by the owner on Apr 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 28
/
battleroom.js
799 lines (689 loc) · 29.4 KB
/
battleroom.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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
// Class libary
JS = require('jsclass');
JS.require('JS.Class');
//does this work? will it show up?
require("sugar");
// Account file
var bot = require("./bot.js");
var account = bot.account;
// Results database
var db = require("./db");
// Logging
var log4js = require('log4js');
var logger = require('log4js').getLogger("battleroom");
var decisionslogger = require('log4js').getLogger("decisions");
//battle-engine
var Battle = require('./battle-engine/battle');
var BattlePokemon = require('./battle-engine/battlepokemon');
var Abilities = require("./data/abilities").BattleAbilities;
var Items = require("./data/items").BattleItems;
var _ = require("underscore");
var clone = require("./clone");
var program = require('commander'); // Get Command-line arguments
var BattleRoom = new JS.Class({
initialize: function(id, sendfunc) {
this.id = id;
this.title = "Untitled";
this.send = sendfunc;
// Construct a battle object that we will modify as our state
this.state = Battle.construct(id, 'base', false);
this.state.join('p1', 'botPlayer'); // We will be player 1 in our local simulation
this.state.join('p2', 'humanPlayer');
this.state.reportPercentages = true;
this.previousState = null; // For TD Learning
setTimeout(function() {
sendfunc(account.message, id); // Notify User that this is a bot
sendfunc("/timer", id); // Start timer (for user leaving or bot screw ups)
}, 10000);
this.decisions = [];
this.log = "";
this.state.start();
},
init: function(data) {
var log = data.split('\n');
if (data.substr(0, 6) === '|init|') {
log.shift();
}
if (log.length && log[0].substr(0, 7) === '|title|') {
this.title = log[0].substr(7);
log.shift();
logger.info("Title for " + this.id + " is " + this.title);
}
},
//given a player and a pokemon, returns the corresponding pokemon object
getPokemon: function(battleside, pokename) {
for(var i = 0; i < battleside.pokemon.length; i++) {
if(battleside.pokemon[i].name === pokename || //for mega pokemon
battleside.pokemon[i].name.substr(0,pokename.length) === pokename)
return battleside.pokemon[i];
}
return undefined; //otherwise Pokemon does not exist
},
//given a player and a pokemon, updates that pokemon in the battleside object
updatePokemon: function(battleside, pokemon) {
for(var i = 0; i < battleside.pokemon.length; i++) {
if(battleside.pokemon[i].name === pokemon.name) {
battleside.pokemon[i] = pokemon;
return;
}
}
logger.info("Could not find " + pokemon.name + " in the battle side, creating new Pokemon.");
for(var i = battleside.pokemon.length - 1; i >= 0; i--) {
if(battleside.pokemon[i].name === "Bulbasaur") {
battleside.pokemon[i] = pokemon;
return;
}
}
},
//returns true if the player object is us
isPlayer: function(player) {
return player === this.side + 'a:' || player === this.side + ':';
},
// TODO: Understand more about the opposing pokemon
updatePokemonOnSwitch: function(tokens) {
var tokens2 = tokens[2].split(' ');
var level = tokens[3].split(', ')[1].substring(1);
var tokens4 = tokens[4].split(/\/| /); //for health
var player = tokens2[0];
var pokeName = tokens2[1];
var health = tokens4[0];
var maxHealth = tokens4[1];
var battleside = undefined;
if (this.isPlayer(player)) {
logger.info("Our pokemon has switched! " + tokens[2]);
battleside = this.state.p1;
//remove boosts for current pokemon
this.state.p1.active[0].clearVolatile();
} else {
logger.info("Opponents pokemon has switched! " + tokens[2]);
battleside = this.state.p2;
//remove boosts for current pokemon
this.state.p2.active[0].clearVolatile();
}
var pokemon = this.getPokemon(battleside, pokeName);
if(!pokemon) { //pokemon has not been defined yet, so choose Bulbasaur
//note: this will not quite work if the pokemon is actually Bulbasaur
pokemon = this.getPokemon(battleside, "Bulbasaur");
var set = this.state.getTemplate(pokeName);
set.moves = set.randomBattleMoves;
//set.moves = _.sample(set.randomBattleMoves, 4); //for efficiency, need to implement move ordering
set.level = parseInt(level);
//choose the best ability
var abilities = Object.values(set.abilities).sort(function(a,b) {
return this.state.getAbility(b).rating - this.state.getAbility(a).rating;
}.bind(this));
set.ability = abilities[0];
pokemon = new BattlePokemon(set, battleside);
pokemon.trueMoves = []; //gradually add moves as they are seen
}
//opponent hp is recorded as percentage
pokemon.hp = Math.ceil(health / maxHealth * pokemon.maxhp);
pokemon.position = 0;
battleside.active[0].isActive = false;
pokemon.isActive = true;
this.updatePokemon(battleside,pokemon);
battleside.active = [pokemon];
//Ensure that active pokemon is in slot zero
battleside.pokemon = _.sortBy(battleside.pokemon, function(pokemon) { return pokemon == battleside.active[0] ? 0 : 1 });
},
updatePokemonOnMove: function(tokens) {
var tokens2 = tokens[2].split(' ');
var player = tokens2[0];
var pokeName = tokens2[1];
var move = tokens[3];
var battleside = undefined;
if(this.isPlayer(player)) {
battleside = this.state.p1;
} else {
battleside = this.state.p2;
}
var pokemon = this.getPokemon(battleside, pokeName);
if(!pokemon) {
logger.error("We have never seen " + pokeName + " before in this battle. Should not have happened.");
return;
}
//update last move (doesn't actually affect the bot...)
pokemon.lastMove = toId(move);
//if move is protect or detect, update stall counter
if('stall' in pokemon.volatiles) {
pokemon.volatiles.stall.counter++;
}
//update status duration
if(pokemon.status) {
pokemon.statusData.duration = (pokemon.statusData.duration?
pokemon.statusData.duration+1:
1);
}
//we are no longer newly switched (so we don't fakeout after the first turn)
pokemon.activeTurns += 1;
if(!this.isPlayer(player)) { //anticipate more about the Pokemon's moves
if(pokemon.trueMoves.indexOf(toId(move)) < 0 && pokemon.trueMoves.length < 4) {
pokemon.trueMoves.push(toId(move));
logger.info("Determined that " + pokeName + " can use " + toId(move));
//if we have collected all of the moves, eliminate all other possibilities
if(pokemon.trueMoves.length >= 4) {
logger.info("Collected all of " + pokeName + "'s moves!");
var newMoves = [];
var newMoveset = [];
for(var i = 0; i < pokemon.moveset.length; i++) {
if(pokemon.trueMoves.indexOf(pokemon.moveset[i].id) >= 0) {
newMoves.push(pokemon.moveset[i].id); //store id
newMoveset.push(pokemon.moveset[i]); //store actual moves
}
}
pokemon.moves = newMoves;
pokemon.moveset = newMoveset;
}
}
}
this.updatePokemon(battleside, pokemon);
},
updatePokemonOnDamage: function(tokens) {
//extract damage dealt to a particular pokemon
//also takes into account passives
//note that opponent health is recorded as percent. Keep this in mind
var tokens2 = tokens[2].split(' ');
var tokens3 = tokens[3].split(/\/| /);
var player = tokens2[0];
var pokeName = tokens2[1];
var health = tokens3[0];
var maxHealth = tokens3[1];
var battleside = undefined;
if(this.isPlayer(player)) {
battleside = this.state.p1;
} else {
battleside = this.state.p2;
}
var pokemon = this.getPokemon(battleside, pokeName);
if(!pokemon) {
logger.error("We have never seen " + pokeName + " before in this battle. Should not have happened.");
return;
}
//update hp
pokemon.hp = Math.ceil(health / maxHealth * pokemon.maxhp);
this.updatePokemon(battleside, pokemon);
},
updatePokemonOnBoost: function(tokens, isBoost) {
var tokens2 = tokens[2].split(' ');
var stat = tokens[3];
var boostCount = parseInt(tokens[4]);
var player = tokens2[0];
var pokeName = tokens2[1];
var battleside = undefined;
if(this.isPlayer(player)) {
battleside = this.state.p1;
} else {
battleside = this.state.p2;
}
var pokemon = this.getPokemon(battleside, pokeName);
if(!pokemon) {
logger.error("We have never seen " + pokeName + " before in this battle. Should not have happened.");
return;
}
if(isBoost) {
if(stat in pokemon.boosts)
pokemon.boosts[stat] += boostCount;
else
pokemon.boosts[stat] = boostCount;
} else {
if(stat in pokemon.boosts)
pokemon.boosts[stat] -= boostCount;
else
pokemon.boosts[stat] = -boostCount;
}
this.updatePokemon(battleside, pokemon);
},
updatePokemonSetBoost: function(tokens) {
var tokens2 = tokens[2].split(' ');
var stat = tokens[3];
var boostCount = parseInt(tokens[4]);
var player = tokens2[0];
var pokeName = tokens2[1];
var battleside = undefined;
if(this.isPlayer(player)) {
battleside = this.state.p1;
} else {
battleside = this.state.p2;
}
var pokemon = this.getPokemon(battleside, pokeName);
if(!pokemon) {
logger.error("We have never seen " + pokeName + " before in this battle. Should not have happened.");
return;
}
pokemon.boosts[stat] = boostCount;
this.updatePokemon(battleside, pokemon);
},
updatePokemonRestoreBoost: function(tokens) {
var tokens2 = tokens[2].split(' ');
var player = tokens2[0];
var pokeName = tokens2[1];
var battleside = undefined;
if(this.isPlayer(player)) {
battleside = this.state.p1;
} else {
battleside = this.state.p2;
}
var pokemon = this.getPokemon(battleside, pokeName);
if(!pokemon) {
logger.error("We have never seen " + pokeName + " before in this battle. Should not have happened.");
return;
}
for(var stat in pokemon.boosts) {
if(pokemon.boosts[stat] < 0)
delete pokemon.boosts[stat];
}
this.updatePokemon(battleside, pokemon);
},
updatePokemonStart: function(tokens, newStatus) {
//add condition such as leech seed, substitute, ability, confusion, encore
//move: yawn, etc.
//ability: flash fire, etc.
var tokens2 = tokens[2].split(' ');
var player = tokens2[0];
var pokeName = tokens2[1];
var status = tokens[3];
var battleside = undefined;
if(this.isPlayer(player)) {
battleside = this.state.p1;
} else {
battleside = this.state.p2;
}
var pokemon = this.getPokemon(battleside, pokeName);
if(status.substring(0,4) === 'move') {
status = status.substring(6);
} else if(status.substring(0,7) === 'ability') {
status = status.substring(9);
}
if(newStatus) {
pokemon.addVolatile(status);
} else {
pokemon.removeVolatile(status);
}
this.updatePokemon(battleside, pokemon);
},
updateField: function(tokens, newField) {
//as far as I know, only applies to trick room, which is a pseudo-weather
var fieldStatus = tokens[2].substring(6);
if(newField) {
this.state.addPseudoWeather(fieldStatus);
} else {
this.state.removePseudoWeather(fieldStatus);
}
},
updateWeather: function(tokens) {
var weather = tokens[2];
if(weather === "none") {
this.state.clearWeather();
} else {
this.state.setWeather(weather);
//we might want to keep track of how long the weather has been lasting...
//might be done automatically for us
}
},
updateSideCondition: function(tokens, newSide) {
var player = tokens[2].split(' ')[0];
var sideStatus = tokens[3];
if(sideStatus.substring(0,4) === "move")
sideStatus = tokens[3].substring(6);
var battleside = undefined;
if(this.isPlayer(player)) {
battleside = this.state.p1;
} else {
battleside = this.state.p2;
}
if(newSide) {
battleside.addSideCondition(sideStatus);
//Note: can have multiple layers of toxic spikes or spikes
} else {
battleside.removeSideCondition(sideStatus);
//remove side status
}
},
updatePokemonStatus: function(tokens, newStatus) {
var tokens2 = tokens[2].split(' ');
var player = tokens2[0];
var pokeName = tokens2[1];
var status = tokens[3];
var battleside = undefined;
if(this.isPlayer(player)) {
battleside = this.state.p1;
} else {
battleside = this.state.p2;
}
var pokemon = this.getPokemon(battleside, pokeName);
if(newStatus) {
pokemon.setStatus(status);
//record a new Pokemon's status
//also keep track of how long the status has been going? relevant for toxic poison
//actually, might be done by default
} else {
pokemon.clearStatus();
//heal a Pokemon's status
}
this.updatePokemon(battleside, pokemon);
},
updatePokemonOnItem: function(tokens, newItem) {
//record that a pokemon has an item. Most relevant if a Pokemon has an air balloon/chesto berry
//TODO: try to predict the opponent's current item
var tokens2 = tokens[2].split(' ');
var player = tokens2[0];
var pokeName = tokens2[1];
var item = tokens[3];
var battleside = undefined;
if(this.isPlayer(player)) {
battleside = this.state.p1;
} else {
battleside = this.state.p2;
}
var pokemon = this.getPokemon(battleside, pokeName);
if(newItem) {
pokemon.setItem(item);
} else {
pokemon.clearItem(item);
}
this.updatePokemon(battleside, pokemon);
},
//Apply mega evolution effects, or aegislash/meloetta
updatePokemonOnFormeChange: function(tokens) {
var tokens2 = tokens[2].split(' ');
var tokens3 = tokens[3].split(', ');
var player = tokens2[0];
var pokeName = tokens2[1];
var newPokeName = tokens3[0];
var battleside = undefined;
if(this.isPlayer(player)) {
battleside = this.state.p1;
} else {
battleside = this.state.p2;
}
//Note: crashes when the bot mega evolves.
logger.info(pokeName + " has transformed into " + newPokeName + "!");
var pokemon = this.getPokemon(battleside, pokeName, true);
//apply forme change
pokemon.formeChange(newPokeName);
this.updatePokemon(battleside, pokemon);
},
//for ditto exclusively
updatePokemonOnTransform: function(tokens) {
var tokens2 = tokens[2].split(' ');
var tokens3 = tokens[3].split(' ');
var player = tokens2[0];
var pokeName = tokens2[1];
var newPokeName = tokens3[1];
var battleside = undefined;
var pokemon = undefined;
if(this.isPlayer(player)) {
battleside = this.state.p1;
pokemon = this.getPokemon(battleside, pokeName);
pokemon.transformInto(this.state.p2.active[0]);
} else {
battleside = this.state.p2;
pokemon = this.getPokemon(battleside, pokeName);
pokemon.transformInto(this.state.p1.active[0]);
}
this.updatePokemon(battleside, pokemon);
},
recieve: function(data) {
if (!data) return;
logger.trace("<< " + data);
if (data.substr(0, 6) === '|init|') {
return this.init(data);
}
if (data.substr(0, 9) === '|request|') {
return this.receiveRequest(JSON.parse(data.substr(9)));
}
var log = data.split('\n');
for (var i = 0; i < log.length; i++) {
this.log += log[i] + "\n";
var tokens = log[i].split('|');
if (tokens.length > 1) {
if (tokens[1] === 'tier') {
this.tier = tokens[2];
} else if (tokens[1] === 'win') {
this.send("gg", this.id);
this.winner = tokens[2];
if (this.winner == account.username) {
logger.info(this.title + ": I won this game");
} else {
logger.info(this.title + ": I lost this game");
}
if(program.net === "update" && this.previousState) {
var playerAlive = _.any(this.state.p1.pokemon, function(pokemon) { return pokemon.hp > 0; });
var opponentAlive = _.any(this.state.p2.pokemon, function(pokemon) { return pokemon.hp > 0; });
if(!playerAlive || !opponentAlive) minimaxbot.train_net(this.previousState, null, (this.winner == account.username));
}
if(!program.nosave) this.saveResult();
// Leave in two seconds
var battleroom = this;
setTimeout(function() {
battleroom.send("/leave " + battleroom.id);
}, 2000);
} else if (tokens[1] === 'switch' || tokens[1] === 'drag') {
this.updatePokemonOnSwitch(tokens);
} else if (tokens[1] === 'move') {
this.updatePokemonOnMove(tokens);
} else if(tokens[1] === 'faint') { //we could outright remove a pokemon...
//record that pokemon has fainted
} else if(tokens[1] === 'detailschange' || tokens[1] === 'formechange') {
this.updatePokemonOnFormeChange(tokens);
} else if(tokens[1] === '-transform') {
this.updatePokemonOnTransform(tokens);
} else if(tokens[1] === '-damage') { //Error: not getting to here...
this.updatePokemonOnDamage(tokens);
} else if(tokens[1] === '-heal') {
this.updatePokemonOnDamage(tokens);
} else if(tokens[1] === '-boost') {
this.updatePokemonOnBoost(tokens, true);
} else if(tokens[1] === '-unboost') {
this.updatePokemonOnBoost(tokens, false);
} else if(tokens[1] === '-setboost') {
this.updatePokemonSetBoost(tokens);
} else if(tokens[1] === '-restoreboost') {
this.updatePokemonRestoreBoost(tokens);
} else if(tokens[1] === '-start') {
this.updatePokemonStart(tokens, true);
} else if(tokens[1] === '-end') {
this.updatePokemonStart(tokens, false);
} else if(tokens[1] === '-fieldstart') {
this.updateField(tokens, true);
} else if(tokens[1] === '-fieldend') {
this.updateField(tokens, false);
} else if(tokens[1] === '-weather') {
this.updateWeather(tokens);
} else if(tokens[1] === '-sidestart') {
this.updateSideCondition(tokens, true);
} else if(tokens[1] === '-sideend') {
this.updateSideCondition(tokens, false);
} else if(tokens[1] === '-status') {
this.updatePokemonStatus(tokens, true);
} else if(tokens[1] === '-curestatus') {
this.updatePokemonStatus(tokens, false);
} else if(tokens[1] === '-item') {
this.updatePokemonOnItem(tokens, true);
} else if(tokens[1] === '-enditem') {
this.updatePokemonOnItem(tokens, false);
} else if(tokens[1] === '-ability') {
//relatively situational -- important for mold breaker/teravolt, etc.
//needs to be recorded so that we don't accidentally lose a pokemon
//We don't actually care about the rest of these effects, as they are merely visual
} else if(tokens[1] === '-supereffective') {
} else if(tokens[1] === '-crit') {
} else if(tokens[1] === '-singleturn') { //for protect. But we only care about damage...
} else if(tokens[1] === 'c') {//chat message. ignore. (or should we?)
} else if(tokens[1] === '-activate') { //protect, wonder guard, etc.
} else if(tokens[1] === '-fail') {
} else if(tokens[1] === '-immune') {
} else if(tokens[1] === 'message') {
} else if(tokens[1] === 'cant') {
} else if(tokens[1] === 'leave') {
} else if(tokens[1]) { //what if token is defined
logger.info("Error: could not parse token '" + tokens[1] + "'. This needs to be implemented");
}
}
}
},
saveResult: function() {
// Save game data to data base
game = {
"title": this.title,
"id": this.id,
"win": (this.winner == account.username),
"date": new Date(),
"decisions": "[]", //JSON.stringify(this.decisions),
"log": this.log,
"tier": this.tier
};
db.insert(game, function(err, newDoc) {
if(newDoc) logger.info("Saved result of " + newDoc.title + " to database.");
else logger.error("Error saving result to database.");
});
},
receiveRequest: function(request) {
if (!request) {
this.side = '';
return;
}
if (request.side) this.updateSide(request.side, true);
if (request.active) logger.info(this.title + ": I need to make a move.");
if (request.forceSwitch) logger.info(this.title + ": I need to make a switch.");
if (request.active || request.forceSwitch) this.makeMove(request);
},
//note: we should not be recreating pokemon each time
//is this redundant?
updateSide: function(sideData) {
if (!sideData || !sideData.id) return;
logger.info("Starting to update my side data.");
for (var i = 0; i < sideData.pokemon.length; ++i) {
var pokemon = sideData.pokemon[i];
var details = pokemon.details.split(",");
var name = details[0].trim();
var level = parseInt(details[1].trim().substring(1));
var gender = details[2] ? details[2].trim() : null;
var template = {
name: name,
moves: pokemon.moves,
ability: Abilities[pokemon.baseAbility].name,
evs: {
hp: 85,
atk: 85,
def: 85,
spa: 85,
spd: 85,
spe: 85
},
ivs: {
hp: 31,
atk: 31,
def: 31,
spa: 31,
spd: 31,
spe: 31
},
item: (!pokemon.item || pokemon.item === '') ? '' : Items[pokemon.item].name,
level: level,
active: pokemon.active,
shiny: false
};
//keep track of old pokemon
var oldPokemon = this.state.p1.pokemon[i];
// Initialize pokemon
this.state.p1.pokemon[i] = new BattlePokemon(template, this.state.p1);
this.state.p1.pokemon[i].position = i;
// Update the pokemon object with latest stats
for (var stat in pokemon.stats) {
this.state.p1.pokemon[i].baseStats[stat] = pokemon.stats[stat];
}
// Update health/status effects, if any
var condition = pokemon.condition.split(/\/| /);
this.state.p1.pokemon[i].hp = parseInt(condition[0]);
if(condition.length > 2) {//add status condition
this.state.p1.pokemon[i].setStatus(condition[2]); //necessary
}
if(oldPokemon.isActive && oldPokemon.statusData) { //keep old duration
pokemon.statusData = oldPokemon.statusData;
}
// Keep old boosts
this.state.p1.pokemon[i].boosts = oldPokemon.boosts;
// Keep old volatiles
this.state.p1.pokemon[i].volatiles = oldPokemon.volatiles;
if (pokemon.active) {
this.state.p1.active = [this.state.p1.pokemon[i]];
this.state.p1.pokemon[i].isActive = true;
}
// TODO(rameshvarun): Somehow parse / load in current hp and status conditions
}
// Enforce that the active pokemon is in the first slot
this.state.p1.pokemon = _.sortBy(this.state.p1.pokemon, function(pokemon) { return pokemon.isActive ? 0 : 1 });
this.side = sideData.id;
this.oppSide = (this.side === "p1") ? "p2" : "p1";
logger.info(this.title + ": My current side is " + this.side);
},
makeMove: function(request) {
var room = this;
setTimeout(function() {
if(program.net === "update") {
if(room.previousState != null) minimaxbot.train_net(room.previousState, room.state);
room.previousState = clone(room.state);
}
var decision = BattleRoom.parseRequest(request);
// Use specified algorithm to determine resulting choice
var result = undefined;
if(decision.choices.length == 1) result = decision.choices[0];
else if(program.algorithm === "minimax") result = minimaxbot.decide(clone(room.state), decision.choices);
else if(program.algorithm === "greedy") result = greedybot.decide(clone(room.state), decision.choices);
else if(program.algorithm === "random") result = randombot.decide(clone(room.state), decision.choices);
room.decisions.push(result);
room.send("/choose " + BattleRoom.toChoiceString(result, room.state.p1) + "|" + decision.rqid, room.id);
}, 5000);
},
// Static class methods
extend: {
toChoiceString: function(choice, battleside) {
if (choice.type == "move") {
if(battleside && battleside.active[0].canMegaEvo) //mega evolve if possible
return "move " + choice.id + " mega";
else
return "move " + choice.id;
} else if (choice.type == "switch") {
return "switch " + (choice.id + 1);
}
},
parseRequest: function(request) {
var choices = [];
if(!request) return choices; // Empty request
if(request.wait) return choices; // This player is not supposed to make a move
// If we can make a move
if (request.active) {
_.each(request.active[0].moves, function(move) {
if (!move.disabled) {
choices.push({
"type": "move",
"id": move.id
});
}
});
}
// Switching options
var trapped = (request.active) ? (request.active[0].trapped || request.active[0].maybeTrapped) : false;
var canSwitch = request.forceSwitch || !trapped;
if (canSwitch) {
_.each(request.side.pokemon, function(pokemon, index) {
if (pokemon.condition.indexOf("fnt") < 0 && !pokemon.active) {
choices.push({
"type": "switch",
"id": index
});
}
});
}
return {
rqid: request.rqid,
choices: choices
};
}
}
});
module.exports = BattleRoom;
var minimaxbot = require("./bots/minimaxbot");
var greedybot = require("./bots/greedybot");
var randombot = require("./bots/randombot");