/
tichu.game.php
1247 lines (1146 loc) · 53.6 KB
/
tichu.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 <gisabelli@boardgamearena.com> & Emmanuel Colin <ecolin@boardgamearena.com>
* Tichu implementation : © Bryan McGinnis <bryanrm@gmail.com>
*
* 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.
* -----
*
* tichu.game.php
*
* This is the main file for your game logic.
* In this PHP file, you are going to defines the rules of the game.
*/
require_once( APP_GAMEMODULE_PATH.'module/table/table.game.php' );
class Tichu extends Table {
function Tichu( ) {
// Your global variables labels:
// Here, you can assign labels to global variables you are using for this game.
// 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.
// Note: afterwards, you can get/set the global variables with getGameStateValue/setGameStateInitialValue/setGameStateValue
parent::__construct();self::initGameStateLabels( array(
"currentHandType" => 10,
"maxCardValue" => 11,
"alreadyFulfilledWish" => 12,
"playType" => 13,
"lastPlayPlayer" => 14,
"firstOutPlayer" => 15,
"lastOutPlayer" => 16,
"OneTwoVictory" => 17,
"dogNextPlayer" => 18,
"gameLength" => 100,
"grandTichu" => 101,
"grandTichuPasses" => 102,
) );
$this->cards = self::getNew( "module.common.deck" );
$this->cards->init( "card" );
}
protected function getGameName() { return "tichu"; }
protected function setupNewGame( $players, $options = array() ) {
self::debug("setupNewGame");
/* setupNewGame:
This method is called 1 time when a new game is launched.
In this method, you must setup the game according to game rules, in order
the game is ready to be played. */
$sql = "DELETE FROM player WHERE 1 ";
self::DbQuery( $sql );
// Set the colors of the players with HTML color code
// The default below is red/green/blue/yellow
// The number of colors defined here must correspond to the max number of players allowed for the games
$default_color = array( "ff0000", "008000", "0000ff", "ffa500" );
$start_points = 0;
$end_points = self::getGameStateValue( 'gameLength' ) == 1 ? 600 : 1000;
//$start_points = self::getGameStateValue( 'grandTichu' ) == 1 ? 75 : 100;
// Create players
// Note: if you added some extra field on "player" table in (dbmodel.sql), you can initialize it here.
$sql = "INSERT INTO player (player_id, player_team, player_score, player_maxscore, player_color, player_canal, player_name, player_avatar) VALUES ";
$values = array(); $i=0;
foreach( $players as $player_id => $player ) {
$color = array_shift( $default_color );
$player_team = $i % 2; // Make 1st & 3rd player team 0, 2nd & 4th team 1
$values[] = "('$player_id','$player_team','$start_points','$end_points','$color','".$player['player_canal']."','".addslashes( $player['player_name'] )."','".addslashes( $player['player_avatar'] )."')";
$i++; }
$sql .= implode(',',$values);
self::DbQuery( $sql );
self::reloadPlayersBasicInfos();
/********************** Start the game initialization *******************/
// Init global values with their initial values
// Note: hand types: 0 = give 3 cards to player on the left
// 1 = give 3 cards to player on the right
// 2 = give 3 cards to player on tthe front
// 3 = keep cards
//
// Need to change to give 1 card to West, 1 to East, 1 to North
// I would like to set it up to move first card clicked to W, second to E, third to N
// Then have the Send cards button, and a back button
self::setGameStateInitialValue( 'currentHandType', 0 ); // For passing
// Set high card value
self::setGameStateInitialValue( 'maxCardValue', 0 );
// Mark if the wish has been fulfilled during this hand
self::setGameStateInitialValue( 'alreadyFulfilledWish', 0 );
// Play Type per hand, this can't change except bombs and off of dog, -1=not set, see line 259
self::setGameStateInitialValue( 'playType', -1 );
// Add Last person to play
self::setGameStateInitialValue( 'lastPlayPlayer', 0 );
// First to go out
self::setGameStateInitialValue( 'firstOutPlayer', 0 );
// Last to to out
self::setGameStateInitialValue( 'lastOutPlayer', 0 );
// 1-2 Victory
self::setGameStateInitialValue( 'OneTwoVictory', -1 );
// Dog Skip (Skip if this player if he is flagged or this prop > 0
self::setGameStateInitialValue( 'dogNextPlayer', 0 );
//number of passes during grand tichu phase
self::setGameStateInitialValue( 'grandTichuPasses', 0 );
// Count # of consecutive passes, if 3 then trick is over
// self::setGameStateInitialValue( 'consecutivePassPlays', 0 );
// Init game statistics
// (note: statistics are defined in your stats.inc.php file)
self::initStat( "table" , "handNbr", 0 );
self::initStat( "player", "getQueenOfSpade", 0 );
self::initStat( "player", "getHearts", 0 );
self::initStat( "player", "getAllPointCards", 0 );
self::initStat( "player", "getNoPointCards", 0 );
// Create cards in deck
$cards = array();
foreach( $this->colors as $color_id => $color ) { // club=1, spade=2, heart=3, diamond=4
for( $value=1; $value<=14; $value++ ) { // 2, 3, 4, ... K, A
$cards[]=array('type'=>$color_id, 'type_arg'=>$value, 'nbr'=>1); } }
$this->cards->createCards( $cards, 'deck' );
// Reset plays_order & cards_order
$sql="UPDATE card SET card_plays_order='0', card_cards_order='0'";
self::DbQuery( $sql );
// Reset all players have called tichu or grand tichu this hand
$sql="UPDATE player SET player_call_tichu='0', player_call_grand_tichu='0'";
self::DbQuery( $sql );
$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 refresh the game page (F5) */
protected function getAllDatas() {
self::debug("getAllDatas");
$result = array( 'players' => array() );
$player_id = self::getCurrentPlayerId(); // !! We must only return informations visible by this player !!
// Get information about players
// Note: you can retrieve some extra field you add for "player" table in "dbmodel.sql" if you need it.
$sql = "SELECT player_id id, player_score score, player_team team, player_call_tichu call_tichu, player_call_grand_tichu call_grand_tichu FROM player ORDER BY player_no";
$dbres = self::DbQuery( $sql );
while( $player=mysql_fetch_assoc($dbres) )
$result['players'][ $player['id'] ] = $player;
// Get cards in current player hand (1st person)
$result['hand'] = $this->getCardsInLocation( 'hand', $player_id );
// $playerHand2 = $this->cards->getCardsInLocation( 'hand', $player_id );
// var_dump($result['hand']);
// var_dump($playerHand2);
// Cards played on the table (for all players)
$result['cardsontable'] = $this->getCardsInLocation( 'cardsontable' );
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 called each time in a game state with "updateGameProgression" property (see states.inc.php) */
function getGameProgression() { // Game progression: get player minimum score
$maximumScore = self::getUniqueValueFromDb( "SELECT MAX( player_score ) FROM player" );
$end_points = self::getGameStateValue( 'gameLength' ) == 1 ? 600 : 1000;
return max( 0, min( 100, intval($maximumScore/$end_points*100) ) ); // Note: 0 => 100
}
//////////////////////////////////////////////////////////////////////////////
//////////// Utility functions
////////////
/* At this place, you can put any utility methods useful for your game logic */
// Return players => direction (N/S/E/W) from the point of view
// of current player (current player must be on south)
function getPlayersToDirection() {
$result = array();
$players = self::loadPlayersBasicInfos(); // Get all players info
$nextPlayer = self::createNextPlayerTable( array_keys( $players ) );
$current_player = self::getCurrentPlayerId();
$directions = array( 'S', 'E', 'N', 'W' ); // Tichu goes counter clockwise
if( ! isset( $nextPlayer[ $current_player ] ) ) {
// Spectator mode: take any player for south
$player_id = $nextPlayer[0];
$result[ $player_id ] = array_shift( $directions );
} else {
// Normal mode: current player is on south
$player_id = $current_player;
$result[ $player_id ] = array_shift( $directions );
}
while( count( $directions ) > 0 ) {
$player_id = $nextPlayer[ $player_id ];
$result[ $player_id ] = array_shift( $directions );
}
return $result;
}
// This is my own version of this. The one by the same named called by $this->cards->getCardsInLocation()
// was not pulling the new fields that were added to database (cards_order & plays_order)
function getCardsInLocation($location,$player_id=0) {
$sql="SELECT * FROM card WHERE card_location='$location'";
if ($player_id>0)
$sql.=" AND card_location_arg='$player_id'";
// echo $sql;
$result=self::DbQuery( $sql );
$arr3=array();
while ($arr1=mysql_fetch_assoc($result)) {
if($arr1['card_id']>0) {
$id=$arr2['id']=$arr1['card_id'];
$arr2['type']=$arr1['card_type'];
$arr2['type_arg']=$arr1['card_type_arg'];
$arr2['location']=$arr1['card_location'];
$arr2['location_arg']=$arr1['card_location_arg'];
$arr2['cards_order']=$arr1['card_cards_order'];
$arr2['plays_order']=$arr1['card_plays_order'];
$arr3[$id]=$arr2;
}
}
if ($arr3) return $arr3;
}
function getCardPlayValue($card)
{
//TODO handle special cards
return $card['type_arg']*10;
}
//////////////////////////////////////////////////////////////////////////////
//////////// Player actions
////////////
/* Each time a player is doing some game action, one of this method below is called.
(note: each method below correspond to an input method in tichu.action.php) */
function sortAscending($a, $b)
{
$value1 = $this->getCardPlayValue($a);
$value2 = $this->getCardPlayValue($b);
if ($value1 == $value2)
return 0;
return ($value1 < $value2) ? -1 : 1;
}
function sortDescending($a, $b)
{
$value1 = $this->getCardPlayValue($a);
$value2 = $this->getCardPlayValue($b);
if ($value1 == $value2)
return 0;
return ($value1 > $value2) ? -1 : 1;
}
function passGrandTichu(){
self::notifyAllPlayers( 'grandTichuPass',
clienttranslate('${player_name} passes'), array(
'player_name' => self::getActivePlayerName()
) );
$grandTichuPasses = self::getGameStateValue( 'grandTichuPasses');
$grandTichuPasses = $grandTichuPasses + 1;
self::setGameStateValue( 'grandTichuPasses', $grandTichuPasses);
if ($grandTichuPasses < 4)
{
$this->gamestate->nextState( 'nextGrandTichu' ); // Next player
}
else
{
$this->gamestate->nextState( 'allSkipped' );
}
}
function callGrandTichu()
{ // More than 1 player can call Grand Tichu!
// In player table, set player_call_grand_tichu to 1
$player_id = self::getActivePlayerId();
$sql="UPDATE player SET player_call_grand_tichu='1' WHERE player_id='$player_id'";
self::DbQuery( $sql );
self::notifyAllPlayers( 'grandTichuCall',
clienttranslate('${player_name} calls Grand Tichu'), array(
'player_id' => $player_id,
'player_name' => self::getActivePlayerName()
) );
// Change player's name, adding " (Grand Tichu)"
$grandTichuPasses = self::getGameStateValue( 'grandTichuPasses');
$grandTichuPasses = $grandTichuPasses + 1;
self::setGameStateValue( 'grandTichuPasses', $grandTichuPasses);
if ($grandTichuPasses < 4)
{
$this->gamestate->nextState( 'nextGrandTichu' ); // Next player
}
else
{
$this->gamestate->nextState( 'allSkipped' );
}
}
function passPlay(){ // Press Pass button, skip turn
self::checkAction( "passPlay" );
if (self::getGameStateValue( 'playType' )<0) // If no cards or only dog on table you can't pass
throw new feException( 'Must play a card' );
$player_id = self::getActivePlayerId();
self::notifyAllPlayers( 'passPlay',
clienttranslate('${player_name} passes'), array(
// 'i18n' => array( 'specials_label' ),
'player_id' => $player_id,
'player_name' => self::getActivePlayerName()
) );
// Directs to states.inc.php:104,:110->stNextPlayer(tichu.game.php:513)
$this->gamestate->nextState( 'playCards' );
}
function playCards( $playCardsIds ) { // Press Play button, play cards from player hand
self::debug("PLAYCARDS server action called with ids [".$playCardsIds."]");
self::checkAction( "playCards" );
$player_id = self::getActivePlayerId();
// Get all cards in player hand (for checking if the cards played are in player's hand)
$playerHand = $this->getCardsInLocation( 'hand', $player_id );
// $bFirstCard = ( count( $playerHand ) == 14 ); // Not necessary in Tichu to track the first play
$maxCardValue = self::getGameStateValue( 'maxCardValue' );
// Check that the card is in this hand (for Hearts)
// I might need some of this validation (for Tichu)
$currentCards = null;
$bIsInHand = false;
//$bAtLeastOneCardOfCurrentTrickColor = false;
//$bAtLeastOneCardWithoutPoints = false;
//$bAtLeastOneCardNotHeart = false;
// Build an array of card_id's in the player's hand
$playerHandIds=array();
$playCards=array();
foreach ($playerHand as $card)
{
$playerHandIds[]=$card['id'];
if (in_array($card['id'],$playCardsIds))
{
$playCards[]=$card;
}
}
//by default, sort ascending
usort($playCards, array($this, "sortAscending"));
// Check each card to be played and make sure they are ALL in this player's hand
$bIsInHand=(count($playCardsIds)==count(array_intersect($playCardsIds,$playerHandIds)))?true:false;
if( !$bIsInHand ) throw new feException( "Cards are not in your hand" );
// Do some basic validation, this will also be validated on client
// Figure out what type of play is happening: (playType)
//-1 = Dog (This will actually keep playType at -1 so any type can be played, but not bomb)
// 0 = Singles
// 1 = Doubles
// 2 = Triples
// 3 = Full House
// 4 = Consecutive Doubles
// 5-14 = Run of 5 or more
// 15 = Dog
// 20 = Bomb
//
// First check if it is a bomb play
//throw new feException("getting play type");
$playType=self::getGameStateValue( 'playType' );
//get an array of the values played, this will make validation easier
$cardValues = array();
foreach ($playCards as $card)
{
array_push($cardValues, $this->getCardPlayValue($card));
}
//AK - I think this is easier to validate by expected play type than number of cards
//I'll do the non-special cases first...
//but first, what is the expected play type?
//TODO add bomb handling
//TODO add dragon handling
//TODO add phoenix handling
//throw new feException("calculating play type");
if ($playType == -1) //player has free choice. Must first figure out the type of play used.
{
if (count($playCardsIds) == 1)
{ //singles
$playType = 0;
}
else if (count($playCardsIds) == 2)
{ //doubles
$playType = 1;
}
else if (count($playCardsIds) == 3)
{ //triples
$playType = 2;
}
else if (count($playCardsIds) == 4)
{ //consecutive doubles
$playType = 4;
}
else if (count($playCardsIds) == 5)
{ //full house OR run
if ($cardValues[0] != $cardValues[1])
{ //a run, otherwise assume a full house
$playType = count($playCardsIds);
}
else
{
$playType = 3;
}
}
else if (count($playCardsIds) > 5)
{ //consecutive doubles OR run
if ($cardValues[0] != $cardValues[1])
{
$playType = count($playCardsIds);
}
else
{
$playType = 4;
}
}
else
{ //should never get this far.
throw new feException("Unrecognised play");
}
}
//throw new feException("validating play type");
//now we have the play type. Is the chosen play valid for that playtype?
switch ($playType)
{
case 0: //singles
if (count($playCardsIds) != 1) {
throw new feException("Play type is singles");
}
if ($cardValues[0] <= $maxCardValue) {
throw new feException("Must play a higher card");
}
break;
case 1: //doubles
if (count($playCardsIds) != 2) {
throw new feException("Play type is doubles");
}
if ($cardValues[0] != $cardValues[1])
{
throw new feException("Doubles must match");
}
if ($cardValues[0] <= $maxCardValue)
{
throw new feException("Must play a higher double");
}
break;
case 2: //triples
if (count($playCardsIds) != 3) {
throw new feException("Play type is triples");
}
if ($cardValues[0] != $cardValues[1] || $cardValues[1] != $cardValues[2])
{
throw new feException("Triples must match");
}
if ($cardValues[0] <= $maxCardValue) {
throw new feException("Must play a higher triple");
}
break;
case 3: //full house
//TODO - ideally the full house should sort the triple first. This is a nice to have, not essential.
if (count($playCardsIds) != 5) {
throw new feException("Play type is full house");
}
//sorted values - first and second card match, 4th and 5th match, middle value must match
//one of the two either side
if ($cardValues[0] != $cardValues[1] || $cardValues[3] != $cardValues[4] ||
($cardValues[2] != $cardValues[1] && $cardValues[2] != $cardValues[3]))
{
throw new feException("Full House must be a triple and a pair");
}
if ($cardValues[2] <= $maxCardValue)
{ //value is the triple card in full house
throw new feException("Must play a higher full house");
}
break;
case 4: //consecutive pairs
if (count($playCardsIds) % 2 != 0) {
throw new feException("Play type is consecutive pairs");
}
for ($i = 0; $i < count($playCardsIds); $i = $i+2) {
if ($cardValues[$i] != $cardValues[$i + 1]) {
throw new feException("Consecutive pairs cannot contain unpairds cards");
}
if ($i > 0 && $cardValues[$i] - $cardValues[$i-2] != 10) {
throw new feException("All pairs must be consecutive");
}
if ($cardValues[count($playCardsIds)-1] <= $maxCardValue) {
throw new feException("Must play higher consecutive pairs");
}
}
break;
case 5: //run
case 6: //run
case 7: //run
case 8: //run
case 9: //run
case 10: //run
case 11: //run
case 12: //run
case 13: //run
case 14: //run
if (count($playCardsIds) < 5) {
throw new feException("Play type is straight");
}
for ($i = 0; $i < count($playCardsIds); $i++) {
if ($i > 0 && $cardValues[$i] - $cardValues[$i - 1] > 10) {
throw new feException("All cards in the straight must be consecutive");
}
if ($cardValues[count($playCardsIds)-1] <= $maxCardValue) {
throw new feException("Must play a higher straight");
}
}
break;
default :
throw new feException("Unhandled play type");
}
//throw new feException("saving data");
//validation passed!
//update variables and save to db.
$playValue = $cardValues[count($playCardsIds)-1];
self::setGameStateValue( 'maxCardValue', $playValue );
self::setGameStateValue( 'playType', $playType);
//update cards in database
$playCards = self::UpdateCardsInDatabase($player_id, $playCardsIds, $playCards);
//next notify players.
//throw new feException("notifying players");
// Figure out what type of play is happening:
//-1 = Dog (This will actually keep playType at -1 so any type can be played, but not bomb)
// 0 = Singles
// 1 = Doubles
// 2 = Triples
// 3 = Full House
// 4 = Consecutive Doubles
// 5-14 = Run of 5 or more
// 20+?= Bomb
//
// First check if it is a bomb play
/*$playType=self::getGameStateValue( 'playType' );
switch (count($playCardsIds)) {
case 1:
if ($playType>0) // If the current play type is not singles or not first play
throw new feException( 'Must play a higher card of type: '.$this->play_type[$playType] );
$playValue=$playCards[0]['type_arg']*10; // Normal cards value
if ($playValue==10) { // Specials
switch ($playCards[0]['type']) {
case 1: // Dog
if ($playType!=-1)
throw new feException( 'Dog can only be played as first card of a trick' );
// playType is kept at -1 for next player to determine playType
self::notifyAllPlayers( 'playCards', // Notify of Dog play
clienttranslate('${player_name} plays ${specials_label}'), array(
'i18n' => array( 'specials_label' ),
'card_ids' => $playCardsIds,
'player_id' => $player_id,
'player_name' => self::getActivePlayerName(),
'value' => $playCards[0]['type_arg'],
'color' => $playCards[0]['type'],
'specials_label' => $this->specials_label[ $playCards[0]['type'] ],
'cards_order' =>$playCards[0]['cards_order'],
'plays_order' =>$playCards[0]['plays_order']
) );
// self::setGameStateValue( 'lastPlayPlayer', $player_id );
self::setGameStateValue( 'maxCardValue', -5 );
$this->gamestate->nextState( 'playCards' ); // Next player
return;
// break;
case 2: // Mah Jong
$playValue=10;
break;
case 3: // Phoenix
if ($maxCardValue==150) $playValue=145; // Phoenix can't beat dragon
elseif ($maxCardValue<10) $playValue=15; // Played on Dog or on nothing
else $playValue=$maxCardValue+5; // 1/2 pt higher than last play
break;
case 4: // Dragon
$playValue=150;
break;
default:
throw new feException( 'error type_arg:1, type:'+$playCards[0]['type'] );
}
}
if ( $maxCardValue >= $playValue ) // Invalid move: play must be higher
throw new feException( 'Must play a card that is higher than the highest play' );
//set $playType after validation as later code needs it.
//save $playValue/$playType for later plays
$playType=0;
self::setGameStateValue( 'maxCardValue', $playValue );
self::setGameStateValue( 'playType', $playType );
//update db and pass back changes to $playCards (card_order and plays_order)
$playCards = self::UpdateCardsInDatabase($player_id, $playCardsIds, $playCards);
break;
case 2:
if ($playType>-1 && $playType != 1) // If the current play type is not first play/doubles
throw new feException( 'Must play a higher card of type: '.$this->play_type[$playType] );
$playType = 1;
$playValue=$playCards[0]['type_arg']*10; // Normal cards value
if ( $maxCardValue >= $playValue ) // Invalid move: play must be higher
throw new feException( 'Must play a card that is higher than the highest play' );
self::setGameStateValue( 'maxCardValue', $playValue );
self::setGameStateValue( 'playType', $playType); //doubles
//update cards in database
$playCards = self::UpdateCardsInDatabase($player_id, $playCardsIds, $playCards);
break;
case 3:
if ($playType>-1 && $playType != 2) // If the current play type is not first play/doubles
throw new feException( 'Must play a higher card of type: '.$this->play_type[$playType] );
$playType = 2;
$playValue=$playCards[0]['type_arg']*10; // Normal cards value
if ( $maxCardValue >= $playValue ) // Invalid move: play must be higher
throw new feException( 'Must play a card that is higher than the highest play' );
self::setGameStateValue( 'maxCardValue', $playValue );
self::setGameStateValue( 'playType', $playType); //doubles
//update cards in database
$playCards = self::UpdateCardsInDatabase($player_id, $playCardsIds, $playCards);
break;
case 4:
//4 cards could be: bomb, consecutive pairs
//5 cards could be: full house, straight
//6+ cards (even) could be: straight, consecutive pairs
//7+ cards (odd) could be: straight
if ($playType>-1 && $playType != 2) // If the current play type is not first play/doubles
throw new feException( 'Must play a higher card of type: '.$this->play_type[$playType] );
$playType = 1;
$playValue=$playCards[0]['type_arg']*10; // Normal cards value
if ( $maxCardValue >= $playValue ) // Invalid move: play must be higher
throw new feException( 'Must play a card that is higher than the highest play' );
self::setGameStateValue( 'maxCardValue', $playValue );
self::setGameStateValue( 'playType', $playType); //doubles
//update cards in database
$playCards = self::UpdateCardsInDatabase($player_id, $playCardsIds, $playCards);
break;
default:
throw new feException( 'Play type not yet implemented' );
}*/
// Checks are done! now we can play our card
// Update database, change card_location from 'hand' to 'cardsontable'
// Actual visual movement of card is done below in Notifications
$this->cards->moveCards( $playCardsIds, 'cardsontable', $player_id );
//** NOTIFICATIONS ** // These sent to notif_playCards: tichu.js:318
// self::notifyAllPlayers( $notification_type, $notification_log, $notification_args )
// notification_type: String that defines type of your notification (and to trigger corresponding method)
// notification_log: A string that defines what is to be displayed in the game log.
// notification_args: The arguments of your notifications, as an associative array.
// from tichu.js: this.playCardOnTable( notif.args.player_id, notif.args.color, notif.args.value, notif.args.card_ids, notif.args.cards_order, notif.args.plays_order );
// Future also notify of Wish and Tichu calls and Bombs
self::debug("PLAYCARDS notification start");
self::debug("PLAYCARDS playtype [".$playType."]");
//client call is very similar in each case, shared code between all play types,
//but with slightly different text
if ($playType==0) { // For Singles
if ($playCards[0]['type_arg']>1) { // Not a Special card
$displayText = clienttranslate('${player_name} plays ${value_displayed}');
$displayValue = $this->values_label[ $playCards[0]['type_arg'] ];
$i18n = array( 'value_displayed' ); //not needed now?
}
else{
$displayText = clienttranslate('${player_name} plays ${value_displayed} (${playValue})');
$displayValue = $this->specials_label[ $playCards[0]['type'] ];
$i18n = array( 'specials_label' ); //check if this is needed
}
}
else if ($playType == 1) //doubles
{
$displayText = clienttranslate('${player_name} plays a double ${value_displayed}');
$displayValue = $this->values_label[ $playCards[0]['type_arg'] ];
$i18n = array( 'value_displayed' ); //check if needed
}
else if ($playType == 2) //triples
{
$displayText = clienttranslate('${player_name} plays a triple ${value_displayed}');
$displayValue = $this->values_label[ $playCards[0]['type_arg'] ];
$i18n = array( 'value_displayed' ); //check if needed
}
else if ($playType == 3) //full house
{
$displayText = clienttranslate('${player_name} plays a full house of ${value_displayed}');
$displayValue = $this->values_label[ $playCards[2]['type_arg'] ];
$i18n = array( 'value_displayed' ); //check if needed
}
else if ($playType == 4) //consecutive pairs
{
$displayText = clienttranslate('${player_name} plays consecutive pairs of ${value_displayed}');
$displayValue = $this->values_label[ $playCards[count($playCards)-1]['type_arg'] ];
$i18n = array( 'value_displayed' ); //check if needed
}
else if ($playType >= 5 && $playType <= 14) //straight
{
$displayText = clienttranslate('${player_name} plays a straight with a high card of ${value_displayed}');
$displayValue = $this->values_label[ $playCards[count($playCards)-1]['type_arg'] ];
$i18n = array( 'value_displayed' ); //check if needed
}
else
{
throw new feException("Playtype text missing");
}
$cardColors = array();
$cardValues = array();
foreach ($playCards as $card)
{
array_push($cardValues, $card['type_arg']);
array_push($cardColors, $card['type']);
}
self::notifyAllPlayers(
'playCards', // The notification to call tichu.js:306
$displayText,
array( // Notif.args to pass to JS
'i18n' => array( 'value_displayed' ),
'card_ids' => $playCardsIds,
'player_id' => $player_id,
'player_name' => self::getActivePlayerName(),
'value' => $cardValues,
'color' => $cardColors,
'playValue' => $playValue,
'value_displayed' => $displayValue,
'cards_order' =>$playCards[0]['cards_order'],
'plays_order'=>$playCards[0]['plays_order']
)
);
self::debug("PLAYCARDS card notifications finished");
self::setGameStateValue( 'playType', $playType );
self::setGameStateValue( 'lastPlayPlayer', $player_id );
$this->gamestate->nextState( 'playCards' ); // Next player
}
function UpdateCardsInDatabase($player_id, $playCardsIds, $playCards){
$playerCardsOnTable = $this->getCardsInLocation( 'cardsontable', $player_id );
$plays_order=0; // Find the highest plays_order for this player before playing the new cards
if ($playerCardsOnTable) // Check if this player already has cards on table to get plays_order
foreach ($playerCardsOnTable as $card) // Scan his played cards to get the current highest
$plays_order=max($card['plays_order'],$plays_order);
else $plays_order=0;
$plays_order++; // Increment plays_order by 1, send with playing card
$sql=''; // Set the plays_order one higher, and make each card played a higher cards_order
for ( $cards_order=1; $cards_order <= count($playCardsIds); $cards_order++) {
$card_id=$playCards[$cards_order-1]['id'];
$playCards[$cards_order-1]['cards_order']=$cards_order; // This will have to be sorted by weight
$playCards[$cards_order-1]['plays_order']=$plays_order; // What play # is this player on
$sql ="UPDATE card SET card_cards_order='$cards_order',card_plays_order='$plays_order' ".
"WHERE card_id = '$card_id';";
if ($sql) self::DbQuery($sql);
}
return $playCards;
}
function giveLeft( $card_ids ) {
self::checkAction( "giveLeft" );
$player_id = self::getCurrentPlayerId();
$this->cards->getCardsInLocation( 'cardsontable' );
}
function giveRight( $card_ids ) {
self::checkAction( "giveRight" );
$player_id = self::getCurrentPlayerId();
}
function giveCards( $card_ids ) { // Give some cards (before the hands begin)
self::debug("giveCards");
self::checkAction( "passCards" );
// !! Here we have to get CURRENT player (= player who send the request) and not
// active player, cause we are in a multiple active player state and the "active player"
// correspond to nothing.
$player_id = self::getCurrentPlayerId();
if( count( $card_ids ) != 3 )
throw new feException( self::_("You must give exactly 3 cards") );
// Check if these cards are in player hands
$cards = $this->cards->getCards( $card_ids );
if( count( $cards ) != 3 )
throw new feException( self::_("Some of these cards don't exist") );
foreach( $cards as $card ) { // Verify cards are in correct player's hand
if( $card['location'] != 'hand' || $card['location_arg'] != $player_id )
throw new feException( self::_("Some of these cards are not in your hand") ); }
// To which player should I give these cards ?
$player_to_give_cards = null;
$player_to_direction = self::getPlayersToDirection(); // Note: current player is on the south
for ($index = 0; $index<3; $index++)
{
if( $index == 0 ) $direction = 'W';
else if( $index == 1 ) $direction = 'E';
else if ( $index == 2 ) $direction = 'N';
self::debug("Direction:".$direction);
foreach( $player_to_direction as $opponent_id => $opponent_direction )
{
if( $opponent_direction == $direction )
{
$player_to_give_cards = $opponent_id;
self::debug("Giving card ".$card_ids[$index]." to ".$player_to_give_cards."(".$direction.")");
$this->cards->moveCard( $card_ids[$index], "temporary", $player_to_give_cards );
}
}
if( $player_to_give_cards === null )
throw new feException( self::_("Error while determining to who give the cards") );
}
// (note: we place the cards in some temporary location in order he can't see them before the hand starts)
// This updates database, notifyPlayer below does visuals
// Notify the player so we can make these cards disapear
//self::notifyPlayer( $player_id, "giveCards", "", array( "cards" => $card_ids ) );
//go to the next 'pass cards' state
$this->gamestate->setPlayerNonMultiactive( $player_id, "passCards" );
}
//////////////////////////////////////////////////////////////////////////////
//////////// Game state arguments
////////////
/* Here, you can create methods defines as "game state arguments" (see "args" property in states.inc.php).
These methods are returning some additional informations that are specific to the current game state. */
//////////////////////////////////////////////////////////////////////////////
//////////// Game state actions
////////////
// function stNewHand() {}
// function stGiveCards() {}
// function stTakeCards() {}
// function stNewTrick() {}
// function stBeforePlayerTurn() {}
// function stPlayCards() {}
// function stNextPlayer() {}
// function stEndHand() {}
// function stGameEnd() {}
/* Here, you can create methods defines as "game state actions" (see "action" property in states.inc.php).
The action method of state X is called everytime the current game state is set to X. */
function argPlayerTurn()
{
return array(
'playType' => self::getGameStateValue( 'playType' ),
'maxCardValue' => self::getGameStateValue( 'maxCardValue' ),
);
}
function stNewHand() {
self::debug("stNewHand");
self::incStat( 1, "handNbr" );
// Take back all cards (from any location => null) to deck
$this->cards->moveAllCardsInLocation( null, "deck" );
$this->cards->shuffle( 'deck' );
// Deal 8 cards to each players
// Create deck, shuffle it and give 8 initial cards
$players = self::loadPlayersBasicInfos();
foreach( $players as $player_id => $player ) {
$cards = $this->cards->pickCards( 8, 'deck', $player_id );
// Notify player about his cards
self::notifyPlayer( $player_id, 'newHand', '', array( 'cards' => $cards ) );
}
self::setGameStateValue( 'alreadyFulfilledWish', 0 );
$this->gamestate->nextState( "" );
}
function stPassCards() {
self::debug("stPassCards");
//must deal out the remaining 6 cards each, and notify players
$players = self::loadPlayersBasicInfos();
foreach( $players as $player_id => $player ) {
$cards = $this->cards->pickCards( 6, 'deck', $player_id );
// Notify player about his cards
self::notifyPlayer( $player_id, 'addToHand', '', array( 'cards' => $cards ) );
}
$this->gamestate->setAllPlayersMultiactive();
}
function stGiveCards() {
self::debug("stGiveCards");
self::setGameStateValue( 'grandTichuPasses', 0);
$this->gamestate->nextState( "cardsDealt" );
}
function stTakeCards() {
self::debug("stTakeCards");
// Take cards given by the other player
$players = self::loadPlayersBasicInfos();
foreach( $players as $player_id => $player ) {
// Each player takes cards in the "temporary" location and place it in his hand
$cards = $this->getCardsInLocation( "temporary", $player_id );
$this->cards->moveAllCardsInLocation( "temporary", "hand", $player_id, $player_id );
self::notifyPlayer( $player_id, "takeCards", "", array("cards" => $cards) );
}
// Find the player with the Mah Jong (1), they are starting player
$mahJongCardOwner = self::getUniqueValueFromDb( "SELECT card_location_arg FROM card
WHERE card_location='hand' AND card_type='2' AND card_type_arg='1' " );
if( $mahJongCardOwner !== null ) {
$this->gamestate->changeActivePlayer( $mahJongCardOwner );
} else throw new feException( self::_("Cant find Mah Jong (1)") );
$this->gamestate->nextState( "startHand" ); // For now
}
function stNewTrick() {
self::debug("stNewTrick");
// New trick: active the player who wins the last trick, or the player who owns the Mah Jong card
// $current_player = self::getCurrentPlayerId();
// Then have the Send cards button, and a back button
//self::setGameStateValue( 'currentHandType', 0 );
// Set high card value
self::setGameStateValue( 'maxCardValue', 0 );
// Reset lastPlayPlayer
self::setGameStateValue( 'lastPlayPlayer', 0 );
// Play Type per hand, this can't change except bombs and off of dog, -1=not set, see line 259
self::setGameStateInitialValue( 'playType', -1 );
// Mark if the wish has been fulfilled during this hand
// self::setGameStateInitialValue( 'alreadyFulfilledWish', 0 );
// Count # of consecutive passes, if 3 then trick is over
// self::setGameStateInitialValue( 'consecutivePassPlays', 0 );
$this->gamestate->nextState('');
}
function stNextPlayerDeclareGrandTichu() {
self::debug("stNextPlayerDeclareGrandTichu");
$this->activeNextPlayer();
$this->gamestate->nextState( "" );
}
function stBeforePlayerTurn() { // This can also redirect to Bomb play maybe
self::debug("stBeforePlayerTurn");
// $x=false;
// $dogNextPlayer = self::getGameStateValue( "dogNextPlayer" );
// $current_player = self::getActivePlayerId();
// for ($x=0;$x<6;$x++) { // Search for the next player with cards in hand
// $current_player = self::getPlayerAfter($current_player);
// $num_cards = $this->cards->countCardInLocation( 'hand', $current_player );
// if ($dogNextPlayer) { // If a dog is played is this player skipped?
// if ($current_player==$dogNextPlayer) {
// self::setGameStateValue( "dogNextPlayer", 0 ); $dogNextPlayer=0; }// Dog has completed mission
// } elseif ($num_cards>0) {
// self::giveExtraTime( $current_player ); // Give extra time to next player
// $this->gamestate->changeActivePlayer($current_player);
$this->gamestate->nextState( "startTurn" );
// }
// }
// if ($x==6) throw new feException( "Looped too many times searching for next player" );
}
function stEndTurn() {
self::debug("stEndTurn");
// Active next player OR end the trick and go to the next trick OR end the hand
// Need to change this to: If it's your turn and you were the last to play then pass trick to player
// and pass "nextTrick" => 30
// Figure out next player that is holding cards
$player_nos=array(1,2,3,4,1,2,3);
$current_player = self::getCurrentPlayerId();
$playersHands=array();
if (self::getGameStateValue('maxCardValue')==-10) { $dog=1; self::getGameStateValue('maxCardValue', 0); } else $dog=0;
// Get current player number in DB
$current_player_no=self::getUniqueValueFromDb( "SELECT player_no FROM player WHERE player_id='$current_player'" );
$resHand = $this->getCardsInLocation( 'hand' );
$player_nos=array_slice($player_nos,$current_player_no-1,4);
// var_dump($resHand);
foreach($resHand as $card)
$playersHands[$card['location_arg']]=$card;
if (count($playersHands[$current_player])==0) { // Player goes out on this play
if (self::getGameStateValue( 'firstOutPlayer' )==0) // If he is the first, record it
self::setGameStateValue( 'firstOutPlayer', $current_player ); }
// First check if him and his teammate are out
$sql2="SELECT player_no, player_id, count(card_id) as num, player_team FROM player
LEFT JOIN card ON player_id=card_location_arg
WHERE card_location='hand'
GROUP BY card_location_arg
ORDER BY FIELD(`player`.`player_no`,".implode(',',$player_nos).")";
$result = self::DbQuery( $sql2 );
if (!$result) die($sql2);
$nTeam=array();$nTeam[0]=$nTeam[1]=$n=$next_player=$dogNextPlayer=0;
$playersStillIn=array();$dogSkip=0;
while($arr1=mysql_fetch_assoc($result)) {
if ($arr1['num']>0) $nTeam[$arr1['player_team']]++; // Count # players on each team with cards
else $playersStillIn[]=$arr1;