-
Notifications
You must be signed in to change notification settings - Fork 0
/
calypso.game.php
1739 lines (1544 loc) · 70.6 KB
/
calypso.game.php
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
<?php
/**
*------
* BGA framework: © Gregory Isabelli <[email protected]> & Emmanuel Colin <[email protected]>
* Calypso implementation : © Andy Bond <[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.
* -----
*
* calypso.game.php
*
* This is the main file for your game logic.
*
*/
require_once( APP_GAMEMODULE_PATH.'module/table/table.game.php' );
class Calypso extends Table
{
// Trick-winning method constants
const TRUMP_LEAD = 1;
const FIRST_TRUMP = 2;
const OVERTRUMP = 3;
const PLAINSUIT = 4;
const SUIT_LOOKUP = array(
1 => '<span class="clp-suit-text-spades clp-suit-text">♠</span>',
2 => '<span class="clp-suit-text-hearts clp-suit-text">♥</span>',
3 => '<span class="clp-suit-text-clubs clp-suit-text">♣</span>',
4 => '<span class="clp-suit-text-diamonds clp-suit-text">♦</span>',
);
const SPADES = 1;
const HEARTS = 2;
const CLUBS = 3;
const DIAMONDS = 4;
// game option stuff - see gameoptions.inc.php
const DETAILED_LOG_ON = 1;
function __construct( )
{
// You can use any number of global variables with IDs between 10 and 99.
// If your game has options (variants), you also have to associate here a label to
// the corresponding ID in gameoptions.inc.php.
parent::__construct();
self::initGameStateLabels( array(
// who dealt first this round
"firstHandDealer" => 10,
// who dealt this hand
"currentDealer" => 11,
// suit lead
"trickSuit" => 21,
// who's winning trick so far and with what
"currentTrickWinner" => 22,
"bestCardSuit" => 23,
"bestCardRank" => 24,
// did the lead player lead their personal trump?
"trumpLead" => 25,
// has someone trumped in?
"trumpPlayed" => 26,
// track method of current trick winner
// 1=trump_lead, 2=first_trump, 3=overtrump, 4=plainsuit, see constants above
"winningMethod" => 27,
// what round are we on, and which hand in the round?
"roundNumber" => 31,
"handNumber" => 32,
// trick number as well, as convenient for stats/progression
"trickNumber" => 33,
// gameoptions - see gameoptions.inc.php
// how many rounds we play to
"totalRounds" => 100,
// are renounce indicators on or off?
"renounceFlags" => 101,
// how do we pair players for partnerships?
"partnerships" => 102,
// detailed log option
"detailedLog" => 103,
) );
$this->cards = self::getNew( "module.common.deck" );
$this->cards->init( "card" ); // db table initialisation
}
protected function getGameName( )
{
// Used for translations and stuff. Please do not modify.
return "calypso";
}
/*
setupNewGame:
This method is called only once, when a new game is launched.
In this method, you must setup the game according to the game rules, so that
the game is ready to be played.
*/
protected function setupNewGame( $players, $options = array() )
{
// set colours - see gameinfos.inc.php for values that can exist
$gameinfos = self::getGameinfos();
$default_colors = $gameinfos['player_colors'];
// choose some player randomly to be first dealer
$first_dealer_order_number = bga_rand(1, 4);
// Set up personal trump suits
// Randomly choose suit for first player, then randomly one of the other two available for next
// the rest are then determined
$first_player_suit = bga_rand(1, 4);
// second players suit will be randomly selected from the opposite partnership - (spades/hearts vs clubs/diamonds)
$second_player_suit = ($first_player_suit <= 2) ? bga_rand(3, 4) : bga_rand(1, 2);
// choose first player randomly
// use partnership option + player_table_no to decide mapping to these
// 4 will be dealer, 2 their partner, then 1 and 3 the other partnership
$player_suits = array(
1 => $first_player_suit,
2 => $second_player_suit,
3 => self::getPartnerSuit($first_player_suit),
4 => self::getPartnerSuit($second_player_suit)
);
// normalise player_table_order to be 1-4:
$player_table_orders = array_map(
function($player){return $player['player_table_order'];},
$players
);
// sort by values, keeping key associations intact
asort($player_table_orders);
$player_table_orders = array_combine(array_keys($player_table_orders), array(1, 2, 3, 4));
$first_dealer_id = array_search($first_dealer_order_number, $player_table_orders);
self::setGameStateInitialValue( 'firstHandDealer', $first_dealer_id );
self::setGameStateInitialValue( 'currentDealer', $first_dealer_id );
// set up partnerships
$player_orders = array(1, 2, 3, 4);
switch(self::getGameStateValue('partnerships')){
// 1,3 vs 2,4
case 1:
// default, as above
break;
// 1,2 vs 3,4
case 2:
$player_orders = array(1, 3, 2, 4);
break;
// 1,4 vs 2,3
case 3:
$player_orders = array(1, 2, 4, 3);
break;
// just random
case 4:
shuffle($player_orders);
break;
}
// and rotate so that dealer is last
$dealer = $player_orders[$first_dealer_order_number - 1];
while($dealer != 4){
// move everyone round the table
$player_orders = array_map(
function($order){return ($order % 4) + 1;},
$player_orders
);
$dealer = $player_orders[$first_dealer_order_number - 1];
}
$new_order_index = array_combine(array(1, 2, 3, 4), $player_orders);
$sql = "INSERT INTO player
(player_id, player_color, player_canal, player_name, player_avatar, player_no, trump_suit)
VALUES ";
$values = array();
foreach( $players as $player_id => $player ) {
$order = $new_order_index[$player_table_orders[$player_id]];
$suit = $player_suits[$order];
$color = array_shift( $default_colors );
$values[] = "('".$player_id."','$color','".$player['player_canal']."','".addslashes( $player['player_name'] ).
"','".addslashes( $player['player_avatar'] )."','".addslashes( $order ).
"','".addslashes( $suit )."')";
}
$sql .= implode( ',', $values);
self::DbQuery( $sql );
self::reattributeColorsBasedOnPreferences( $players, $gameinfos['player_colors'] );
/************ Start the game initialization *****/
// pre-game value
self::setGameStateInitialValue( 'roundNumber', 0 );
self::setGameStateInitialValue( 'trickNumber', 0 );
// Create 4 identiical decks of cards
// see material.inc.php to confirm the labelling
$num_decks = 4;
$cards = array();
foreach ( $this->suits as $suit_id => $suit ) {
// spade, heart, club, diamond
for ($rank = 2; $rank <= 14; $rank++) {
// 2, 3, 4, ... K, A
$cards[] = array ('type' => $suit_id, 'type_arg' => $rank, 'nbr' => $num_decks );
}
}
$this->cards->createCards( $cards, 'deck' );
// Init game statistics - see stats.inc.php
self::initStat('table', 'average_calypsos_per_round', 0);
self::initStat('table', 'average_points_per_round', 0);
self::initStat('table', 'proportion_tricks_won_trump_lead', 0);
self::initStat('table', 'proportion_tricks_won_first_trump', 0);
self::initStat('table', 'proportion_tricks_won_overtrump', 0);
self::initStat('table', 'proportion_tricks_won_plainsuit', 0);
self::initStat('player', 'calypsos_per_round', 0);
self::initStat('player', 'partnership_calypsos_per_round', 0);
self::initStat('player', 'calypso_points_per_round', 0);
self::initStat('player', 'partnership_calypso_points_per_round', 0);
self::initStat('player', 'incomplete_calypso_cards_per_round', 0);
self::initStat('player', 'partnership_incomplete_calypso_cards_per_round', 0);
self::initStat('player', 'trickpile_cards_per_round', 0);
self::initStat('player', 'partnership_trickpile_cards_per_round', 0);
self::initStat('player', 'points_per_round', 0);
self::initStat('player', 'partnership_points_per_round', 0);
self::initStat('player', 'personal_trumps_per_hand', 0);
self::initStat('player', 'partner_trumps_per_hand', 0);
self::initStat('player', 'opponent_trumps_per_hand', 0);
self::initStat('player', 'tricks_won_total_per_hand', 0);
self::initStat('player', 'tricks_won_trump_lead_per_hand', 0);
self::initStat('player', 'tricks_won_first_trump_per_hand', 0);
self::initStat('player', 'tricks_won_overtrump_per_hand', 0);
self::reloadPlayersBasicInfos();
$this->activeNextPlayer();
/************ End of the game initialization *****/
}
/*
getAllDatas:
Gather all informations about current game situation (visible by the current player).
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)
*/
protected function getAllDatas()
{
$result = array();
$current_player_id = self::getCurrentPlayerId();
$sql = "SELECT player_id id, player_score score, trump_suit trump_suit, ".
"completed_calypsos completed_calypsos FROM player;";
$result['players'] = self::getCollectionFromDb( $sql );
foreach($result['players'] as $player_id => $info){
// hide actual number in pile, just for display of backs or not
// as all of this info is potentially public (arrives client side on load)
$result['players'][$player_id]['trick_pile'] = self::getTrickPile($player_id) > 0 ? 1 : 0;
$result['players'][$player_id]['player_name'] = self::getPlayerName($player_id);
}
$result['hand'] = $this->cards->getCardsInLocation( 'hand', $current_player_id );
if (!self::isSpectator()){
$player_suit = self::getPlayerSuit($current_player_id);
$partner_suit = self::getPartnerSuit($player_suit);
// give suits in order: player suit, partner suit,
// same colour as player, same colour as partner
$result['suits_by_status'] = array(
+$player_suit,
$partner_suit,
self::getSameColourSuit($player_suit),
self::getSameColourSuit($partner_suit),
);
} else {
// dummy ranking to keep nice and smooth
$result['suits_by_status'] = array(
self::CLUBS,
self::DIAMONDS,
self::HEARTS,
self::SPADES,
);
}
$result['cardsontable'] = $this->cards->getCardsInLocation( 'cardsontable' );
$result['cardsincalypsos'] = $this->cards->getCardsInLocation( 'calypso' );
$result["playable_cards"] = self::getValidCards($current_player_id);
$result['dealer'] = self::getGameStateValue('currentDealer');
$result['handnumber'] = self::getGameStateValue('handNumber');
$result['roundnumber'] = self::getGameStateValue('roundNumber');
$result['totalrounds'] = self::getGameStateValue('totalRounds');
$result['roundscoretable'] = array();
for($round = 1; $round <= $result['roundnumber']; $round++){
$args_array = self::getDisplayScoresArgs($round);
$result['roundscoretable'][$round] = $args_array["score_table"];
}
$result['overallscoretable'] = self::getDisplayOverallScoresArgs();
// N.B. we automatically send over game state anyhow, so need to set that here
if(self::getGameStateValue('renounceFlags') == 1){
$sql = "SELECT rf.renounce_id id, rf.suit suit, rf.player_id player_id, ".
"player.player_name player_name, player.trump_suit trump_suit ".
"FROM renounce_flags rf ".
"LEFT JOIN player ON rf.player_id = player.player_id;";
$player_flags = array();
$renounce_flag_info = self::getCollectionFromDb( $sql );
foreach ($renounce_flag_info as $id => $info) {
$player_flags[] = $info;
}
$result['renounce_flags'] = $player_flags;
// not elegant, but does okay
$result['renounce_flags_on'] = "on";
} else{
$result['renounce_flags_on'] = "off";
}
return $result;
}
/*
getGameProgression:
Compute and return the current game progression.
The number returned must be an integer beween 0 (=the game just started) and
100 (= the game is finished or almost finished).
This method is called each time we are in a game state with the "updateGameProgression" property set to true
(see states.inc.php)
*/
function getGameProgression()
{
$total_rounds = self::getGameStateValue('totalRounds');
$tricks_completed = self::getTrickNumber() - 1;
return round(100.0*$tricks_completed/(13*4*$total_rounds));
}
//////////////////////////////////////////////////////////////////////////////
//////////// Utility functions
////////////
/*
In this space, you can put any utility methods useful for your game logic
*/
function getPartnerSuit($player_suit) {
return array(
self::CLUBS => self::DIAMONDS,
self::DIAMONDS => self::CLUBS,
self::HEARTS => self::SPADES,
self::SPADES => self::HEARTS,
)[$player_suit];
}
// get suit the same colour as a given suit - feeds through to UI
function getSameColourSuit($player_suit) {
return array(
self::CLUBS => self::SPADES,
self::DIAMONDS => self::HEARTS,
self::HEARTS => self::DIAMONDS,
self::SPADES => self::CLUBS,
)[$player_suit];
}
function getPlayerSuit($player_id) {
$sql = "SELECT player_id, trump_suit FROM player WHERE player_id=".$player_id.";";
$query_result = self::getCollectionFromDB( $sql, true );
return $query_result[$player_id];
}
function getPlayerIDFromSuit($suit){
$sql = "SELECT trump_suit, player_id FROM player WHERE trump_suit=".$suit.";";
$query_result = self::getCollectionFromDB( $sql, true );
return $query_result[$suit];
}
function getPartnerID($player_id){
return self::getAdjacentPlayer($player_id, 2);
}
// get the player number relative to the round - for stats
function getRoundPlayerNumber($player_id){
$first_hand_dealer_id = self::getGameStateValue("firstHandDealer");
if($first_hand_dealer_id == $player_id){
return 4;
}
$position_id = $first_hand_dealer_id;
$position = 4;
while($position_id != $player_id){
$position_id = self::getAdjacentPlayer($position_id);
$position = ($position % 4) + 1;
}
return $position;
}
function getPlayerName($player_id){
$players = self::loadPlayersBasicInfos();
return $players[$player_id]["player_name"];
}
function loadPlayersBasicInfosWithTrumps() {
// loadPlayersBasicInfos + trump_suit
$players = self::loadPlayersBasicInfos();
foreach ( $players as $player_id => $player_info ) {
$player_info["player_trump"] = self::getPlayerSuit($player_id);
}
return $players;
}
function getPlayerPartnership($player_id) {
// use bridge terminology
// 3, 4 is clubs, diamonds -> 'minor' suits
$player_suit = self::getPlayerSuit($player_id);
if(in_array($player_suit, array(self::CLUBS, self::DIAMONDS))){
return 'minor';
}
return 'major';
}
function getPartnershipPlayers($partnership){
if($partnership == 'minor'){
return array(
self::getPlayerIDFromSuit(self::CLUBS),
self::getPlayerIDFromSuit(self::DIAMONDS)
);
}
return array(
self::getPlayerIDFromSuit(self::SPADES),
self::getPlayerIDFromSuit(self::HEARTS)
);
}
// next player clockwise pass 1, -1 for anti-clockwise (i.e. previous player)
// this is where order is canonically set in-game!
function getAdjacentPlayer($existing_player_id, $direction_index=1){
$players = self::loadPlayersBasicInfos();
$existing_player_number = $players[$existing_player_id]["player_no"];
foreach ( $players as $player_id => $player ) {
// maybe a pithier way to do this modular arithmetic and get a number in range 1-4
// but this is clear enough
$new_player_number = ($existing_player_number + $direction_index) % 4;
$new_player_number = ($new_player_number == 0) ? 4 : $new_player_number;
if($new_player_number == $player["player_no"]){
return $player_id;
}
}
}
function getPlayerDirections(){
// straight from the php docs - native function in php8+
// had to rename this as it clashes in production
function array_key_first_homebrew(array $arr) {
foreach($arr as $key => $unused) {
return $key;
}
return NULL;
}
$players = self::loadPlayersBasicInfos();
$south_id = self::getCurrentPlayerId();
// if we are a spectator, just pick the first player as south
if(!array_key_exists($south_id, $players)){
$south_id = array_key_first_homebrew($players);
}
$west_id = self::getAdjacentPlayer($south_id);
$north_id = self::getAdjacentPlayer($west_id);
$east_id = self::getAdjacentPlayer($north_id);
$directions = array(
$south_id => "S",
$west_id => "W",
$north_id => "N",
$east_id => "E",
);
return $directions;
}
// actively changing dealer, either the real dealer, or the labelled first-hand dealer
function updateDealer($direction_index=1, $relevant_dealer='currentDealer') {
$current_dealer = self::getGameStateValue($relevant_dealer);
$new_dealer = self::getAdjacentPlayer($current_dealer, $direction_index);
$first_leader = self::getAdjacentPlayer($new_dealer);
$this->gamestate->changeActivePlayer( $first_leader );
// actually set the value!
self::setGameStateValue($relevant_dealer, $new_dealer);
return $new_dealer;
}
function setNextFirstDealer() {
// hop back in other direction for first hand dealer
$next_first_dealer = self::updateDealer($direction_index=-1, $relevant_dealer='firstHandDealer');
return $next_first_dealer;
}
function setRenounceFlag($player_id, $suit){
$sql = "INSERT INTO renounce_flags (player_id, suit) VALUES (".$player_id.",".$suit.");";
self::DbQuery(
$sql
);
}
function clearRenounceFlags(){
$sql = "DELETE FROM renounce_flags;";
self::DbQuery(
$sql
);
}
function getAllCompletedCalypsos(){
$self = $this;
$partnership_order = function($player_1, $player_2) use ($self){
return $this::getPlayerPartnership($player_1) == "minor"? -1 : 1;
};
$sql = "SELECT player_id id, completed_calypsos num_calypsos FROM player";
$player_calypsos = self::getCollectionFromDB( $sql, true );
uksort($player_calypsos, $partnership_order);
return $player_calypsos;
}
function processCompletedTrick() {
$best_value_player_id = self::getGameStateValue( 'currentTrickWinner' );
$winning_method = self::getGameStateValue('winningMethod');
self::updateWinnerMethodCount($best_value_player_id, $winning_method);
// announce who won first, then deal with the admin of what happens to the cards
self::notifyAllPlayers(
'trickWin',
clienttranslate('${player_name} wins the trick'),
array(
'player_id' => $best_value_player_id,
'player_name' => self::getPlayerName($best_value_player_id)
)
);
// card gathering logic:
// $moved_to will track where cards go, so we can send that to js
// get all cards on table
$cards_played = $this->cards->getCardsInLocation( 'cardsontable' );
// move any cards to calypsos there's room for, and get rid of opponents' cards
$moved_to_first_batch = self::sortWonCards($cards_played, $best_value_player_id);
// check if any calypsos are completed, and if so process (remove cards, update db)
$calypsos_completed = self::processCalypsos();
// now check if remaining cards can be added to calypsos
$remaining_cards = $this->cards->getCardsInLocation( 'cardsontable' );
$moved_to_second_batch = self::sortWonCards($remaining_cards, $best_value_player_id);
$moved_to = array_merge($moved_to_first_batch, $moved_to_second_batch);
// any cards still on the table should be duplicates of calypso cards
// note that fact for animation, then give them to the trick winner
$still_remaining_cards = $this->cards->getCardsInLocation( 'cardsontable' );
foreach($still_remaining_cards as $card){
$moved_to[$card["location_arg"]] = array(
"owner" => 0,
"winner" => $best_value_player_id,
"originating_player" => $card["location_arg"],
);
}
$this->cards->moveAllCardsInLocation('cardsontable', 'trickpile', null, $best_value_player_id);
// we construct the animations on the client-side in three steps:
// move to the winner's space
// move from there to where they end up
// then any completed calypsos get tidied up to the relevant calypso pile
// now we move cards where they need to go, and get next player
self::notifyAllPlayers( 'moveCardsToWinner','', array(
'winner_id' => $best_value_player_id,
) );
// first we compute cards going to the next calypso so we can use it in notif
// this will hold player_id => (cards going to the next calypso), if any
$all_fresh_cards = array( );
if(!empty($calypsos_completed)){
foreach($calypsos_completed as $player_id){
# get only those cards for the relevant calypso
// i.e. (cards going to the next calypso)
$fresh_cards = array_filter(
$moved_to_second_batch,
function($card) use ($player_id){
return $card['owner'] == $player_id;
}
);
$all_fresh_cards[$player_id] = $fresh_cards;
}
};
self::notifyAllPlayers( 'moveCardsToCalypsos','', array(
'player_id' => $best_value_player_id,
// this tells us where all the cards will end up
'moved_to' => $moved_to,
// we need info on any completed calypsos + extra cards if so
// so we know which cards will stay in calypso layout
'extras_to_calypso' => $all_fresh_cards,
'calypsos_completed' => $calypsos_completed,
) );
if(!empty($calypsos_completed)){
// this is updated with latest figures already
$total_calypso_counts = self::getAllCompletedCalypsos();
foreach($calypsos_completed as $player_id){
self::updateFastestCalypso($player_id);
self::notifyAllPlayers(
'calypsoComplete',
clienttranslate('${player_name} completes a calypso'),
array(
'player_id' => $player_id,
'player_name' => self::getPlayerName($player_id),
'player_suit' => self::getPlayerSuit($player_id),
'num_calypsos' => $total_calypso_counts[$player_id],
'cards_to_fresh_calypso' => $all_fresh_cards[$player_id],
'dummy' => $moved_to_second_batch,
)
);
}
}
// now that the animations are all constructed we send the go-ahead to play them (in sequence)
self::notifyAllPlayers(
'playAllAnimations',
'',
array(),
);
$this->gamestate->changeActivePlayer( $best_value_player_id );
self::giveExtraTime($best_value_player_id);
}
function initialiseTrick(){
// Set current trick suit to zero (= no trick suit)
self::setGameStateInitialValue( 'trickSuit', 0 );
// No current winner yet
self::setGameStateInitialValue( 'currentTrickWinner', 0 );
// Trump has not been lead yet
self::setGameStateInitialValue( 'trumpLead', 0 );
// and no-one has trumped in yet
self::setGameStateInitialValue( 'trumpPlayed', 0 );
// no winning card currently
self::setGameStateInitialValue( 'bestCardSuit', 0 );
self::setGameStateInitialValue( 'bestCardRank', 0 );
// no current winner, so no associated method
self::setGameStateValue( 'winningMethod', 0 );
}
function setWinner( $best_player_id, $best_card, $method ){
self::setGameStateValue( 'currentTrickWinner', $best_player_id );
self::setGameStateValue( 'bestCardSuit', $best_card['type'] );
self::setGameStateValue( 'bestCardRank', $best_card['type_arg'] );
self::setGameStateValue( 'winningMethod', $method );
}
function updateWinnerMethodCount($trick_winner_id, $winning_method){
switch($winning_method){
case self::TRUMP_LEAD:
$column = "tricks_won_trump_lead";
break;
case self::FIRST_TRUMP:
$column = "tricks_won_first_trump";
break;
case self::OVERTRUMP;
$column = "tricks_won_overtrump";
break;
case self::PLAINSUIT;
$column = "tricks_won_plainsuit";
break;
default:
$column = "tricks_won_error_should_handle_better";
break;
}
$sql = "UPDATE player SET ".$column."=".$column."+1 WHERE player_id=".$trick_winner_id.";";
self::DbQuery($sql);
}
function getPlayerTrickInfo(){
$players = self::getCollectionFromDb(
"SELECT player_id, tricks_won_trump_lead, tricks_won_first_trump, tricks_won_overtrump, tricks_won_plainsuit
FROM player;"
);
return $players;
}
function getTrickPile($player_id){
return count($this->cards->getCardsInLocation( 'trickpile', $player_id ));
}
function setScore( $player_id, $score_delta ){
if($score_delta < 0){
$operator = "-";
$score_delta = -$score_delta;
} else{
$operator = "+";
}
self::DbQuery(
"UPDATE player SET player_score=player_score".$operator.$score_delta." WHERE player_id='".$player_id."'"
);
}
function setRoundScore( $player_id, $num_calypsos, $calypso_cards, $won_cards ){
$round_number = self::getGameStateValue('roundNumber');
$sql_query = "
INSERT INTO round_scores (player_id, round_number, completed_calypsos, calypso_incomplete, won_tricks)
VALUES
(".$player_id.",".$round_number.",".$num_calypsos.",".$calypso_cards.",".$won_cards.");
";
self::DbQuery(
$sql_query
);
}
function validPlay( $player_id, $card ){
$valid_cards = self::getValidCards($player_id);
// this also ensures that $card is in hand, and there has been no funny business
return in_array($card, $valid_cards);
}
function getValidCards( $player_id ) {
// return array of valid cards
// all cards of led suit if available, otherwise anything
$trick_suit = self::getGameStateValue( 'trickSuit' );
$hand = $this->cards->getCardsInLocation( 'hand', $player_id );
if( $trick_suit == 0){
// i.e. first card of trick
// any card is fine
return $hand;
}
// otherwise, get all cards of led suit
$suit_cards = array_filter( $hand, function($hand_card) use ($trick_suit) {
return $hand_card['type'] == $trick_suit;
});
if( empty($suit_cards) ){
// if we have no cards of suit, again any card is fine
return $hand;
}
return $suit_cards;
}
function setPlayerHandActive($player_id) {
self::notifyPlayer(
$player_id,
'playableCards',
'',
array(
'playable_cards' => self::getValidCards($player_id),
)
);
}
function getCurrentRanks($player_id){
$calypso_so_far = $this->cards->getCardsInLocation( 'calypso', $player_id);
return array_map(
function($calypso_card){return $calypso_card['type_arg'];},
$calypso_so_far
);
}
// cards from me & partner go to calypsos if possible, otherwise they remain
// cards from opponents go to trickpile
function sortWonCards($cards_played, $winner_player_id){
$player_suit = self::getPlayerSuit($winner_player_id);
$partner_suit = self::getPartnerSuit($player_suit);
$partner_id = self::getPlayerIDFromSuit($partner_suit);
// array keeps track of where cards went, so we can pass to js for animation
$moved_to = array();
foreach ($cards_played as $card){
// take cards from our (me + part) suits that aren't already in calypsos in progress, and add them
// if they are already there, wait - that will come later
if ($card['type'] == $player_suit){
$player_ranks_so_far = self::getCurrentRanks($winner_player_id);
if (!in_array($card['type_arg'], $player_ranks_so_far)){
$moved_to[$card["location_arg"]] = array(
"originating_player" => $card["location_arg"],
"winner" => $winner_player_id,
"owner" => $winner_player_id,
"suit" => $card["type"],
"rank" => $card["type_arg"],
"card_id" => $card["id"],
);
$this->cards->moveCard( $card["id"], 'calypso', $winner_player_id);
}
} elseif ($card['type'] == $partner_suit){
$partner_ranks_so_far = self::getCurrentRanks($partner_id);
if (!in_array($card['type_arg'], $partner_ranks_so_far)){
$moved_to[$card["location_arg"]] = array(
"originating_player" => $card["location_arg"],
"winner" => $winner_player_id,
"owner" => $partner_id,
"suit" => $card["type"],
"rank" => $card["type_arg"],
"card_id" => $card["id"],
);
$this->cards->moveCard( $card["id"], 'calypso', $partner_id);
}
}
else {
// give opponents cards to player who won trick - partners can have separate piles
$moved_to[$card["location_arg"]] = array(
"owner" => 0,
"winner" => $winner_player_id,
"originating_player" => $card["location_arg"],
);
$this->cards->moveCard( $card["id"], 'trickpile', $winner_player_id);
}
}
return $moved_to;
}
function cardInCalypso($card, $player_id){
$calypso_so_far = $this->cards->getCardsInLocation( 'calypso', $player_id);
$ranks_so_far = array_map(
function($calypso_card){return $calypso_card['type_arg'];},
$calypso_so_far
);
return in_array($card['type_arg'], $ranks_so_far);
}
function processCalypsos(){
$players = self::loadPlayersBasicInfos();
// need to allow possibility of both partners completing calypsos in same trick
$calypsos_completed = array();
foreach ( $players as $player_id => $player ) {
$calypso_so_far = $this->cards->getCardsInLocation( 'calypso', $player_id);
$ranks_so_far = array_map(
function($calypso_card){return $calypso_card['type_arg'];},
$calypso_so_far
);
$calypso_string = implode( ",", $ranks_so_far );
if(sizeof($calypso_so_far) == 13){
$this->cards->moveAllCardsInLocation( 'calypso', 'full_calypsos', $player_id, $player_id );
$sql = "UPDATE player SET completed_calypsos = completed_calypsos+1 WHERE player_id=".$player_id.";";
self::DbQuery( $sql );
$calypsos_completed[] = $player_id;
}
$ranks_so_far = array_map(
function($calypso_card){return $calypso_card['type_arg'];},
$calypso_so_far
);
$calypso_string = implode( ",", $ranks_so_far );
}
return $calypsos_completed;
}
function getRoundScore($round_number){
$round_score = self::getCollectionFromDB(
"SELECT score_id, player_id, completed_calypsos, calypso_incomplete, won_tricks FROM round_scores
WHERE round_number=".$round_number.";"
);
$partnership_scores_raw = self::getCollectionFromDB(
"SELECT score_id, partnership, score FROM partnership_scores
WHERE round_number=".$round_number.";"
);
$partnership_scores = array();
foreach($partnership_scores_raw as $score_id => $details){
$partnership_scores[$details['partnership']] = $details['score'];
}
$processed_score = array();
foreach($round_score as $score_id => $score_info){
$num_calypsos = $score_info['completed_calypsos'];
$calypso_cards = $score_info['calypso_incomplete'];
$won_cards = $score_info['won_tricks'];
$processed_score[$score_info['player_id']] = array(
'calypso_count' => $num_calypsos,
'part_calypso_count' => $calypso_cards,
'won_cards_count' => $won_cards,
'partnership_score' => $partnership_scores[self::getPlayerPartnership($score_info['player_id'])],
) + self::countsToScores($num_calypsos, $calypso_cards, $won_cards);
}
return $processed_score;
}
function countsToScores($num_calypsos, $calypso_cards, $won_cards){
// score calypsos 500, 750, 1000, 1000 (cumulatively)
$calypsos_to_score = array(
0,
500,
1250, // 500 + 750
2250, // 500 + 750 + 1000
3250, // 500 + 750 + 1000 + 1000
);
$part_calypso_card_value = 20;
$won_cards_card_value = 10;
$calypso_score = $calypsos_to_score[$num_calypsos];
$part_calypso_score = $part_calypso_card_value * $calypso_cards;
$won_cards_score = $won_cards_card_value * $won_cards;
return array(
'calypso_score' => $calypso_score,
'part_calypso_score' => $part_calypso_score,
'won_cards_score' => $won_cards_score,
'total_score' => $calypso_score + $part_calypso_score + $won_cards_score,
);
}
// here we actually set the scores
function updateScores(){
$players = self::getAllCompletedCalypsos();
$round_number = self::getGameStateValue( 'roundNumber' );
$partnership_scores = array(
"minor" => 0,
"major" => 0,
);
foreach ( $players as $player_id => $num_calypsos ) {
$calypso_cards = count($this->cards->getCardsInLocation( 'calypso', $player_id ));
$won_cards = count($this->cards->getCardsInLocation( 'trickpile', $player_id ));
$scores_for_updating[$player_id] = self::countsToScores($num_calypsos, $calypso_cards, $won_cards)['total_score'];
self::setRoundScore( $player_id, $num_calypsos, $calypso_cards, $won_cards );
$partnership = self::getPlayerPartnership($player_id);
$partnership_scores[$partnership] += $scores_for_updating[$player_id];
}
foreach ( $players as $player_id => $num_calypsos ) {
$partnership = self::getPlayerPartnership($player_id);
self::setScore( $player_id, $partnership_scores[$partnership] );
}
foreach ( $partnership_scores as $partnership => $score ){
$sql_query = "
INSERT INTO partnership_scores (round_number, partnership, score)
VALUES
(".$round_number.",'".$partnership."',".$score.");
";
self::DbQuery(
$sql_query
);
}
}
function wrap_class($x, $class_name){
// just leave as arrays - the real wrapping happens client side
return array(
"to_wrap" => array(
"string_key" => $x,
"class_name" => $class_name,
),
);
}
// we pass this to js to construct appropriate string so we can generate in loop
// w/o messing up translations
function round_number_wrap($round_number){
return array(
"for_round_number" => array(
"round_number" => $round_number,
),
);
}
function count_wrap($x){
return self::wrap_class($x, "clp-number-entry");
}
function score_wrap($x){
return self::wrap_class($x, "clp-score-entry");
}
function count_wrap_label($x){
return self::wrap_class($x, "clp-number-label");
}
function score_wrap_label($x){
return self::wrap_class($x, "clp-score-label");
}
function suit_element_for_score_table($suit){
return "<div class=\"clp-suit-icon-${suit} clp-table-suit\"></div>";
}
function getDisplayScoresArgs($round_number){
// give counts and scores different classes so we can style them differently
$scores_for_updating = array();
$score_table = array();
$header_names = array( '' );
$header_suits = array( '' );
// just pass keys to front-end at let that handle the labels, as can't get translation working this end
// probably conceptually nicer having it in the js anyhow
$calypso_counts = array( self::count_wrap_label("calypso_count"));
$calypso_scores = array( self::score_wrap_label("score"));
$part_calypso_counts = array( self::count_wrap_label("incomplete_calypso_count"));
$part_calypso_scores = array( self::score_wrap_label("score"));
$won_card_counts = array( self::count_wrap_label("trickpile_count"));
$won_card_scores = array( self::score_wrap_label("score"));
$individual_scores = array( self::score_wrap_label("individual_score"));
$partnership_scores = array( self::score_wrap_label("partnership_score"));