forked from jpeterbaker/bga_homeworlds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
homeworlds.js
1956 lines (1826 loc) · 76.1 KB
/
homeworlds.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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
*------
* BGA framework: © Gregory Isabelli <[email protected]> & Emmanuel Colin <[email protected]>
* Homeworlds implementation : © <Jonathan Baker> <[email protected]>
*
* This code has been produced on the BGA studio platform for use on http://boardgamearena.com.
* See http://en.boardgamearena.com/#!doc/Studio for more information.
* -----
*
* homeworlds.js
*
* Homeworlds user interface script
*
* In this file, you are describing the logic of your user interface, in Javascript language.
*
*/
define([
"dojo",
"dojo/_base/declare",
"ebg/core/gamegui",
"ebg/counter"
],
function (dojo, declare) {
return declare( "bgagame.homeworlds", ebg.core.gamegui, {
constructor: function(){
this.color_names_eng = {1:'red',2:'yellow',3:'green',4:'blue'};
this.color_names_local = {1:_('red'),2:_('yellow'),3:_('green'),4:_('blue')};
this.size_names_eng = {1:'small',2:'medium',3:'large'};
//this.size_names_local = {1:_('small'),2:_('medium'),3:_('large')};
// Once homeworlds are established,
// colony_assignments[size] will be the position (1,2, or 3)
// where colonies with stars of the given size belong
// (in a colony_container)
this.colony_assignments = {1:1,2:2,3:3};
},
/*
setup:
This method must set up the game user interface according to
current game situation specified in parameters.
The method is called each time the game interface is displayed to a player, ie:
_ when the game starts
_ when a player refreshes the game page (F5)
"gamedatas" argument contains all datas retrieved by your "getAllDatas" PHP method.
*/
setup: function(gamedatas) {
// Remember player positions
var player;
for(var player_id in gamedatas.players){
player = gamedatas.players[player_id];
this['player_'+player.player_no] = player_id;
}
// Display first player indicator in the player panel
var player_label = _('First player');
dojo.place(
"<div class='HWfirst_player_indicator'>"+player_label+"</div>",
'player_board_'+this.player_1
);
this.setup_pieces(gamedatas);
// Setup turn token
var token_pos;
if(this.getActivePlayerId() == this.get_bot_player())
token_pos = 'bot';
else
token_pos = 'top';
var token_space = document.getElementById('HWtoken_space_'+token_pos);
dojo.place("<div id='HWturn_token'></div>",token_space);
// Setup game notifications to handle (see "setupNotifications" method below)
this.setupNotifications();
},
setup_pieces: function(gamedatas){
var colornum,pipsnum;
var params;
var piece_id,stack_id;
// Create bank pieces
for(piece_id in gamedatas.bank){
piece = gamedatas.bank[piece_id];
stack_id = 'HWstack_'+piece.color+'_'+piece.pips;
this.setup_piece(piece,'HWbanked',stack_id);
}
// Create systems and their pieces
var system;
for(system_id in gamedatas.systems) {
system = gamedatas.systems[system_id];
this.setup_system(system);
}
// If colonies already existed,
// they were placed according to old colony assignments
// It's not enough to just remake colony assignments
this.arrange_colonies();
},
clear_all: function(){
var pieces_and_systems = dojo.query('.HWsystem,.HWship,.HWstar,.HWbanked');
pieces_and_systems.remove();
},
///////////////////////////////////////////////////
//// Game & client states
// onEnteringState:
// This method is called each time we are entering into a new game state.
// You can use this method to perform user interface changes.
onEnteringState: function( state_name, args ) {
// Current player saves most recent info from server
// to make it easier to cancel partial actions from client states.
// All server-side player-decision states start with "want"
if(this.isCurrentPlayerActive() && state_name.startsWith('want'))
this.set_turn_checkpoint(args,state_name);
// Call appropriate method
var methodName = 'onEntering_' + state_name;
if (this[methodName] !== undefined)
this[methodName](args.args);
},
onEntering_want_creation: function(args){
if(!this.isCurrentPlayerActive())
return
var stacks = dojo.query('.HWstack');
stacks.addClass('HWselectable');
this.connectClass('HWselectable','onclick','stack_selected_star_creation');
this.add_tooltip(
stacks,
_('Click to add this star to your homeworld'),
1500
);
// You could instead use
// stacks.connect('onclick',this,'stack_selected_star_creation' );
// but then this.disconnect wouldn't work
},
onEntering_client_want_creation_ship: function(args){
if(!this.isCurrentPlayerActive())
return
this.disconnectAll();
var stacks = dojo.query('.HWstack');
stacks.addClass('HWselectable');
this.add_tooltip(
stacks,
_('Click to add this ship to your homeworld'),
1500
);
this.connectClass('HWselectable','onclick','stack_selected_ship_creation');
},
onEntering_client_want_creation_confirmation: function(args){
if(!this.isCurrentPlayerActive())
return
// The buttons are handled in onUpdateActionButtons
dojo.addClass('HWturn_token','HWonly_option');
},
onEntering_want_free: function(args){
if(!this.isCurrentPlayerActive())
return
var ships = dojo.query('.HWship.HWfriendly');
ships.addClass('HWselectable');
this.add_tooltip(
ships,
_('Click to activate or sacrifice this ship'),
1500
);
var f = dojo.hitch(
this,
function(evt){
evt.preventDefault();
dojo.stopEvent(evt);
this.activate_ship(evt.currentTarget);
}
);
this.connect_nodes(
ships,
f
);
},
onEntering_want_sacrifice_action: function(args){
if(!this.isCurrentPlayerActive())
return
var ships = dojo.query('.HWship.HWfriendly');
ships.addClass('HWselectable');
var tooltip;
switch(parseInt(args.color)){
case 1:
tooltip = _('Click to give this ship capturing power');
break;
case 2:
tooltip = _('Click to give this ship movement power');
break;
case 3:
tooltip = _('Click to build another ship of this color');
break;
case 4:
tooltip = _('Click to trade this ship for another color');
break;
default:
console.error('Bad power number: '+args.color);
}
this.add_tooltip(
ships,
tooltip,
1500
);
var f = dojo.hitch(
this,
function(evt){
evt.preventDefault();
dojo.stopEvent(evt);
this.activate_ship(evt.currentTarget,args.color);
}
);
this.connect_nodes(ships,f);
},
onEntering_client_want_power: function(args){
if(!this.isCurrentPlayerActive())
return
var activatequery = dojo.query('[activate]');
var activatednode = activatequery[0];
// The system that the activated ship is in
var systemnode = this.get_system(activatednode);
// Candidates for activating technology
var candidates = dojo.query('.HWstar,.HWfriendly.HWship',systemnode);
candidates.addClass('HWselectable');
this.add_power_tooltips(candidates.concat(activatequery));
var f = dojo.hitch(
this,
function(evt){
evt.preventDefault();
dojo.stopEvent(evt);
var shipnode = evt.currentTarget;
var powernode = evt.currentTarget;
var color = this.get_color(powernode);
this.power_selected(color);
}
);
this.connect_nodes(candidates,f);
},
onEntering_want_restart_turn: function(args){
if(!this.isCurrentPlayerActive())
return
dojo.addClass('HWturn_token','HWonly_option');
},
// Set the function f to be called when any element of nodes is clicked
// f should accept a click event as a parameter
connect_nodes: function(nodes, f){
for(var i=0;i<nodes.length;i++)
this.connect(nodes[i],'onclick',f);
},
add_tooltip: function(nodes,tip,delay){
// Replacing addTooltipHtmlToClass which doesn't seem to delay
// when a text arg is missing
var node;
for(var i=0;i<nodes.length;i++){
node = nodes[i];
this.addTooltip(node.id,tip,'',delay);
}
},
add_power_tooltips: function(pieces){
var piece,color;
for(var i=0;i<pieces.length;i++){
piece = pieces[i];
color = this.get_color(piece);
switch(color){
case 1:
this.addTooltip(
piece.id,
_('Click to choose capturing power'),
'',1500
);
break;
case 2:
this.addTooltip(
piece.id,
_('Click to choose movement power'),
'',1500
);
break;
case 3:
this.addTooltip(
piece.id,
_('Click to choose build power and build a new ship in the color of the activated ship'),
'',1500
);
break;
case 4:
this.addTooltip(
piece.id,
_('Click to choose trade power'),
'',1500
);
break;
default:
console.error('Bad power number: '+color);
}
}
},
onEntering_client_want_target: function(args){
if(!this.isCurrentPlayerActive())
return
var activatednode = dojo.query('[activate]')[0];
var power = parseInt(activatednode.getAttribute('activate'));
var targets;
var tooltip;
switch(power){
case 1:
targets = this.power_targets(activatednode,power);
targets.addClass('HWselectable');
tooltip = _('Click this ship to capture it');
this.add_tooltip(targets,tooltip,1500);
break;
case 2:
var systemnode = this.get_system(activatednode);
var systems = this.connected_systems(systemnode);
tooltip = _('Click to move activated ship to this system');
this.add_tooltip(systems,tooltip,1500);
systems.addClass('HWselectable');
var stacks = this.connected_stacks(systemnode);
tooltip = _('Click to move activated ship to a new system with this star');
this.add_tooltip(stacks,tooltip,1500);
stacks.addClass('HWselectable');
break;
case 3:
//tooltip = '';
//this.add_tooltip(targets,tooltip,1500);
break;
case 4:
targets = this.power_targets(activatednode,power);
targets.addClass('HWselectable');
tooltip = _('Click to trade for a ship of this color');
this.add_tooltip(targets,tooltip,1500);
break;
default:
console.error('Bad power number: '+power);
}
this.connectClass('HWselectable','onclick','target_selected');
},
onEntering_client_want_catastrophe_target: function(args){
if(!this.isCurrentPlayerActive())
return
var overpopulated = this.get_overpopulated_pieces();
overpopulated.addClass('HWselectable HWoverpopulated');
this.add_tooltip(
overpopulated,
_('Click to destroy all pieces of this color in this system'),
1500
);
this.connectClass('HWselectable','onclick','catastrophe_target_selected');
},
power_targets: function(activatednode,power){
var systemnode = this.get_system(activatednode);
// Nodes to highlight
power = parseInt(power);
switch(power){
case 1:
return dojo.query('.HWhostile.HWship',systemnode);
case 2:
return this.connected_systems(systemnode).concat(
this.connected_stacks(systemnode));
case 3:
// Build target is selected automatically, so don't highlight anything
return dojo.NodeList();
case 4:
// TODO return candidates rather than highlighting manually
var targets = dojo.NodeList();
var old_color = this.get_color(activatednode);
var pips = this.get_size(activatednode);
var stack,children;
for(var i=1;i<=4;i++){
if(i==old_color)
continue;
stack = document.getElementById('HWstack_'+i+'_'+pips);
children = dojo.query('.HWbanked',stack);
if(children.length==0)
continue;
targets.push(stack);
}
return targets;
default:
console.error('Bad power number: '+power);
}
},
get_overpopulated_pieces: function(){
var systems = dojo.query('.HWsystem');
var targets = dojo.NodeList();
var system,i,j,color,result;
for(i=1;i<=4;i++){
color = '.HW'+this.color_names_eng[i];
for(j=0;j<systems.length;j++){
system = systems[j];
result = dojo.query(color,system);
if(result.length>=4){
targets = targets.concat(result);
}
}
}
return targets;
},
// onLeavingState:
// This method is called each time we are leaving a game state.
// You can use this method to perform user interface changes.
onLeavingState: function( state_name ) {
// Call appropriate method
var methodName = "onLeaving_" + state_name;
if (this[methodName] !== undefined)
this[methodName]();
},
onLeaving_client_want_creation_confirmation: function(){
if(!this.isCurrentPlayerActive())
return
this.deselect_all();
dojo.removeClass('HWturn_token','HWonly_option');
},
onLeaving_client_want_creation_ship: function(){
if(!this.isCurrentPlayerActive())
return
this.deselect_all();
},
onLeaving_want_free: function(){
if(!this.isCurrentPlayerActive())
return
this.deselect_all();
},
onLeaving_want_sacrifice_action: function(){
if(!this.isCurrentPlayerActive())
return
this.deselect_all();
},
onLeaving_client_want_power: function(){
if(!this.isCurrentPlayerActive())
return
this.deselect_all();
},
onLeaving_client_want_target: function(){
if(!this.isCurrentPlayerActive())
return
this.deselect_all();
this.deactivate_all();
},
onLeaving_client_want_catastrophe_target: function(args){
if(!this.isCurrentPlayerActive())
return
this.deselect_all();
var selectable = dojo.query('.HWoverpopulated');
selectable.removeClass('HWoverpopulated')
},
onLeaving_want_restart_turn: function(){
if(!this.isCurrentPlayerActive())
return
this.deselect_all();
dojo.removeClass('HWturn_token','HWonly_option');
},
// onUpdateActionButtons:
// in this method you can manage "action buttons" that are displayed in the
// action status bar (ie: the HTML links in the status bar).
// This function gets called just before onEnteringState with the same parameters.
onUpdateActionButtons: function( state_name, args ) {
// Only active players get buttons
if(!this.isCurrentPlayerActive())
return;
// Only choice states get buttons
if(!state_name.startsWith('want') && !state_name.startsWith('client'))
return;
// Set default pass button params
// These will be changed if passing is not expected,
// i.e., if there are things the player could still do
var pass_button_message = _('End turn');
var pass_button_color = 'blue';
switch(state_name){
// Server choice states get catastrophe button
case 'want_free':
case 'want_sacrifice_action':
case 'want_catastrophe':
// This needs to be checked in free and sacrifice action cases
if(this.get_overpopulated_pieces().length > 0){
this.addActionButton(
'catastrophe_button',
_('Trigger catastrophe'),
'catastrophe_button_selected'
);
}
// In these states, there are still actions available
pass_button_message = _('Pass');
pass_button_color = 'red'
// NO BREAK
// The above states get pass, draw, and restart buttons
case 'want_restart_turn':
this.addActionButton(
'pass_button',
pass_button_message,
function(evt){
this.pass_button_selected(state_name);
},
null, // destination (deprecated)
null, // blinking (default false)
pass_button_color
);
// Token needs to be selectable when pass button is available
this.selectablize_token(state_name);
this.setup_draw_button(args);
this.addActionButton(
'restart_button',
_('Restart turn'),
function(evt){
this.restart_button_selected();
}
);
break;
case 'client_want_power':
this.addActionButton(
'sacrifice_button',
_('Sacrifice ship'),
'sacrifice_button_selected'
);
// NO BREAK
// The client_want_power state gets both
// a sacrifice and cancel button
case 'client_want_catastrophe_target':
case 'client_want_target':
this.addActionButton(
'cancel_button',
_('Cancel'),
function(evt){
this.cancel_action();
}
);
break;
case 'client_want_creation_confirmation':
this.addActionButton(
'confirm_button',
_('End turn'),
function(evt){
this.finalize_creation();
}
);
case 'want_creation':
case 'client_want_creation_ship':
this.addActionButton(
'restart_button',
_('Restart turn'),
function(evt){
this.restart_creation();
}
);
this.selectablize_token(state_name);
break;
}
},
setup_draw_button: function(args){
if(args.draw_offerer == 0){
// No one has offered a draw yet
this.addActionButton(
'draw_button',
_('Offer draw'),
'draw_button_selected'
);
}
else if(args.draw_offerer == this.player_id){
// This player has already offered a draw
this.addActionButton(
'cancel_draw_button',
_('Cancel draw offer'),
'cancel_draw_button_selected'
);
}
else{
// The other player offered a draw
this.addActionButton(
'draw_button',
_('Accept draw and end game'),
'draw_button_selected'
);
}
},
///////////////////////////////////////////////////
//// Utility methods
get_color: function(piecenode){
return parseInt(piecenode.getAttribute('ptype').split('_')[0]);
},
get_size: function(piecenode){
return parseInt(piecenode.getAttribute('ptype').split('_')[1]);
},
get_id: function(piecenode){
return parseInt(piecenode.id.split('_')[1]);
},
get_system: function(piecenode){
// Get the system node containing this piece
var par = piecenode;
while(!dojo.hasClass(par,'HWsystem')){
//while(!par.id.startsWith('HWsystem')){
par = par.parentNode;
if(par === undefined || par.id === undefined){
this.showMessage( _('Piece is not in a system.'), 'error');
return null;
}
}
return par;
},
get_bad_home_warning: function(){
// Warn the player if they don't have green, blue, and a large ship
var systemnode = dojo.query('[homeplayer_id=player_'+this.player_id+']')[0];
var blues = dojo.query('.HWblue',systemnode);
var greens = dojo.query('.HWgreen',systemnode);
var large_ships = dojo.query('.HWlarge.HWship',systemnode);
var stars = dojo.query('.HWstar',systemnode);
var star_match = this.get_color(stars[0]) == this.get_color(stars[1]);
var gemini = this.get_size (stars[0]) == this.get_size (stars[1]);
var message = '';
if(star_match)
message += ' '+_('Your stars are the same color and will be very vulnerable to catastrophe.');
if(large_ships.length == 0)
message += ' '+_('You do not have a large ship and will be vulnerable to direct assault.');
if(greens.length == 0)
message += ' '+_('You do not have a green piece and cannot build.');
if(blues.length == 0)
message += ' '+_('You do not have a blue piece and cannot diversify.');
if(gemini)
message += ' '+_('Your stars are the same size and your home will be connected to more systems, which may be confusing.');
if(message.length > 0){
// At least one problem was detected
message =
'<span style="color:red">'
+ _('WARNING: Your homeworld has the following problems:')
+ '</span>'
+ message
+ ' <span style="color:red">'
+ _('You should restart your turn unless this was deliberate.')
+ '</span>';
}
//this.confirmationDialog(message);
//this.multipleChoiceDialog(message,['OK'],()=>{});
return message;
},
// Set up the global variable this.colony_assignments
setup_colony_assignments: function(){
var player_id_top = this.get_top_player();
var player_id_bot = this.get_bot_player();
var home_top = dojo.query('[homeplayer_id=player_'+player_id_top+']');
var home_bot = dojo.query('[homeplayer_id=player_'+player_id_bot+']');
if(home_top.length == 0 || home_bot.length == 0){
// Creation is not finished
return;
}
var top_stars = dojo.query('.HWstar',home_top[0]);
var bot_stars = dojo.query('.HWstar',home_bot[0]);
var all_stars = {1:top_stars,2:bot_stars};
/*
groupings[0]: an array of the sizes of colony stars that are connected to neither homeworld
groupings[1]: star sizes that are connected only the home of the player displayed at the top
groupings[2]: only to the home of the player displayed at the bottom
groupings[3]: to both
*/
var groupings = [[],[],[],[]];
var pips;
var groupi,group,connects,i,stars,star,home_num;
for(pips=1;pips<=3;pips++){
// groupi will match the index in groupings
groupi = 0;
// For each of the two homes, 1 for top and 2 for bot
for(home_num=1;home_num<=2;home_num++){
stars = all_stars[home_num];
// Check if a star of size pips connects to these stars
connects = 1;
for(i=0;i<stars.length;i++){
star = stars[i];
if(pips == this.get_size(star)){
connects = 0;
break;
}
}
if(connects){
groupi += home_num;
}
}
groupings[groupi].push(pips);
}
var adjacent_row;
// Handle "both" and "neither" groups
var groups = [0,3];
for(i in groups){
groupi = groups[i];
group = groupings[groupi];
if(group.length == 0)
continue;
// If there is exactly one star size that connects to neither home,
// (likewise to both homes)
// it makes sense to put that size in the middle
// (The weird case is when there's exactly one in the "neither" category
// and exactly one in the "both" category")
if(group.length == 1){
this.colony_assignments[group[0]] = 2;
if(groupi==0 && groupings[3].length==1){
// Here's the weird case:
// put the "neither" in the middle
// and "both" by the less-connected home,
var both = groupings[3][0];
var less_connected;
if(groupings[1].length==1)
less_connected = 2;
else
less_connected = 1;
// Colony row that's
adjacent_row = 2*less_connected-1;
this.colony_assignments[both] = adjacent_row;
// The lower loop about singly-connected stars
// Can work out the more-connected system
break;
}
}
else{
this.colony_assignments[group[0]] = 1;
this.colony_assignments[group[1]] = 3;
}
}
// Handle "top only" and "bot only" groups
groups = [1,2];
for(i in groups){
groupi = groups[i];
group = groupings[groupi];
if(group.length == 0)
continue;
adjacent_row = 2*groupi-1;
// If there is any star size that connects to only one home,
// it makes sense to put that one such size next to that home.
this.colony_assignments[group[0]] = adjacent_row;
// If there's another size that connects to only that home,
// then it goes in the middle
if(group.length > 1)
this.colony_assignments[group[1]] = 2;
}
},
// Remember server state for easy partial action canceling
set_turn_checkpoint: function(args,state_name){
// args needs to be deeply copied because
// it appears to be overwritten on state change
//this['latest_args'] = this.deepcopy(args);
this['latest_args'] = {
state_name: state_name,
descriptionmyturn: args.descriptionmyturn,
args: args.args
};
},
deepcopy: function(x){
// Not fast, but easy to write
return JSON.parse(JSON.stringify(x));
},
/*
Return a piecenode in this stack node
The piece is NOT removed from the stack
For consistency, the highest-index piece is returned
(this can prevent soft-lock during tutorials).
*/
get_piece_in_stack: function(stacknode){
var children = stacknode.children;
var hi = -1;
var piecenode = null;
var child,pid;
for(var i=0;i<children.length;++i){
child = children[i];
pid = this.get_id(child);
if(pid>hi){
hi = pid;
piecenode = child;
}
}
return piecenode;
},
put_in_bank: function(piecenode){
var ani_origin = this.place_animation_marker(piecenode,true);
var systemnode = this.get_system(piecenode);
dojo.removeClass(piecenode,'HWfriendly HWhostile HWstar HWship HWoverpopulated');
piecenode.removeAttribute('activate');
dojo.addClass(piecenode,'HWbanked');
var color = this.get_color(piecenode);
var pips = this.get_size(piecenode);
var stacknode = document.getElementById('HWstack_'+color+'_'+pips);
dojo.place(piecenode,stacknode,'first');
// TODO be smarter about when this is done
this.on_system_change(systemnode);
var ani_target = this.place_animation_marker(piecenode,false);
this.slide_between(piecenode,ani_origin,ani_target);
},
// Make a system at setup from JSON object (creating new pieces)
setup_system: function(system){
var star_size = null;
if(system.homeplayer_id == null){
// This is a colony, so find its star size
for(star_id in system.stars){
star_size = system.stars[star_id].pips;
break;
}
}
var systemnode = this.place_system(
system.system_id,
system.system_name,
system.homeplayer_id,
star_size
);
var ship_id,star_id;
// player ID of the player whose ships should point north
var friendly_id = this.get_bot_player();
// Add ships
for(ship_id in system.ships){
ship = system.ships[ship_id];
if(friendly_id == ship.owner_id)
this.setup_piece(ship,'HWfriendly HWship',systemnode);
else
this.setup_piece(ship,'HWhostile HWship',systemnode);
}
// Add stars
var starcontainer = dojo.query('.HWstar_container',systemnode)[0];
for(star_id in system.stars){
star = system.stars[star_id];
this.setup_piece(star,'HWstar',starcontainer);
}
this.on_system_change(systemnode);
},
setup_piece: function(piece,more_classes,container){
var params = {
piece_id : piece.piece_id,
colorname : this.color_names_eng[piece.color],
pipsname : this.size_names_eng[piece.pips],
colornum : piece.color,
pipsnum : piece.pips,
more_classes : more_classes
};
var piece_html = this.format_block('jstpl_piece',params);
dojo.place(piece_html,container);
},
ajaxcallwrapper: function(action, args, handler) {
// this allows to skip args parameter for action which do not require them
if (!args)
args = [];
// Avoid rapid clicking problems
args.lock = true;
// Check that player is active and action is declared
if (this.checkAction(action)) {
// this is mandatory fluff
this.ajaxcall(
"/" + this.game_name + "/" + this.game_name + "/" + action + ".html",
args,
this,
// Success result handler is empty - it is seldom needed
(result) => {},
// The real result handler is called both on success and error
// The optional param "is_error" is seldom needed
handler
);
}
},
/*
Create and return an un-displayed node that is in the location of the given node.
The given node can then be moved in the DOM tree and then animated from
the un-displayed node to its new location
If old is set to true, piecenode is going to be taken from the DOM tree,
so the marker needs to save the spot in the DOM tree.
If old is false, the piecenode is already in the new place in the DOM tree,
so the marker needs to save the new display location and its place in the DOM tree doesn't matter.
The markers should be destroyed when unneeded to avoid (small) memory leaks.
Destruction will be performed by slide_between if marker is passed
*/
place_animation_marker: function(piecenode,old=true){
var html = "<div class='HWanimarker' id='"+piecenode.id+old+"'></div>";
var marker = dojo.place(html,'HWboard');
// Get the current style including CSS stuff
//var style = getComputedStyle(piecenode);
// Give the same margins to marker
//console.log('margin style:',style.margin);
//dojo.setStyle(marker,'margin',style.margin);
//dojo.setStyle(marker,'height',style.height);
//dojo.setStyle(marker,'width',style.width);
if(!old){
// The node is in its new position now. Just save it.
this.placeOnObject(marker,piecenode);
return marker;
}
// The node is in its old position.
// Put the marker next to it in the DOM tree
// so the marker will move correspondingly if elements shift
// when the node changes in the tree.
if(piecenode.id=='HWturn_token' || dojo.hasClass(piecenode,'HWbanked')){
this.placeOnObject(marker,piecenode.parentNode);
}
else if(dojo.hasClass(piecenode,'HWstar')){
dojo.place(marker,piecenode,'after');
}
else if(dojo.hasClass(piecenode,'HWfriendly')){
dojo.addClass(marker,'HWfriendly');
dojo.place(marker,piecenode,'after');
}
else if(dojo.hasClass(piecenode,'HWhostile')){
dojo.addClass(marker,'HWhostile');
dojo.place(marker,piecenode,'after');
}
else{
this.showMessage(
'Attempting unknown animation.',
'error'
);
}
return marker;
},
/*
Run an animation moving node from origin to target (all nodes)
The node should already be in the desired place in the DOM tree
origin and target nodes will be deleted when animation is complete
*/
slide_between: function(node,origin,target,delay=0,remove_markers=true){
var t = 400;
var delay_html = "<div id='HWdelayer"+node.id+"' style='display:none'></div>";
var delayer = dojo.place(delay_html,'HWboard');
dojo.addClass(node,'HWsliding');
this.placeOnObject(node,origin);
var animation_slide = this.slideToObject(node.id,target.id,t,delay);
var animation_delay = this.slideToObject(delayer.id,delayer.id,0,delay+t+500);
dojo.connect(
animation_delay,
'onEnd',
function(){
// Animation callbacks appear to be called too early.
// Applying this callback to the animation itself
// seems to make the animation jump at the end.
dojo.removeAttr(node,'style');
dojo.removeClass(node,'HWsliding');
delayer.remove();
if(remove_markers){
origin.remove();
target.remove();
}
}
);
var ani = dojo.fx.combine([animation_slide,animation_delay]);
ani.play();
},
/*
Place a ship in a system and update classes as appropriate
piecenode: the piece node that should be placed as a ship
targetnode: the node where piecenode should be placed
If this is a system, piecenode will become a child of targetnode
If this is a ship, piecenode will be placed before targetnode as a sibling
(this parameter is not used if neighbor is provided)
(if neighbor is not provided, then systemnode must be)
owner_id: the ID of the player who should own the ship