dcabc678220d2f65f0924ed29bce0ce0dea2381d
[e-DoKo.git] / include / game.php
1 <?php
2 /* Copyright 2006, 2007, 2008, 2009, 2010 Arun Persaud <arun@nubati.net>
3  *
4  *   This file is part of e-DoKo.
5  *
6  *   e-DoKo is free software: you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation, either version 3 of the License, or
9  *   (at your option) any later version.
10  *
11  *   e-DoKo is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with e-DoKo.  If not, see <http://www.gnu.org/licenses/>.
18  *
19  */
20
21 /* make sure that we are not called from outside the scripts,
22  * use a variable defined in config.php to check this
23  */
24 if(!isset($HOST))
25   exit;
26
27 /* calling game.php only makes sense when we give it a hash for a game */
28 if(!myisset('me'))
29   {
30     echo "Hmm, you really shouldn't mess with the urls.<br />\n";
31     return;
32   }
33 $me = $_REQUEST['me'];
34
35 /* Ok, got a hash, but is it valid? */
36 $myid = DB_get_userid('hash',$me);
37 if(!$myid)
38   {
39     echo "Can't find you in the database, please check the url.<br />\n";
40     echo "perhaps the game has been canceled, check by login in <a href=\"$INDEX\">here</a>.";
41     return;
42   }
43
44 global $GAME,$RULES,$CARDS;
45
46 /* get some information from the DB */
47 $gameid   = DB_get_gameid_by_hash($me);
48 $myname   = DB_get_name('hash',$me);
49 $mystatus = DB_get_status_by_hash($me);
50 $origmystatus = DB_get_status_by_hash($me); /* to show "it's your turn" menu when game has just finished */
51 $mypos    = DB_get_pos_by_hash($me);
52 $myhand   = DB_get_handid('hash',$me);
53 $myparty  = DB_get_party_by_hash($me);
54 $session  = DB_get_session_by_gameid($gameid);
55
56 /* get prefs and save them in a variable*/
57 $PREF = DB_get_PREF(isset($_SESSION['id'])?$_SESSION['id']:$myid);
58
59 /* get rule set for this game */
60 $RULES = DB_get_RULES($gameid);
61
62 /* get some infos about the game */
63 $gametype   = DB_get_gametype_by_gameid($gameid);
64 $gamestatus = DB_get_game_status_by_gameid($gameid);
65 $GT         = $gametype;
66 if($gametype=='solo')
67   {
68     $gametype = DB_get_solo_by_gameid($gameid);
69     $GT  = $gametype.' '.$GT;
70   }
71
72 /* do we need to worry about Schweinchen?
73  * check gametype and rules
74  * if yes, figure out if someone actually has Schweinchen
75  * save information in $GAME
76  */
77 $ok=0;
78 if( $gamestatus == 'pre' )
79   {
80     /* always need to use Schweinchen to figure out for example who has poverty */
81     $ok=1;
82     /* unless the gametype is set and we know that we are in poverty were schweinchen is not valid */
83     if( in_array( $gametype,array('poverty','dpoverty') ))
84       $ok=0;
85   }
86 else
87   {
88     /* in a game Schweinchen is not valid in all types of games */
89     if( in_array($gametype,array('normal','wedding','trump','silent') ))
90       if( in_array($RULES['schweinchen'],array('both','second','secondaftercall')) )
91         $ok=1;
92   }
93
94 /* these are the defaults */
95 $GAME['schweinchen-who']    = NULL;
96 $GAME['schweinchen-first']  = NULL;
97 $GAME['schweinchen-second'] = NULL;
98
99 if($ok)
100 {
101   /* need to check for Schweinchen */
102   for($i=1;$i<5;$i++)
103     {
104       $hash  = DB_get_hash_from_game_and_pos($gameid,$i);
105       $cards = DB_get_all_hand($hash);
106       if( in_array('19',$cards) && in_array('20',$cards) )
107         $GAME['schweinchen-who']=$hash;
108     };
109   $GAME['schweinchen-first']  = 0; /* to keep track if they have been played already */
110   $GAME['schweinchen-second'] = 0;
111 }
112 /* end check for Schweinchen */
113
114 /* set the $CARDS variable, needed for sorting the cards
115  * we set it to normal so that the pre-game phase is handled ok
116  * and later set it to the correct game type that is played
117  */
118 set_gametype('normal');
119
120 /* put everyting in a form */
121 echo "<form action=\"index.php?action=game&amp;me=$me\" method=\"post\">\n";
122
123 /* handle user notes (only possible while game is running)*/
124 if( $mystatus!='gameover' )
125   if(myisset('note'))
126     {
127       $note = $_REQUEST['note'];
128
129       if($note != '')
130         DB_insert_note($note,$gameid,$myid);
131     };
132
133 /* handle calls, output a comment to show when the call was made */
134 /* initialize comments */
135 $comment  =  '';
136
137 /* check for calls, set comment */
138 if(myisset('call')  && $_REQUEST['call']  == '120' && can_call(120,$me))
139   {
140     $result = DB_query("UPDATE Hand SET point_call='120' WHERE hash='$me' ");
141     if($myparty=='re')
142       $comment .= "Re";
143     else if($myparty=='contra')
144       $comment .= "Contra";
145   }
146 if(myisset('call')  && $_REQUEST['call']  == '90' && can_call(90,$me))
147   {
148     $result = DB_query("UPDATE Hand SET point_call='90'  WHERE hash='$me' ");
149     $comment .= "No 90";
150   }
151 if(myisset('call')  && $_REQUEST['call']  == '60' && can_call(60,$me))
152   {
153     $result = DB_query("UPDATE Hand SET point_call='60'  WHERE hash='$me' ");
154     $comment .= "No 60";
155   }
156 if(myisset('call')  && $_REQUEST['call']  == '30' && can_call(30,$me))
157   {
158     $result = DB_query("UPDATE Hand SET point_call='30'  WHERE hash='$me' ");
159     $comment .= "No 30";
160   }
161 if(myisset('call')  && $_REQUEST['call']  == '0' && can_call(0,$me))
162   {
163     $result = DB_query("UPDATE Hand SET point_call='0'   WHERE hash='$me' ");
164     $comment .= "Zero";
165   }
166
167 /* get information needed to submit comment */
168 $playid = DB_get_current_playid($gameid);
169
170 /* set comment */
171 if($comment != '')
172   DB_insert_comment($comment,$playid,$myid);
173 /* clear up */
174 unset($comment);
175 /* end check for calls */
176
177
178 /* output extra division in case this game is part of a session */
179 if($session)
180   {
181     echo "<div class=\"session\">\n";
182     echo '  <div class="sessionrules">'._('Rules').': ';
183     switch($RULES['dullen'])
184       {
185       case 'none':
186         echo "  <img class=\"rulesicon\" alt=\""._('no ten of hearts')."\" src=\"pics/button/no-ten-of-hearts.png\"/>\n"; break;
187       case 'firstwins':
188         echo "  <img class=\"rulesicon\" alt=\""._('ten of hearts')."\" src=\"pics/button/ten-of-hearts.png\"/>\n"; break;
189       case 'secondwins':
190         echo "  <img class=\"rulesicon\" alt=\""._('second ten of hearts')."\" src=\"pics/button/second-ten-of-hearts.png\"/>\n"; break;
191       }
192     switch($RULES['schweinchen'])
193       {
194       case 'none':
195         echo "  <img class=\"rulesicon\" alt=\""._('no schweinchen')."\" ".
196           "src=\"pics/button/no-schweinchen.png\"/>\n"; break;
197       case 'both':
198         echo "  <img class=\"rulesicon\" alt=\""._('two schweinchen')."\" ".
199           "src=\"pics/button/two-schweinchen.png\"/>\n"; break;
200       case 'second':
201         echo "  <img class=\"rulesicon\" alt=\"".('second schweinchen')."\" ".
202           "src=\"pics/button/second-schweinchen.png\"/>\n"; break;
203       case 'secondaftercall':
204         echo "  <img class=\"rulesicon\" alt=\""._('second schweinchen after call')."\" ".
205           "src=\"pics/button/second-schweinchen-after-call.png\"/>\n"; break;
206       }
207     switch($RULES['call'])
208       {
209       case '1st-own-card':
210         echo "  <img class=\"rulesicon\" alt=\""._('1st-own-card')."\" src=\"pics/button/1st-own-card.png\"/>\n"; break;
211       case '5th-card':
212         echo "  <img class=\"rulesicon\" alt=\""._('5th-card')."\" src=\"pics/button/5th-card.png\"/>\n"; break;
213       case '9-cards':
214         echo "  <img class=\"rulesicon\" alt=\""._('9-cards')."\" src=\"pics/button/9-cards.png\"/>\n"; break;
215       }
216     echo "  <div>\n";
217     echo '       '._('10ofhearts').":  {$RULES['dullen']}      <br />\n";
218     echo '       '._('schweinchen').": {$RULES['schweinchen']} <br />\n";
219     echo '       '._('call').":        {$RULES['call']}        <br />\n";
220     echo '       '._('lowtrump').":    {$RULES['lowtrump']}    <br />\n";
221     echo "  </div>\n  </div>\n";
222
223     /* show score */
224
225     echo "  <div class=\"sessionscore\">";
226
227     $score   = generate_score_table($session);
228
229     /* get the last entry to show on the main page */
230     $tmpscore= $score;
231     $finalscore = array_pop($tmpscore);
232     $finalscore = $finalscore['players'];
233
234     if($finalscore)
235       {
236         echo _('Score').": \n";
237         foreach($finalscore as $user=>$value)
238           {
239             $name = DB_get_name('userid',$user);
240             echo " ".substr($name,0,2).": $value ";
241           }
242       }
243     else
244       {
245         /* first game, no score yet */
246         echo "&nbsp;";
247       }
248
249     /* output all games for the score table */
250     echo format_score_table_html($score,$myid);
251     echo "  </div>\n";
252
253     /* figure out which game in a session we are in and link to the
254      * previous and next game if possible
255      */
256     $hashes = DB_get_hashes_by_session($session,$myid);
257     $next     = NULL;
258     $i = 1;
259     foreach($hashes as $hash)
260       {
261         if($hash == $me)
262           $j=$i;
263         $i++;
264         $lasthash=$hash;
265       }
266     $i--;
267
268     if($j>1)
269       $previous = $hashes[$j-2];
270     else
271       $previous = NULL;
272     if($j<$i)
273       $next = $hashes[$j];
274     else
275       $next = NULL;
276
277     if(isset($_SESSION['id']) && $_SESSION['id']==$myid)
278       {
279         if($previous)
280           echo "<a href=\"{$INDEX}?action=game&amp;me=$previous\">"._('previous game')."</a>&nbsp;&nbsp;&nbsp; \n";
281         echo "This is game number $j of <a href=\"{$INDEX}?action=game&amp;me=$lasthash\">$i</a> in session $session.\n";
282         if($next)
283           echo "&nbsp;&nbsp;&nbsp;<a href=\"{$INDEX}?action=game&amp;me=$next\">"._('next game')."</a> \n";
284       }
285     else
286       echo "This is game number $j of $i in session $session.";
287     echo "\n</div>\n";
288   }
289
290 /* display the table and the names */
291 display_table();
292
293 /* mystatus gets the player through the different stages of a game.
294  * start:    does the player want to play?
295  * init:     check for sickness
296  * check:    check for return values from init
297  * poverty:  handle poverty, wait here until all player have reached this state
298  *           display sickness and move on to game
299  * play:     game in progress
300  * gameover: are we revisiting a game
301  */
302
303 /* the user has done something, update the timestamp. Use $myid in
304  * active games and check for session-id in old games (myid might be wrong in that case)
305  */
306 if($mystatus!='gameover')
307   DB_update_user_timestamp($myid);
308  else
309    if(isset($_SESSION['id']))
310      DB_update_user_timestamp($_SESSION['id']);
311
312 switch($mystatus)
313   {
314   case 'start':
315     /* don't ask if user has autosetup set to yest */
316     $skip = 0;
317     if($PREF['autosetup']=='yes') $skip = 1;
318
319     if( !myisset('in') && !$skip)
320       {
321         /* asks the player, if he wants to join the game */
322         output_check_want_to_play($me);
323         echo '<div class="mycards"></div>';
324         break;
325       }
326     else
327       {
328         /* check the result, if player wants to join, got next stage, else cancel game */
329         if(!$skip && $_REQUEST['in'] == 'no' )
330           {
331             /* cancel the game */
332             $message = "Hello, \n\n".
333               "the game has been canceled due to the request of one of the players.\n\n";
334
335             $userids = DB_get_all_userid_by_gameid($gameid);
336             foreach($userids as $user)
337               {
338                 mymail($user,$gameid,GAME_CANCELED,$message);
339               }
340
341             /* update game status */
342             cancel_game('noplay',$gameid);
343             break;
344           }
345         else
346           {
347             /* user wants to join the game */
348
349             /* move on to the next stage,
350              * no break statement to immediately go to the next stage
351              */
352
353             DB_set_hand_status_by_hash($me,'init');
354
355             /* check if everyone has reached this stage, send out email */
356             $userids = DB_get_all_userid_by_gameid($gameid);
357             $ok = 1;
358             foreach($userids as $user)
359               {
360                 $userstat = DB_get_hand_status_by_userid_and_gameid($user,$gameid);
361                 if($userstat!='init')
362                   {
363                     /* whos turn is it? */
364                     DB_set_player_by_gameid($gameid,$user);
365                     $ok = 0;
366                     break;
367                   }
368               };
369             if($ok)
370               {
371                 /* all done, send out email unless this player is the startplayer */
372                 $startplayer = DB_get_startplayer_by_gameid($gameid);
373                 if($mypos == $startplayer)
374                   {
375                     /* do nothing, go to next stage */
376                   }
377                 else
378                   {
379                     /* email startplayer */
380                     /*
381                      $hash        = DB_get_hash_from_game_and_pos($gameid,$startplayer);
382                      $who         = DB_get_userid('hash',$hash);
383                      DB_set_player_by_gameid($gameid,$who);
384
385                      $message = "It's your turn now in game ".DB_format_gameid($gameid).".\n".
386                      "Use this link to go the game: ".$HOST.$INDEX."?action=game&me=".$hash."\n\n" ;
387                      mymail($who, $gameid, GAME_READY,$message);
388                     */
389                   }
390               }
391           }
392       }
393   case 'init':
394     /* here we ask the player if he is sick */
395     $mycards = DB_get_hand($me);
396     $mycards = mysort($mycards,$gametype);
397
398     if(!myisset('solo','wedding','poverty','nines','lowtrump') )
399       {
400         /* output sickness of other playes, in case the already selected and are sitting in front of the current player */
401         echo "\n<ul class=\"tricks\">\n";
402         echo "  <li class=\"nohighlight\"> Game ".DB_format_gameid($gameid).": </li>\n";
403         echo "  <li onclick=\"hl('0');\" class=\"current\"><a href=\"#\">Pre</a>\n".
404           "    <div class=\"trick\" id=\"trick0\">\n";
405
406         for($pos=1;$pos<5;$pos++)
407           {
408             $usersick   = DB_get_sickness_by_pos_and_gameid($pos,$gameid);
409             $userid     = DB_get_userid('gameid-position',$gameid,$pos);
410             $userstatus = DB_get_hand_status_by_userid_and_gameid($userid,$gameid);
411
412             if($userstatus=='start' || $userstatus=='init')
413               echo " <div class=\"vorbehalt".($pos-1)."\"> still needs <br/ > to decide </div>\n"; /* show this to everyone */
414             else
415               if($usersick!=NULL && $pos<=$mypos ) /* only show this for people sitting before the player */
416                 echo " <div class=\"vorbehalt".($pos-1)."\"> sick </div>\n";
417               else if($usersick==NULL && $pos<=$mypos)
418                 echo " <div class=\"vorbehalt".($pos-1)."\"> healthy </div>\n";
419           }
420         echo "    </div>\n  </li>\n</ul>\n";  /* end div trick, end li trick , end tricks*/
421         /* end displaying sickness */
422
423         output_check_for_sickness($me,$mycards);
424
425         echo '<div class="mycards">'._('Your cards are').": <br />\n";
426         foreach($mycards as $card)
427           display_card($card,$PREF['cardset']);
428         echo "</div>\n";
429
430         break;
431       }
432     else
433       {
434         /* check if someone selected more than one sickness */
435         $Nsickness = 0;
436         if($_REQUEST['solo']!='No')       $Nsickness++;
437         if($_REQUEST['wedding']  == 'yes') $Nsickness++;
438         if($_REQUEST['poverty']  == 'yes') $Nsickness++;
439         if($_REQUEST['nines']    == 'yes') $Nsickness++;
440         if($_REQUEST['lowtrump'] == 'yes') $Nsickness++;
441
442         if($Nsickness>1)
443           {
444             echo "<p class=\"message\"> You selected more than one sickness, please go back ".
445               "and answer the <a href=\"$INDEX?action=game&amp;me=$me&amp;in=yes\">question</a> again.</p>";
446
447             echo '<div class="mycards">'._('Your cards are').": <br />\n";
448             foreach($mycards as $card)
449               display_card($card,$PREF['cardset']);
450             echo "</div>\n";
451
452             break;
453           }
454         else
455           {
456             /* everything is ok, save what user said and proceed */
457             echo "<p class=\"message\">Processing what you selected in the last step...";
458
459             /* check if this sickness needs to be handled first */
460             $gametype    = DB_get_gametype_by_gameid($gameid);
461             $startplayer = DB_get_startplayer_by_gameid($gameid); /* need this to check which solo goes first */
462
463             if( $_REQUEST['solo']!='No' )
464               {
465                 /* user wants to play a solo */
466
467                 /* store the info in the user's hand info */
468                 DB_set_solo_by_hash($me,$_REQUEST['solo']);
469                 DB_set_sickness_by_hash($me,'solo');
470
471                 echo "<br />Seems like you want to play a {$_REQUEST['solo']} solo. Got it.<br />\n";
472
473                 if($gametype == 'solo' && $startplayer<$mypos)
474                   {}/* do nothing, since someone else already is playing solo */
475                 else
476                   {
477                     /* this solo comes first
478                      * store info in game table
479                      */
480                     DB_set_gametype_by_gameid($gameid,'solo');
481                     DB_set_startplayer_by_gameid($gameid,$mypos);
482                     DB_set_solo_by_gameid($gameid,$_REQUEST['solo']);
483                   };
484               }
485             else if($_REQUEST['wedding'] == 'yes')
486               {
487                 /* silent solo is set further down */
488                 echo _("Ok, you don't want to play a silent solo...wedding was chosen.")."<br />\n";
489                 DB_set_sickness_by_hash($me,'wedding');
490               }
491             else if($_REQUEST['poverty'] == 'yes')
492               {
493                 echo _("Don't think you can win with just a few trump...? Ok, poverty chosen.")." <br />\n";
494                 DB_set_sickness_by_hash($me,'poverty');
495               }
496             else if($_REQUEST['nines'] == 'yes')
497               {
498                 echo _("What? You just don't want to play a game because you have a few nines? Well, if no one".
499                        " is playing solo, this game will be canceled.")."<br />\n";
500                 DB_set_sickness_by_hash($me,'nines');
501               }
502             else if($_REQUEST['lowtrump'] == 'yes')
503               {
504                 if($RULES['lowtrump']=='cancel')
505                   echo _("What? You just don't want to play a game because you have low trump? Well, if no one".
506                          " is playing solo, this game will be canceled.")."<br />\n";
507                 else
508                   echo _("Don't think you can win with low trumps...? Ok, poverty chosen.")." <br />.<br />\n";
509
510                 DB_set_sickness_by_hash($me,'lowtrump');
511               }
512
513             echo "</p>\n";
514
515             /* move on to the next stage*/
516             DB_set_hand_status_by_hash($me,'check');
517             $mystatus='check';
518           };
519       };
520
521   case 'check':
522     /* here we check what all players said and figure out what game we are playing
523      * this can therefore only be handled once all players finished the last stage
524      */
525
526     $mycards = DB_get_hand($me);
527     $mycards = mysort($mycards,$gametype);
528
529     /* output sickness of other playes, in case they already selected and are sitting in front of the current player */
530     echo "\n<ul class=\"tricks\">\n";
531     echo "  <li class=\"nohighlight\"> Game ".DB_format_gameid($gameid).": </li>\n";
532     echo "  <li onclick=\"hl('0');\" class=\"current\"><a href=\"#\">Pre</a>\n".
533       "    <div class=\"trick\" id=\"trick0\">\n";
534
535     for($pos=1;$pos<5;$pos++)
536       {
537         $usersick   = DB_get_sickness_by_pos_and_gameid($pos,$gameid);
538         $userid     = DB_get_userid('gameid-position',$gameid,$pos);
539         $userstatus = DB_get_hand_status_by_userid_and_gameid($userid,$gameid);
540
541         if($userstatus=='start' || $userstatus=='init')
542           echo " <div class=\"vorbehalt".($pos-1)."\"> still needs <br />to decide </div>\n"; /* show this to everyone */
543         else
544           if($usersick!=NULL) /* in the init-phase we only showed players with $pos<$mypos, now we can show all */
545             echo " <div class=\"vorbehalt".($pos-1)."\"> sick </div>\n";
546           else
547             echo " <div class=\"vorbehalt".($pos-1)."\"> healthy </div>\n";
548       }
549     echo "    </div>\n  </li>\n</ul>\n";  /* end div trick, end li trick , end tricks*/
550     /* end displaying sickness */
551
552     echo "<div class=\"message\">\n";
553     echo '<p> '._('Checking if someone else selected solo, nines, wedding or poverty.').'</p>';
554
555     /* check if everyone has reached this stage */
556     $userids = DB_get_all_userid_by_gameid($gameid);
557     $ok = 1;
558     foreach($userids as $user)
559       {
560         $userstat = DB_get_hand_status_by_userid_and_gameid($user,$gameid);
561         if($userstat!='check')
562           {
563             $ok = 0;
564             DB_set_player_by_gameid($gameid,$user);
565             break;
566           }
567       };
568
569     if(!$ok)
570       {
571         echo '<p>'._('This step can only be handled after everyone finished the last step. '.
572           'Seems like this is not the case, so you need to wait a bit... '.
573           'you will get an email once that is the case, please use the link in '.
574           'that email to continue the game.').'</p></div>';
575
576         /* display cards, if player was just at the init-phase he will still see the cards from there
577          * we can put this one here, since the last player to finish the init state won't get here and
578          * will still see his card anyway from the init-phase
579          */
580         if($mystatus=='check')
581           {
582             /* show cards */
583             echo '<div class="mycards">'._('Your cards are').": <br />\n";
584             foreach($mycards as $card)
585               display_card($card,$PREF['cardset']);
586             echo "</div>\n";
587           }
588         break;
589       }
590     else
591       {
592         /* Ok, everyone finished the init-phase, time to figure out what game we
593          * are playing, in case there are any solos this already
594          * will have the correct information in it */
595
596         echo '<p>'._('Ok, everyone is done... figuring out what kind of game we are playing.').'</p>';
597
598         $gametype    = DB_get_gametype_by_gameid($gameid);
599         $startplayer = DB_get_startplayer_by_gameid($gameid);
600
601         /* check for sickness */
602         $cancel  = 0;
603         $poverty = 0;
604         $wedding = 0;
605         $solo    = 0;
606         foreach($userids as $user)
607           {
608             $name     = DB_get_name('userid',$user);
609             $usersick = DB_get_sickness_by_userid_and_gameid($user,$gameid);
610             if($usersick == 'nines' || ($RULES['lowtrump']=='cancel' && $usersick=='lowtrump') )
611               {
612                 $cancel     = $user;
613                 $cancelsick = $usersick;
614                 break; /* no need to check for other poverties, since only solo can win and that is already set */
615               }
616             else if($usersick == 'poverty' || ($RULES['lowtrump']=='poverty' && $usersick=='lowtrump'))
617               $poverty++;
618             else if($usersick == 'wedding')
619               $wedding=$user;
620             else if($usersick == 'solo')
621               $solo++;
622           }
623
624         /* now check which sickness comes first and set the gametype to it */
625         if($gametype == 'solo')
626           {
627             /* do nothing */
628           }
629         else if($cancel)
630           {
631             /* cancel game */
632             if($cancelsick == 'nines')
633               {
634                 $message = "The game has been canceled because ".DB_get_name('userid',$cancel).
635                   " has five or more nines and nobody is playing solo.\n\n".
636                   "To redeal either start a new game or, in case the game was part of a tournament,\n".
637                   "go to the last game and use the link at the bottom of the page to redeal.\n\n";
638
639                 /* update game status */
640                 cancel_game('nines',$gameid);
641
642                 echo "<p>The game has been canceled because ".DB_get_name('userid',$cancel).
643                   " has five or more nines and nobody is playing solo.</p>\n";
644               }
645             else if ($cancelsick == 'lowtrump')
646               {
647                 $message = "The game has been canceled because ".DB_get_name('userid',$cancel).
648                   " has low trump and nobody is playing solo.\n\n".
649                   "To redeal either start a new game or, in case the game was part of a tournament,\n".
650                   "go to the last game and use the link at the bottom of the page to redeal.\n\n";
651
652                 /* update game status */
653                 cancel_game('lowtrump',$gameid);
654
655                 echo "<p>The game has been canceled because ".DB_get_name('userid',$cancel).
656                   " has low trump and nobody is playing solo.</p>\n";
657               };
658
659             $userids = DB_get_all_userid_by_gameid($gameid);
660             foreach($userids as $user)
661               {
662                 mymail($user,$gameid, GAME_CANCELED, $message);
663               }
664
665             echo "</div>\n"; /* end div message */
666             break;
667           }
668         else if($poverty==1) /* one person has poverty */
669           {
670             DB_set_gametype_by_gameid($gameid,'poverty');
671             $gametype = 'poverty';
672             $who      = DB_get_sickness_by_gameid($gameid);
673             if(!$who)
674               {
675                 $firstsick = DB_get_sickness_by_pos_and_gameid(1,$gameid);
676                 if($firstsick == 'poverty' || ($RULES['lowtrump']=='poverty' && $firstsick=='lowtrump'))
677                   DB_set_sickness_by_gameid($gameid,2); /* who needs to be asked first */
678                 else
679                   DB_set_sickness_by_gameid($gameid,1); /* who needs to be asked first */
680               }
681           }
682         else if($poverty==2) /* two people have poverty */
683           {
684             DB_set_gametype_by_gameid($gameid,'dpoverty');
685             $gametype = 'dpoverty';
686             $who      = DB_get_sickness_by_gameid($gameid);
687             if(!$who)
688               {
689                 $firstsick = DB_get_sickness_by_pos_and_gameid(1,$gameid);
690                 if($firstsick == 'poverty' || ($RULES['lowtrump']=='poverty' && $firstsick=='lowtrump'))
691                   {
692                     $secondsick = DB_get_sickness_by_pos_and_gameid(1,$gameid);
693                     if($secondsick == 'poverty'  || ($RULES['lowtrump']=='poverty' && $secondsick=='lowtrump'))
694                       DB_set_sickness_by_gameid($gameid,30); /* who needs to be asked first */
695                     else
696                       DB_set_sickness_by_gameid($gameid,20); /* who needs to be asked first */
697                   }
698                 else
699                   DB_set_sickness_by_gameid($gameid,10); /* who needs to be asked first */
700               }
701           }
702         else if($wedding> 0)
703           {
704             DB_set_gametype_by_gameid($gameid,'wedding');
705             DB_set_sickness_by_gameid($gameid,'-1'); /* wedding not resolved yet */
706             $gametype = 'wedding';
707           };
708         /* now the gametype is set correctly in the database */
709         echo '<p>'._('Got it').' :)</p>';
710
711         /* loop over all players, set re/contra if possible and start the game if possible */
712         $userids = DB_get_all_userid_by_gameid($gameid);
713         foreach($userids as $userid)
714           {
715             $userhash = DB_get_hash_from_gameid_and_userid($gameid,$userid);
716
717             switch($gametype)
718               {
719               case 'solo':
720                 /* are we the solo player? set us to re, else set us to contra */
721                 $pos = DB_get_pos_by_hash($userhash);
722                 if($pos == $startplayer)
723                   DB_set_party_by_hash($userhash,'re');
724                 else
725                   DB_set_party_by_hash($userhash,'contra');
726                 DB_set_hand_status_by_hash($userhash,'play');
727                 break;
728
729               case 'wedding':
730                 /* set person with the wedding to re, do the rest during the game */
731                 $usersick = DB_get_sickness_by_userid_and_gameid($userid,$gameid);
732                 if($usersick == 'wedding')
733                   DB_set_party_by_hash($userhash,'re');
734                 else
735                   DB_set_party_by_hash($userhash,'contra');
736
737                 DB_set_hand_status_by_hash($userhash,'play');
738                 break;
739
740               case 'normal':
741                 $hand = DB_get_all_hand($userhash);
742
743                 if(in_array('3',$hand)||in_array('4',$hand))
744                   DB_set_party_by_hash($userhash,'re');
745                 else
746                   DB_set_party_by_hash($userhash,'contra');
747                 DB_set_hand_status_by_hash($userhash,'play');
748                 break;
749               case 'poverty':
750               case 'dpoverty':
751                 /* set person with poverty to play status */
752                 $usersick = DB_get_sickness_by_userid_and_gameid($userid,$gameid);
753                 if($usersick == 'poverty'  || ($RULES['lowtrump']=='poverty' && $usersick=='lowtrump'))
754                   DB_set_hand_status_by_hash($userhash,'play');
755
756                 /* set status of first player to be asked to poverty */
757                 $who = DB_get_sickness_by_gameid($gameid);
758                 if($who > 6) $who= $who/10; /* in case we have dpoverty */
759                 $whoid = DB_get_userid('gameid-position',$gameid,$who);
760                 if($whoid==$userid)
761                   DB_set_hand_status_by_hash($userhash,'poverty');
762               }
763           }
764         /* check for silent solo, set game type to solo in this case */
765         $gametype = DB_get_gametype_by_gameid($gameid);
766         $userids  = DB_get_all_userid_by_gameid($gameid);
767         foreach($userids as $userid)
768           {
769             $userhash = DB_get_hash_from_gameid_and_userid($gameid,$userid);
770
771             if($gametype=='normal')
772               {
773                 $userhand = DB_get_all_hand($userhash);
774                 if(check_wedding($userhand))
775                   {
776                     /* normal game type and player has both queens -> silent solo */
777                     /* keep startplayer, just set gametype to silent solo */
778                     DB_set_gametype_by_gameid($gameid,'solo');
779                     DB_set_solo_by_gameid($gameid,'silent');
780                   }
781               }
782           }
783
784         /* send out email to first player or poverty person*/
785         if($gametype!='poverty' && $gametype!='dpoverty')
786           {
787             $startplayer = DB_get_startplayer_by_gameid($gameid);
788             $hash        = DB_get_hash_from_game_and_pos($gameid,$startplayer);
789             $who         = DB_get_userid('hash',$hash);
790             DB_set_player_by_gameid($gameid,$who);
791
792             if($hash!=$me)
793               {
794                 if(DB_get_email_pref_by_hash($hash)!='emailaddict')
795                   {
796                     /* email startplayer */
797                     $message = "It's your turn now in game ".DB_format_gameid($gameid).".\n".
798                       "Use this link to play a card: ".$HOST.$INDEX."?action=game&me=".$hash."\n\n" ;
799                     mymail($who,$gameid,GAME_READY,$message);
800                   }
801               }
802             else
803               echo "Please, <a href=\"$INDEX?action=game&amp;me=$me\">start</a> the game.<br />\n";
804           }
805         else
806           {
807             /* set status of first player to be asked to poverty */
808             $who   = DB_get_sickness_by_gameid($gameid);
809             if($who > 6) $who= $who/10; /* in case we have dpoverty */
810
811             $whoid = DB_get_userid('gameid-position',$gameid,$who);
812             if($whoid==$myid)
813               echo "Please, <a href=\"$INDEX?action=game&amp;me=$me\">start</a> the game.<br /\n";
814             else
815               {
816                 $whohash = DB_get_hash_from_game_and_pos($gameid,$who);
817                 DB_set_player_by_gameid($gameid,$whoid);
818
819                 if(DB_get_email_pref_by_hash($hash)!='emailaddict')
820                   {
821                     /* email player for poverty */
822                     $message = "Poverty: It's your turn now in game ".DB_format_gameid($gameid).".\n".
823                       "Use this link to play a card: ".$HOST.$INDEX."?action=game&me=".$whohash."\n\n" ;
824                     mymail($whoid,$gameid,GAME_POVERTY,$message);
825                   }
826               }
827           }
828         echo "</div>\n";
829         /* show cards */
830         echo '<div class="mycards">'._('Your cards are').": <br />\n";
831         foreach($mycards as $card)
832           display_card($card,$PREF['cardset']);
833         echo "</div>\n";
834
835         break;
836       }
837
838   case 'poverty':
839     /* user only gets here in a poverty game, several things have to be handled here:
840      * A) ask, if user wants to take trump
841      *      yes-> take trump,
842      *            poverty: set re/contra
843      *            dpoverty: first time: set re, send email to second player
844      *                      second time: set contra
845      *            poverty: set status of other players to 'play'
846      *            set status to play in case 0 trump
847      *      no -> set status to play,
848      *            ask next player or cancle the game if no more players
849      * B) user took trump and has too many cards (e.g. count(cards)>12 and re/contra set)
850      *         ask to give cards back, set status to play, once player has 12 cards
851      *
852      * it is easier to check B) first
853      */
854
855     set_gametype($gametype); /* this sets the $CARDS variable */
856     $myparty = DB_get_party_by_hash($me);
857
858     /* the following is part B) of whats needs to be done)
859     /*    check if user wants to give cards back */
860     if(myisset('exchange'))
861       {
862         $exchange    = $_REQUEST['exchange'];
863         $partnerhash = DB_get_partner_hash_by_hash($me);
864         $partnerid   = DB_get_userid('hash',$partnerhash);
865         $partnerhand = DB_get_handid('gameid-userid',$gameid,$partnerid);
866
867         /* if exchange is set to a value>0, exchange that card back to the partner */
868         if($exchange >0)
869           {
870             $result = DB_query("UPDATE Hand_Card SET hand_id='$partnerhand'".
871                                " WHERE hand_id='$myhand' AND card_id=".DB_quote_smart($exchange));
872             DB_add_exchanged_card(DB_quote_smart($exchange),$myhand,$partnerhand);
873           };
874       }
875
876     /* update hand */
877     $mycards = DB_get_hand($me);
878     $mycards = mysort($mycards,$gametype);
879
880     /* output pre-game trick in case user reloads,
881      * only needs to be done when a team has been formed */
882     if($myparty=='re' || $myparty=='contra')
883       {
884         echo "\n<ul class=\"tricks\">\n";
885         echo "  <li class=\"nohighlight\"> Game ".DB_format_gameid($gameid).": </li>\n";
886
887         $mygametype =  DB_get_gametype_by_gameid($gameid);
888
889         echo "  <li onclick=\"hl('0');\" class=\"current\"><a href=\"#\">Pre</a>\n".
890           "    <div class=\"trick\" id=\"trick0\">\n";
891
892         /* get information so show the cards that have been handed over in a poverty game */
893         output_exchanged_cards();
894
895         echo "    </div>\n  </li>\n</ul>\n\n";  /* end div trick, end li trick , end ul tricks */
896       }
897     /* end output pre-game trick */
898
899     /* check if user need to give more cards back */
900     if( ($myparty=='re' || $myparty=='contra') && count($mycards)>12)
901       {
902         echo '<div class="poverty"> '._('You need to get rid of a few cards')."</div>\n";
903
904         $type='exchange';
905         echo '<div class="mycards">'._('Your cards are').": <br />\n";
906         foreach($mycards as $card)
907           display_link_card($card,$PREF['cardset'],$type);
908         echo "  <input type=\"submit\" class=\"submitbutton\" value=\"select card to give back\" />\n";
909         echo "</div>\n";
910       }
911     else if( ($myparty=='re' || $myparty=='contra') && count($mycards)==12)
912       {
913         /* user is done, ready to play */
914         DB_set_hand_status_by_hash($me,'play');
915
916         /* email start player */
917         $startplayer = DB_get_startplayer_by_gameid($gameid);
918         $hash        = DB_get_hash_from_game_and_pos($gameid,$startplayer);
919         $who         = DB_get_userid('hash',$hash);
920         DB_set_player_by_gameid($gameid,$who);
921
922         if($hash!=$me)
923           {
924             if(DB_get_email_pref_by_hash($hash)!='emailaddict')
925               {
926                 /* email startplayer */
927                 $message = "It's your turn now in game ".DB_format_gameid($gameid).".\n".
928                   "Use this link to play a card: ".$HOST.$INDEX."?action=game&me=".$hash."\n\n" ;
929                 mymail($who,$gameid,GAME_READY,$message);
930               }
931           }
932         else
933           echo "<div class=\"message\">Please, <a href=\"$INDEX?action=game&amp;me=$me\">start</a> the game.</div>\n";
934         echo '<div class="mycards"></div>'."\n"; /* needed to make sure the message area is in the right position */
935       }
936
937     /* the following is part A) of what needs to be done */
938     if(!myisset('trump'))
939       {
940         if(!$myparty)
941           {
942             echo "<div class=\"poverty\">\n";
943             $userids = DB_get_all_userid_by_gameid($gameid);
944             foreach($userids as $user)
945               {
946                 $name      = DB_get_name('userid',$user);
947                 $usersick  = DB_get_sickness_by_userid_and_gameid($user,$gameid);
948                 $userhash  = DB_get_hash_from_gameid_and_userid($gameid,$user);
949                 $userparty = DB_get_party_by_hash($userhash);
950
951                 if(($usersick=='poverty'|| ($RULES['lowtrump']=='poverty' && $usersick=='lowtrump')) && !$userparty)
952                   {
953                     $hash    = DB_get_hash_from_gameid_and_userid($gameid,$user);
954                     $cards   = DB_get_hand($hash);
955                     /* count trump */
956                     $nrtrump = 0;
957                     foreach($cards as $card)
958                       if($card<27) $nrtrump++;
959                     $low='';
960                     if($usersick=='lowtrump')
961                       $low='low';
962                     echo "Player $name has $nrtrump $low trump. Do you want to take them?".
963                       "<a href=\"index.php?action=game&amp;me=$me&amp;trump=$user\">Yes</a> <br />\n";
964                   }
965               }
966             echo "<a href=\"index.php?action=game&amp;me=$me&amp;trump=no\">No way</a> <br />\n";
967             echo "</div><div>\n";
968
969             echo '<div class="mycards">'._('Your cards are').": <br />\n";
970             foreach($mycards as $card)
971               display_card($card,$PREF['cardset']);
972             echo "</div></div>\n";
973           }
974         break;
975       }
976     else
977       {
978         $trump = $_REQUEST['trump'];
979
980         if($trump=='no')
981           {
982             /* user doesn't want to take trump */
983             DB_set_hand_status_by_hash($me,'play');
984
985             /* set next player who needs to be asked and email him*/
986             $firstsick  = (string) DB_get_sickness_by_pos_and_gameid($mypos+1,$gameid);
987             $secondsick = (string) DB_get_sickness_by_pos_and_gameid($mypos+2,$gameid);
988
989             /* don't ask people who have poverty */
990             $next=1;
991             if($firstsick=='poverty' || ($RULES['lowtrump']=='poverty' && $firstsick=='lowtrump'))
992               {
993                 if($secondsick=='poverty'|| ($RULES['lowtrump']=='poverty' && $secondsick=='lowtrump'))
994                   $next=3;
995                 else
996                   $next=2;
997               }
998             if($gametype=='dpoverty')
999               {
1000                 $next=999; /* need to cancel for sure, since both would need to take the trump */
1001               }
1002
1003             /* no more people to ask, need to cancel the game */
1004             if($mypos+$next>4)
1005               {
1006                 $message = "Hello, \n\n".
1007                   "Game ".DB_format_gameid($gameid)." has been canceled since nobody wanted to take the trump.\n\n";
1008
1009                 $userids = DB_get_all_userid_by_gameid($gameid);
1010                 foreach($userids as $user)
1011                   {
1012                     mymail($user, $gameid, GAME_CANCELED_POVERTY, $message);
1013                   }
1014
1015                 /* update game status */
1016                 cancel_game('trump',$gameid);
1017
1018                 echo "<p class=\"message\";>Game ".DB_format_gameid($gameid)." has been canceled.<br /><br /></p>";
1019                 break;
1020               }
1021             else
1022               {
1023                 /* email next player, set his status to poverty */
1024                 $userhash = DB_get_hash_from_game_and_pos($gameid,$mypos+$next);
1025                 $userid   = DB_get_userid('hash',$userhash);
1026
1027                 DB_set_player_by_gameid($gameid,$userid);
1028                 DB_set_hand_status_by_hash($userhash,'poverty');
1029
1030                 $message = "Someone has poverty, it's your turn to decide, if you want to take the trump. Please visit:".
1031                   " ".$HOST.$INDEX."?action=game&me=".$userhash."\n\n" ;
1032                 mymail($userid,$gameid, GAME_POVERTY, $message);
1033               }
1034           }
1035         else
1036           {
1037             /* player wants to take trump, change cards */
1038
1039             /* user wants to take trump */
1040             $trump = $_REQUEST['trump'];
1041             $userhand = DB_get_handid('gameid-userid',$gameid,$trump);
1042             $userhash = DB_get_hash_from_gameid_and_userid($gameid,$trump);
1043
1044             /* remember which cards were handed over*/
1045             $partnerhand = DB_get_all_hand($userhash);
1046             foreach ($partnerhand as $card)
1047               if($card<27)
1048                 DB_add_exchanged_card($card,$userhand,$myhand);
1049
1050             /* copy trump from player A to B */
1051             $result = DB_query("UPDATE Hand_Card SET hand_id='$myhand' WHERE hand_id='$userhand' AND card_id<'27'" );
1052
1053             /* reload cards */
1054             $mycards = DB_get_hand($me);
1055
1056             /* set re/contra */
1057             if($gametype=='poverty')
1058               {
1059                 $userids = DB_get_all_userid_by_gameid($gameid);
1060                 foreach($userids as $user)
1061                   {
1062                     $hash = DB_get_hash_from_gameid_and_userid($gameid,$user);
1063                     if($hash==$userhash||$hash==$me)
1064                       {
1065                         DB_set_party_by_hash($hash,'re');
1066                       }
1067                     else
1068                       {
1069                         DB_set_party_by_hash($hash,'contra');
1070                         DB_set_hand_status_by_hash($hash,'play'); /* the contra party is ready to play */
1071                       }
1072                   }
1073                 /* check if we are done (in case of no trump handed over), if so, go to 'play' phase right away*/
1074                 if(count($mycards)==12)
1075                   {
1076                     DB_set_hand_status_by_hash($me,'play');
1077                   }
1078               }
1079             else /*dpoverty*/
1080               {
1081                 /* has the re party already been set?*/
1082                 $re_set=0;
1083                 $userids = DB_get_all_userid_by_gameid($gameid);
1084                 foreach($userids as $user)
1085                   {
1086                     $hash = DB_get_hash_from_gameid_and_userid($gameid,$user);
1087                     $party = DB_get_party_by_hash($hash);
1088                     if($party=='re')
1089                       $re_set=1;
1090                   }
1091                 if($re_set)
1092                   {
1093                     DB_set_party_by_hash($me,'contra');
1094                     DB_set_party_by_hash($userhash,'contra');
1095                   }
1096                 else
1097                   {
1098                     DB_set_party_by_hash($me,'re');
1099                     DB_set_party_by_hash($userhash,'re');
1100
1101                     /* send out email to second non-poverty player */
1102                     $firstsick  = (string) DB_get_sickness_by_pos_and_gameid($mypos+1,$gameid);
1103                     $secondsick = (string) DB_get_sickness_by_pos_and_gameid($mypos+2,$gameid);
1104
1105                     $next=1;
1106                     if($firstsick=='poverty'|| ($RULES['lowtrump']=='poverty' && $firstsick=='lowtrump'))
1107                       if($secondsick=='poverty'|| ($RULES['lowtrump']=='poverty' && $secondsick=='lowtrump'))
1108                         $next=3;
1109                       else
1110                         $next=2;
1111
1112                     if($mypos+$next>4)
1113                       echo "<div class=\"message\">Error in poverty, please contact the Admin</div>\n";
1114
1115                     $userhash = DB_get_hash_from_game_and_pos($gameid,$mypos+$next);
1116                     $userid   = DB_get_userid('hash',$userhash);
1117
1118                     DB_set_player_by_gameid($gameid,$userid);
1119                     DB_set_hand_status_by_hash($userhash,'poverty');
1120
1121                     $message = "Two people have poverty, it's your turn to decide, if you want to take the trump. Please visit:".
1122                       " ".$HOST.$INDEX."?action=game&me=".$userhash."\n\n" ;
1123                     mymail($userid,$gameid, GAME_DPOVERTY, $message);
1124                   }
1125               }
1126             echo "<div class=\"message\">Please, <a href=\"$INDEX?action=game&amp;me=$me\">continue</a> here.</div>\n";
1127           }
1128       }
1129     echo "</div>\n";
1130     break;
1131
1132   case 'play':
1133   case 'gameover':
1134     /* both entries here,  so that the tricks are visible for both.
1135      * in case of 'play' there is a break later that skips the last part
1136      */
1137
1138     /* first check if the game has been canceled and display */
1139     switch($gamestatus)
1140       {
1141       case 'cancel-noplay':
1142         echo "<div class=\"message\"><p>The game has been canceled due to the request of one player.</p><p>If this was a mistake all 4 players need to send an Email to $ADMIN_NAME at $ADMIN_EMAIL requesting that the game should be restarted.</p></div>";
1143         break;
1144       case 'cancel-timedout':
1145         echo "<div class=\"message\"><p>The game has been canceled because one player wasn't responding.</p><p>If this was a mistake all 4 players need to send an Email to $ADMIN_NAME at $ADMIN_EMAIL requesting that the game should be restarted.</p></div>";
1146         break;
1147       case 'cancel-nines':
1148         echo "<div class=\"message\"><p>The game has been canceled because one player had too many nines.</p></div>";
1149         break;
1150       case 'cancel-lowtrump':
1151         echo "<div class=\"message\"><p>The game has been canceled because one player had low trump.</p></div>";
1152         break;
1153       case 'cancel-trump':
1154         echo "<div class=\"message\"><p>The game has been canceled because nobody wanted to take the trump.</p></div>";
1155         break;
1156       }
1157     /* for these two types, we shouldn't show the cards, since we might want to restart the game */
1158     if (in_array($gamestatus,array('cancel-noplay','cancel-timedout')))
1159       break;
1160
1161     /* check if all players are ready to play,
1162      * if so, send out email to the startplayer
1163      * only need to do this if the game hasn't started yet
1164      */
1165     $gamestatus = DB_get_game_status_by_gameid($gameid);
1166     if($gamestatus == 'pre')
1167       {
1168         $ok = 1;
1169         $userids = DB_get_all_userid_by_gameid($gameid);
1170         foreach($userids as $user)
1171           {
1172             $userstatus = DB_get_hand_status_by_userid_and_gameid($user,$gameid);
1173             if($userstatus !='play' && $userstatus!='gameover')
1174               {
1175                 $ok = 0;
1176                 DB_set_player_by_gameid($gameid,$user);
1177                 break;
1178               }
1179           }
1180         if($ok)
1181           {
1182             /* only set this after all poverty, etc. are handled*/
1183             DB_set_game_status_by_gameid($gameid,'play');
1184
1185             /* email startplayer */
1186             $startplayer = DB_get_startplayer_by_gameid($gameid);
1187             $hash        = DB_get_hash_from_game_and_pos($gameid,$startplayer);
1188             $who         = DB_get_userid('hash',$hash);
1189             DB_set_player_by_gameid($gameid,$who);
1190
1191             if($hash!=$me && DB_get_email_pref_by_hash($hash)!='emailaddict')
1192               {
1193                 /* email startplayer) */
1194                 $message = "It's your turn now in game ".DB_format_gameid($gameid).".\n".
1195                   "Use this link to play a card: ".$HOST.$INDEX."?action=game&me=".$hash."\n\n" ;
1196                 mymail($who,$gameid, GAME_READY, $message);
1197               }
1198           }
1199       }
1200     /* figure out what kind of game we are playing,
1201      * set the global variables $CARDS['trump'],$CARDS['diamonds'],$CARDS['hearts'],
1202      * $CARDS['clubs'],$CARDS['spades'],$CARDS['foxes']
1203      * accordingly
1204      */
1205
1206     $gametype = DB_get_gametype_by_gameid($gameid);
1207     $GT       = $gametype;
1208     if($gametype=='solo')
1209       {
1210         $gametype = DB_get_solo_by_gameid($gameid);
1211         if($gametype=='silent')
1212           $GT = 'normal';
1213         else
1214           $GT = $gametype.' '.$GT;
1215       }
1216     else
1217       $gametype = 'normal';
1218
1219     set_gametype($gametype); /* this sets the $CARDS variable */
1220
1221     /* get some infos about the game, need to reset this, since it might have changed */
1222     $gamestatus = DB_get_game_status_by_gameid($gameid);
1223
1224     /* has the game started? No, then just wait here...*/
1225     if($gamestatus == 'pre')
1226       {
1227         echo '<p class="message"> '._('You finished the setup, but not everyone else finished it... '.
1228           'You need to wait for the others. Just wait for an email.').' </p>';
1229
1230         $mycards = DB_get_hand($me);
1231         $mycards = mysort($mycards,$gametype);
1232
1233         echo '<div class="mycards">'._('Your cards are').": <br />\n";
1234         foreach($mycards as $card)
1235           display_card($card,$PREF['cardset']);
1236         echo "</div>\n";
1237
1238         break; /* not sure this works... the idea is that you can
1239                 * only  play a card after everyone is ready to play */
1240       }
1241
1242
1243     /* get time from the last action of the game */
1244     $r = DB_query_array("SELECT mod_date from Game WHERE id='$gameid' " );
1245     $gameend = time() - strtotime($r[0]);
1246
1247     /* handle comments in case player didn't play a card, allow comments a week after the end of the game */
1248     if( (!myisset('card') && $mystatus=='play') || ($mystatus=='gameover' && ($gameend < 60*60*24*7)) )
1249       if(myisset('comment'))
1250         {
1251           $comment = $_REQUEST['comment'];
1252           $playid = DB_get_current_playid($gameid);
1253
1254           if($comment != '')
1255             DB_insert_comment($comment,$playid,$myid);
1256         };
1257
1258     /* get everything relevant to display the tricks */
1259     $result = DB_query("SELECT Hand_Card.card_id as card,".
1260                        "       Hand.position as position,".
1261                        "       Play.sequence as sequence, ".
1262                        "       Trick.id, ".
1263                        "       GROUP_CONCAT(CONCAT('<span>',User.fullname,': ',Comment.comment,'</span>')".
1264                        "                    SEPARATOR '\n' ), ".
1265                        "       Play.create_date, ".
1266                        "       Hand.user_id ".
1267                        "FROM Trick ".
1268                        "LEFT JOIN Play ON Trick.id=Play.trick_id ".
1269                        "LEFT JOIN Hand_Card ON Play.hand_card_id=Hand_Card.id ".
1270                        "LEFT JOIN Hand ON Hand_Card.hand_id=Hand.id ".
1271                        "LEFT JOIN Comment ON Play.id=Comment.play_id ".
1272                        "LEFT JOIN User On User.id=Comment.user_id ".
1273                        "WHERE Trick.game_id='".$gameid."' ".
1274                        "GROUP BY Trick.id, sequence ".
1275                        "ORDER BY Trick.id, sequence  ASC");
1276     $trickNR   = 0;
1277     $lasttrick = DB_get_max_trickid($gameid);
1278
1279     $play = array(); /* needed to calculate winner later  */
1280     $seq  = 1;
1281     $pos  = DB_get_startplayer_by_gameid($gameid)-1;
1282     $firstcard = ''; /* first card in a trick */
1283
1284     echo "\n<ul class=\"tricks\">\n";
1285     echo '  <li class="nohighlight"> '._('Game').' '.DB_format_gameid($gameid).": </li>\n";
1286
1287     /* output vorbehalte */
1288     $mygametype = DB_get_gametype_by_gameid($gameid);
1289     $mygamesolo = DB_get_solo_by_gameid($gameid);
1290     if($mygametype != 'normal') /* only show when needed */
1291       if(!( $mygametype == 'solo' && $mygamesolo == 'silent') )
1292         {
1293           echo "  <li onclick=\"hl('0');\" class=\"current\"><a href=\"#\">Pre</a>\n".
1294             "    <div class=\"trick\" id=\"trick0\">\n";
1295
1296           /* get information so show the cards that have been handed over in a poverty game */
1297           output_exchanged_cards();
1298
1299           echo "    </div>\n  </li>\n";  /* end div trick, end li trick */
1300         }
1301
1302     /* output tricks */
1303     while($r = DB_fetch_array($result))
1304       {
1305         $pos     = $r[1];
1306         $seq     = $r[2];
1307         $trick   = $r[3];
1308         $comment = $r[4];
1309         $user    = $r[6];
1310
1311         /* count number of tricks */
1312         if($seq==1)
1313           $trickNR++;
1314
1315         /* check if first schweinchen has been played */
1316         if( $GAME['schweinchen-who'] && ($r[0] == 19 || $r[0] == 20) )
1317           if(!$GAME['schweinchen-first'])
1318             $GAME['schweinchen-first'] = 1; /* playing the first fox */
1319           else
1320             $GAME['schweinchen-second'] = 1; /* this must be the second fox */
1321
1322         /* save card to be able to find the winner of the trick later */
1323         $play[$seq] = array('card'=>$r[0],'pos'=>$pos);
1324
1325         if($seq==1)
1326           {
1327             /* first card in a trick, output some html */
1328             if($trick!=$lasttrick)
1329               {
1330                 /* start of an old trick? */
1331                 echo "  <li onclick=\"hl('$trickNR');\" class=\"old\"><a href=\"#\">"._('Trick')." $trickNR</a>\n".
1332                   "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
1333                   "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
1334               }
1335             else if($trick==$lasttrick)
1336               {
1337                 /* start of a last trick? */
1338                 echo "  <li onclick=\"hl('$trickNR');\" class=\"current\"><a href=\"#\">"._('Trick')." $trickNR</a>\n".
1339                   "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
1340                   "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
1341               };
1342
1343             /* remember first card, so that we are able to check, what cards can be played */
1344             $firstcard = $r[0];
1345           };
1346
1347         /* display card */
1348         echo "      <div class=\"card".($pos-1)."\">\n";
1349
1350         /* display comments */
1351         if($comment!='')
1352           echo "        <span class=\"comment\">".$comment."</span>\n";
1353
1354         echo '        ';
1355         display_card($r[0],$PREF['cardset']);
1356
1357         echo "      </div>\n"; /* end div card */
1358
1359         /* end of trick? */
1360         if($seq==4)
1361           {
1362             $winner    = get_winner($play,$gametype); /* returns the position */
1363             echo "    </div>\n  </li>\n";  /* end div trick, end li trick */
1364           }
1365       }
1366
1367     /* whos turn is it? */
1368     if($seq==4)
1369       {
1370         $winner    = get_winner($play,$gametype); /* returns the position */
1371         $next      = $winner;
1372         $firstcard = ''; /* new trick, no first card */
1373       }
1374     else
1375       {
1376         $next = $pos+1;
1377         if($next==5) $next = 1;
1378       }
1379
1380     /* my turn?, display cards as links, ask for comments*/
1381     if(DB_get_pos_by_hash($me) == $next)
1382       $myturn = 1;
1383     else
1384       $myturn = 0;
1385
1386     /* do we want to play a card? */
1387     if(myisset('card') && $myturn)
1388       {
1389         $card   = $_REQUEST['card'];
1390         $handid = DB_get_handid('hash',$me);
1391         $commentSchweinchen =''; /* used to add a comment when Schweinchen is being played */
1392
1393         /* check if we have card and that we haven't played it yet*/
1394         /* set played in hand_card to true where hand_id and card_id*/
1395         $r = DB_query_array("SELECT id FROM Hand_Card WHERE played='false' and ".
1396                               "hand_id='$handid' AND card_id=".DB_quote_smart($card));
1397         $handcardid = $r[0];
1398
1399         if($handcardid) /* everything ok, play card  */
1400           {
1401             /* update Game timestamp */
1402             DB_update_game_timestamp($gameid);
1403
1404             /* mark card as played */
1405             DB_query("UPDATE Hand_Card SET played='true' WHERE hand_id='$handid' AND card_id=".
1406                      DB_quote_smart($card));
1407
1408             /* get trick id or start new trick */
1409             $a = DB_get_current_trickid($gameid);
1410             $trickid  = $a[0];
1411             $sequence = $a[1];
1412             $tricknr  = $a[2];
1413
1414             $playid = DB_play_card($trickid,$handcardid,$sequence);
1415
1416             /* check special output for schweinchen in case in case a fox is being played
1417              * check for correct rules, etc. has already been done
1418              */
1419             if( $GAME['schweinchen-who'] && ($card == 19 || $card == 20) )
1420               {
1421                 if(!$GAME['schweinchen-first'])
1422                   $GAME['schweinchen-first'] = 1; /* playing the first fox */
1423                 else
1424                   $GAME['schweinchen-second'] = 1; /* this must be the second fox */
1425
1426                 if( $RULES['schweinchen']=='both' ||
1427                     ($RULES['schweinchen']=='second' && $GAME['schweinchen-second']==1 )||
1428                     ($RULES['schweinchen']=='secondaftercall' && $GAME['schweinchen-second']==1 &&
1429                      (DB_get_call_by_hash($GAME['schweinchen-who']) || DB_get_partner_call_by_hash($GAME['schweinchen-who']) ))
1430                   )
1431                   {
1432                     DB_insert_comment('Schweinchen! ',$playid,$myid);
1433                     $commentSchweinchen = 'Schweinchen! ';
1434                   }
1435                 if ($debug)
1436                   echo 'schweinchen = '.$GAME['schweinchen-who'].' ---<br />';
1437               }
1438
1439             /* if sequence == 4 check who one in case of wedding */
1440             if($sequence == 4 && $GT == 'wedding')
1441               {
1442                 /* is wedding resolve */
1443                 $resolved = DB_get_sickness_by_gameid($gameid);
1444                 if($resolved<0)
1445                   {
1446                     /* who has wedding */
1447                     $userids = DB_get_all_userid_by_gameid($gameid);
1448                     foreach($userids as $user)
1449                       {
1450                         $usersick = DB_get_sickness_by_userid_and_gameid($user,$gameid);
1451                         if($usersick == 'wedding')
1452                           $whosick = $user;
1453                       }
1454                     /* who won the trick */
1455                     $play     = DB_get_cards_by_trick($trickid);
1456                     $winner   = get_winner($play,$gametype); /* returns the position */
1457                     $winnerid = DB_get_userid('gameid-position',$gameid,$winner);
1458                     /* is tricknr <=3 */
1459                     if($tricknr <=3 && $winnerid!=$whosick)
1460                       {
1461                         /* set resolved at tricknr*/
1462                         $resolved = DB_set_sickness_by_gameid($gameid,$tricknr);
1463                         /* set partner */
1464                         $whash = DB_get_hash_from_gameid_and_userid($gameid,$winnerid);
1465                         DB_set_party_by_hash($whash,'re');
1466                       }
1467                     if($tricknr == 3 && $winnerid==$whosick)
1468                       {
1469                         /* set resolved at tricknr*/
1470                         $resolved = DB_set_sickness_by_gameid($gameid,'3');
1471                       }
1472                   }
1473               }
1474
1475             /* if sequence == 4, set winner of the trick, count points and set the next player */
1476             if($sequence==4)
1477               {
1478                 $play   = DB_get_cards_by_trick($trickid);
1479                 $winner = get_winner($play,$gametype); /* returns the position */
1480
1481                 /*
1482                  * check if someone caught a fox
1483                  *******************************/
1484
1485                 /* first check if we should account for solos at all,
1486                  * since it doesn't make sense in some games
1487                  */
1488                 $ok = 0; /* fox shouldn't be counted */
1489                 if(DB_get_gametype_by_gameid($gameid)=='solo')
1490                   {
1491                     $solo = DB_get_solo_by_gameid($gameid);
1492                     if($solo == 'trump' || $solo == 'silent')
1493                       $ok = 1; /* for trump solos and silent solos, foxes are ok */
1494                   }
1495                 else
1496                   $ok = 1; /* for all other games (not solos) foxes are ok too */
1497
1498                 if($ok==1)
1499                   foreach($play as $played)
1500                     {
1501                       if ( $played['card']==19 || $played['card']==20 )
1502                         if ($played['pos']!= $winner )
1503                           {
1504                             /* possible caught a fox, check party */
1505                             $uid1 = DB_get_userid('gameid-position',$gameid,$winner);
1506                             $uid2 = DB_get_userid('gameid-position',$gameid,$played['pos']);
1507
1508                             $party1 = DB_get_party_by_gameid_and_userid($gameid,$uid1);
1509                             $party2 = DB_get_party_by_gameid_and_userid($gameid,$uid2);
1510
1511                             if($party1 != $party2)
1512                               DB_query("INSERT INTO Score".
1513                                        " VALUES( NULL,NULL,$gameid,'$party1',$uid1,$uid2,'fox')");
1514                           }
1515                     }
1516
1517                 /*
1518                  * check for karlchen (jack of clubs in the last trick)
1519                  ******************************************************/
1520
1521                 /* same as for foxes, karlchen doesn't always make sense
1522                  * check what kind of game it is and set karlchen accordingly */
1523
1524                 if($tricknr == 12 ) /* Karlchen works only in the last trick */
1525                   {
1526                     /* check for solo */
1527                     $solo = 'none';
1528                     if(DB_get_gametype_by_gameid($gameid)=='solo' )
1529                       $solo = DB_get_solo_by_gameid($gameid);
1530
1531                     /* no Karlchen in these solos */
1532                     if($solo != 'trumpless' && $solo != 'jack' && $solo != 'queen' )
1533                       {
1534                         foreach($play as $played)
1535                           if ( $played['card']==11 || $played['card']==12 )
1536                             if ($played['pos'] == $winner )
1537                               {
1538                                 /* save Karlchen */
1539                                 $uid1   = DB_get_userid('gameid-position',$gameid,$winner);
1540                                 $party1 = DB_get_party_by_gameid_and_userid($gameid,$uid1);
1541
1542                                 DB_query("INSERT INTO Score".
1543                                          " VALUES( NULL,NULL,$gameid,'$party1',$uid1,NULL,'karlchen')");
1544                               };
1545                       };
1546                   }; /* end scoring Karlchen */
1547
1548                 /*
1549                  * check for doppelopf (>40 points)
1550                  ***********************************/
1551
1552                 $points = 0;
1553                 foreach($play as $played)
1554                   {
1555                     $points += DB_get_card_value_by_cardid($played['card']);
1556                   }
1557                 if($points > 39)
1558                   {
1559                     $uid1   = DB_get_userid('gameid-position',$gameid,$winner);
1560                     $party1 = DB_get_party_by_gameid_and_userid($gameid,$uid1);
1561
1562                     DB_query("INSERT INTO Score".
1563                              " VALUES( NULL,NULL,$gameid,'$party1',$uid1,NULL,'doko')");
1564                   }
1565
1566                 /*
1567                  * set winner (for this trick)
1568                  */
1569
1570                 if($winner>0)
1571                   DB_query("UPDATE Trick SET winner='$winner' WHERE id='$trickid'");
1572                 else
1573                   echo "ERROR during scoring";
1574
1575                 if($debug)
1576                   echo "DEBUG: position $winner won the trick <br />";
1577
1578                 /* who is the next player? */
1579                 $next = $winner;
1580               }
1581             else
1582               {
1583                 $next = DB_get_pos_by_hash($me)+1;
1584               }
1585             if($next==5) $next=1;
1586
1587             /* check for coment */
1588             if(myisset('comment'))
1589               {
1590                 $comment = $_REQUEST['comment'];
1591                 if($comment != '')
1592                   DB_insert_comment($comment,$playid,$myid);
1593                 if($commentSchweinchen)
1594                   $comment = $commentSchweinchen . $comment;
1595               };
1596
1597             /* display played card */
1598             $pos = DB_get_pos_by_hash($me);
1599             if($sequence==1)
1600               {
1601                 echo "  <li onclick=\"hl('".($tricknr)."');\" class=\"current\"><a href=\"#\">"._('Trick').' '.($tricknr)."</a>\n".
1602                   "    <div class=\"trick\" id=\"trick".($tricknr)."\">\n".
1603                   "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
1604               }
1605
1606             echo "      <div class=\"card".($pos-1)."\">\n        ";
1607
1608             /* display comments */
1609             display_card($card,$PREF['cardset']);
1610             if($comment!='')
1611               echo "\n        <span class=\"comment\"> ".$comment."</span>\n";
1612             echo "      </div>\n";
1613
1614             echo "    </div>\n  </li>\n";  /* end div trick, end li trick */
1615
1616             /*check if we still have cards left, else set status to gameover */
1617             if(sizeof(DB_get_hand($me))==0)
1618               {
1619                 DB_set_hand_status_by_hash($me,'gameover');
1620                 $mystatus = 'gameover';
1621               }
1622
1623             /* if all players are done, set game status to game over,
1624              * get the points of the last trick and send out an email
1625              * to all players
1626              */
1627             $userids = DB_get_all_userid_by_gameid($gameid);
1628
1629             $done=1;
1630             foreach($userids as $user)
1631               if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='gameover')
1632                 $done=0;
1633
1634             if($done)
1635               DB_set_game_status_by_gameid($gameid,'gameover');
1636
1637             /* email next player, if game is still running */
1638             if(DB_get_game_status_by_gameid($gameid)=='play')
1639               {
1640                 $next_hash = DB_get_hash_from_game_and_pos($gameid,$next);
1641                 $who       = DB_get_userid('hash',$next_hash);
1642                 DB_set_player_by_gameid($gameid,$who);
1643
1644                 $message = "A card has been played in game ".DB_format_gameid($gameid).".\n\n".
1645                   "It's your turn  now.\n".
1646                   "Use this link to play a card: ".$HOST.$INDEX."?action=game&me=".$next_hash."\n\n" ;
1647                 if( DB_get_email_pref_by_uid($who)!='emailaddict' )
1648                   {
1649                     mymail($who,$gameid, GAME_YOUR_TURN, $message);
1650                   }
1651               }
1652             else /* send out final email */
1653               {
1654                 /* individual score */
1655                 $result = DB_query("SELECT User.fullname, IFNULL(SUM(Card.points),0), Hand.party FROM Hand".
1656                                    " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1657                                    " LEFT JOIN User ON User.id=Hand.user_id".
1658                                    " LEFT JOIN Play ON Trick.id=Play.trick_id".
1659                                    " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1660                                    " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1661                                    " WHERE Hand.game_id='$gameid'".
1662                                    " GROUP BY User.fullname" );
1663                 $message  = "The game is over. Thanks for playing :)\n";
1664                 $message .= "Final score:\n";
1665                 while( $r = DB_fetch_array($result) )
1666                   $message .= "   ".$r[0]."(".$r[2].") ".$r[1]."\n";
1667
1668                 $result = DB_query("SELECT  Hand.party, IFNULL(SUM(Card.points),0) FROM Hand".
1669                                    " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1670                                    " LEFT JOIN User ON User.id=Hand.user_id".
1671                                    " LEFT JOIN Play ON Trick.id=Play.trick_id".
1672                                    " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1673                                    " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1674                                    " WHERE Hand.game_id='$gameid'".
1675                                    " GROUP BY Hand.party" );
1676                 $message .= "\nTotals:\n";
1677                 $re     = 0;
1678                 $contra = 0;
1679                 while( $r = DB_fetch_array($result) )
1680                   {
1681                     $message .= "    ".$r[0]." ".$r[1]."\n";
1682                     if($r[0] == 're')
1683                       $re = $r[1];
1684                     else if($r[0] == 'contra')
1685                       $contra = $r[1];
1686                   }
1687
1688                 /*
1689                  * save score in database
1690                  *
1691                  */
1692
1693                 /* get calls from re/contra */
1694                 $call_re     = -1;
1695                 $call_contra = -1;
1696                 foreach($userids as $user)
1697                   {
1698                     $hash  = DB_get_hash_from_gameid_and_userid($gameid,$user);
1699                     $call  = DB_get_call_by_hash($hash);
1700                     $party = DB_get_party_by_hash($hash);
1701
1702                     if($call!=NULL)
1703                       {
1704                         $call = (int) $call;
1705
1706                         if($party=='re')
1707                           {
1708                             if($call_re== -1)
1709                               $call_re = $call;
1710                             else if( $call < $call_re)
1711                               $call_re = $call;
1712                           }
1713                         else if($party=='contra')
1714                           {
1715                             if($call_contra== -1)
1716                               $call_contra = $call;
1717                             else if( $call < $call_contra)
1718                               $call_contra = $call;
1719                           }
1720                       }
1721                   }
1722
1723                 /* figure out who one */
1724                 $winning_party = NULL;
1725
1726                 if($call_re == -1 && $call_contra == -1)
1727                   {
1728                     /* nobody made a call, so it's easy to figure out who won */
1729                     if($re>120)
1730                       $winning_party='re';
1731                     else
1732                       $winning_party='contra';
1733                   }
1734                 else
1735                   {
1736                     /* if one party makes a call, they only win, iff they make enough points
1737                      * if only one party made a call, the other one wins,
1738                      * if the first one didn't make it
1739                      */
1740                     if($call_re != -1)
1741                       {
1742                         $offset = 120 - $call_re;
1743                         if($call_re == 0)
1744                           $offset--; /* since we use a > in the next equation */
1745
1746                         if($re > 120+$offset)
1747                           $winning_party='re';
1748                         else if ($call_contra == -1 )
1749                           $winning_party='contra';
1750                       }
1751
1752                     if($call_contra != -1)
1753                       {
1754                         $offset = 120 - $call_contra;
1755                         if($call_contra == 0)
1756                           $offset--; /* since we use a > in the next equation */
1757
1758                         if($contra > 120+$offset)
1759                           $winning_party='contra';
1760                         else if ($call_re == -1 )
1761                           $winning_party='re';
1762                       }
1763                   }
1764
1765                 /* one point for each call of the other party in case the other party didn't win
1766                  * and one point each in case the party made more than points than one of the calls
1767                  */
1768                 if($winning_party!='contra' && $call_contra!= -1)
1769                   {
1770                     for( $p=$call_contra;$p<=120; $p+=30 )
1771                       {
1772                           DB_query("INSERT INTO Score".
1773                                    " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'against$p')");
1774                         }
1775
1776                       for( $p=$call_contra; $p<120; $p+=30)
1777                         {
1778                           if( $re >= $p )
1779                             DB_query("INSERT INTO Score".
1780                                      " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'made$p')");
1781                         }
1782                     }
1783                   if($winning_party!='re' and $call_re!= -1)
1784                     {
1785                       for( $p=$call_re;$p<=120; $p+=30 )
1786                         {
1787                           DB_query("INSERT INTO Score".
1788                                    " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'against$p')");
1789                         }
1790
1791                       for( $p=$call_re; $p<120; $p+=30)
1792                         {
1793                           if( $contra>=$p )
1794                             DB_query("INSERT INTO Score".
1795                                      " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'made$p')");
1796                         }
1797                     }
1798
1799                   /* point in case contra won */
1800                   if($winning_party=='contra')
1801                     {
1802                       DB_query("INSERT INTO Score".
1803                                " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'againstqueens')");
1804                     }
1805
1806                   /* one point each for winning and each 30 points + calls */
1807                   if($winning_party=='re')
1808                     {
1809                       foreach(array(120,150,180,210,240) as $p)
1810                         {
1811                           $offset = 0;
1812                           if($p==240 || $call_contra != -1)
1813                             $offset = 1;
1814
1815                           if($re>$p-$offset)
1816                             DB_query("INSERT INTO Score".
1817                                      " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'".(240-$p)."')");
1818                         }
1819                       /* re called something and won */
1820                       foreach(array(0,30,60,90,120) as $p)
1821                         {
1822                           if($call_re!= -1 && $call_re<$p+1)
1823                             DB_query("INSERT INTO Score".
1824                                      " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'call$p')");
1825                         }
1826                     }
1827                   else if( $winning_party=='contra')
1828                     {
1829                       foreach(array(120,150,180,210,240) as $p)
1830                         {
1831                           $offset = 0;
1832                           if($p==240 || $call_re != -1)
1833                             $offset = 1;
1834
1835                           if($contra>$p-$offset)
1836                             DB_query("INSERT INTO Score".
1837                                      " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'".(240-$p)."')");
1838                         }
1839                       /* re called something and won */
1840                       foreach(array(0,30,60,90,120) as $p)
1841                         {
1842                           if($call_contra != -1 && $call_contra<$p+1)
1843                             DB_query("INSERT INTO Score".
1844                                      " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'call$p')");
1845                         }
1846                     }
1847
1848
1849                   /* add score points to email */
1850                   $message .= "\n";
1851                   $Tpoint = 0;
1852                   $message .= " Points Re: \n";
1853                   $queryresult = DB_query("SELECT score FROM Score ".
1854                                           "  WHERE game_id=$gameid AND party='re'".
1855                                           " ");
1856                   while($r = DB_fetch_array($queryresult) )
1857                     {
1858                       $message .= "   ".$r[0]."\n";
1859                       $Tpoint ++;
1860                     }
1861                   $message .= " Points Contra: \n";
1862                   $queryresult = DB_query("SELECT score FROM Score ".
1863                                           "  WHERE game_id=$gameid AND party='contra'".
1864                                           " ");
1865                   while($r = DB_fetch_array($queryresult) )
1866                     {
1867                       $message .= "   ".$r[0]."\n";
1868                       $Tpoint --;
1869                     }
1870                   $message .= " Total Points (from the Re point of view): $Tpoint\n";
1871                   $message .= "\n";
1872
1873                   $session = DB_get_session_by_gameid($gameid);
1874                   $score = generate_score_table($session);
1875
1876                   $message .= "Score Table:\n";
1877                   $message .= format_score_table_ascii($score);
1878                   $message .= "\nUse these links to have a look at game ".DB_format_gameid($gameid).": \n";
1879
1880                   /* send out final email */
1881                   foreach($userids as $user)
1882                     {
1883                       /* add links for all players */
1884                       $hash = DB_get_hash_from_gameid_and_userid($gameid,$user);
1885                       $name = DB_get_name('userid',$user);
1886
1887                       $link = "$name: ".$HOST.$INDEX."?action=game&me=".$hash."\n" ;
1888                       $message .= $link;
1889                     }
1890                   $message .= "\n\n (you can use reply all on this email to reach all the players.)\n\n";
1891                   mymail($userids,$gameid, GAME_OVER, $message);
1892               }
1893           }
1894         else
1895           {
1896             echo "can't find that card?! <br />\n";
1897           }
1898       }
1899     else if(myisset('card') && !$myturn )
1900       {
1901         echo _("please wait until it's your turn!")."<br />\n";
1902       }
1903
1904     if($seq!=4 && $trickNR>=1 && !(myisset('card') && $myturn) )
1905       echo "    </div>\n  </li>\n";  /* end div trick, end li trick */
1906
1907     /* display points in case game is over */
1908     if($mystatus=='gameover' && DB_get_game_status_by_gameid($gameid)=='gameover' )
1909       {
1910         echo "  <li onclick=\"hl('13');\" class=\"current\"><a href=\"#\">"._('Score')."</a>\n".
1911           "    <div class=\"trick\" id=\"trick13\">\n";
1912         /* add pic for re/contra
1913          "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";*/
1914
1915         $result = DB_query("SELECT User.fullname, IFNULL(SUM(Card.points),0), Hand.party,Hand.position FROM Hand".
1916                            " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1917                            " LEFT JOIN User ON User.id=Hand.user_id".
1918                            " LEFT JOIN Play ON Trick.id=Play.trick_id".
1919                            " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1920                            " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1921                            " WHERE Hand.game_id='$gameid'".
1922                            " GROUP BY User.fullname" );
1923         while( $r = DB_fetch_array($result))
1924           echo "      <div class=\"card".($r[3]-1)."\">\n".
1925             "        <div class=\"score\">".$r[2]."<br /> ".$r[1]."</div>\n".
1926             "      </div>\n";
1927
1928         /* display totals */
1929         $result = DB_query("SELECT Hand.party, IFNULL(SUM(Card.points),0) FROM Hand".
1930                            " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1931                            " LEFT JOIN User ON User.id=Hand.user_id".
1932                            " LEFT JOIN Play ON Trick.id=Play.trick_id".
1933                            " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1934                            " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1935                            " WHERE Hand.game_id='$gameid'".
1936                            " GROUP BY Hand.party" );
1937         echo "<div class=\"total\">\n  Totals:<br />\n";
1938         while( $r = DB_fetch_array($result))
1939           echo "  ".$r[0]." ".$r[1]."<br />\n";
1940
1941         $queryresult = DB_query("SELECT timediff(mod_date,create_date) ".
1942                                 " FROM Game WHERE id='$gameid'");
1943         $r = DB_fetch_array($queryresult);
1944         echo "  <p>This game took ".$r[0]." hours.</p>\n";
1945
1946         echo "  <div class=\"re\">\n   Points Re: <br />\n";
1947         $queryresult = DB_query("SELECT score FROM Score ".
1948                                 "  WHERE game_id=$gameid AND party='re'".
1949                                 " ");
1950         while($r = DB_fetch_array($queryresult) )
1951           echo "   ".$r[0]."<br />\n";
1952         echo "  </div>\n";
1953
1954         echo "  <div class=\"contra\">\n   Points Contra: <br />\n";
1955         $queryresult = DB_query("SELECT score FROM Score ".
1956                                 "  WHERE game_id=$gameid AND party='contra'".
1957                                 " ");
1958         while($r = DB_fetch_array($queryresult) )
1959           echo "   ".$r[0]."<br />\n";
1960         echo "  </div>\n";
1961
1962         echo "</div>\n";
1963
1964         echo "    </div>\n  </li>\n";  /* end div trick, end li trick */
1965       }
1966
1967     echo "  <li onclick=\"hl_prev();\" class=\"old\"><a href=\"#\">"._('prev')."</a></li>\n";
1968     echo "  <li onclick=\"hl_next();\" class=\"old\"><a href=\"#\">"._('next')."</a></li>\n";
1969     echo "</ul>\n"; /* end ul tricks*/
1970
1971     $mycards = DB_get_hand($me);
1972     $mycards = mysort($mycards,$gametype);
1973     echo "<div class=\"mycards\">\n";
1974
1975     if($myturn && !myisset('card') && $mystatus=='play' )
1976       {
1977         echo "Hello ".$myname.", it's your turn!  <br />\n";
1978         echo _('Your cards are').": <br />\n";
1979
1980         /* do we have to follow suite? */
1981         $followsuit = 0;
1982         if(have_suit($mycards,$firstcard))
1983           $followsuit = 1;
1984
1985         /* count how many cards we can play, so that we can pre-select it if there is only one */
1986         $howmanycards = 0;
1987         foreach($mycards as $card)
1988           {
1989             if($howmanycards>1)
1990               break;
1991
1992             /* display only cards that the player is allowed to play as links, the rest just display normal
1993              * also check if we have both schweinchen, in that case only display on of them as playable
1994              */
1995             if( ($followsuit && !same_type($card,$firstcard)) ||
1996                 ( (int)($card)==19 &&
1997                   !$GAME['schweinchen-first'] &&
1998                   ( $RULES['schweinchen']=='second' ||
1999                     ( $RULES['schweinchen']=='secondaftercall' &&
2000                      (DB_get_call_by_hash($GAME['schweinchen-who']) ||
2001                       DB_get_partner_call_by_hash($GAME['schweinchen-who']) )
2002                     )
2003                   ) &&
2004                   $GAME['schweinchen-who']==$me &&
2005                   in_array($gametype,array('normal','wedding','trump','silent'))
2006                   )
2007                 )
2008               continue;
2009             else
2010               $howmanycards++;
2011           }
2012
2013         if($howmanycards==1)
2014           $howmanycards=1;
2015         else
2016           $howmanycards=0;
2017
2018         foreach($mycards as $card)
2019           {
2020             /* display only cards that the player is allowed to play as links, the rest just display normal
2021              * also check if we have both schweinchen, in that case only display on of them as playable
2022              */
2023             if( ($followsuit && !same_type($card,$firstcard)) ||
2024                 ( (int)($card)==19 &&
2025                   !$GAME['schweinchen-first'] &&
2026                   ( $RULES['schweinchen']=='second' ||
2027                     ( $RULES['schweinchen']=='secondaftercall' &&
2028                      (DB_get_call_by_hash($GAME['schweinchen-who']) ||
2029                       DB_get_partner_call_by_hash($GAME['schweinchen-who']) )
2030                     )
2031                   ) &&
2032                   $GAME['schweinchen-who']==$me &&
2033                   in_array($gametype,array('normal','wedding','trump','silent'))
2034                   )
2035                 )
2036               display_card($card,$PREF['cardset']);
2037             else
2038               display_link_card($card,$PREF['cardset'],$type='card',$selected=$howmanycards);
2039           }
2040       }
2041     else if($mystatus=='play' )
2042       {
2043         echo _('Your cards are').": <br />\n";
2044         foreach($mycards as $card)
2045           display_card($card,$PREF['cardset']);
2046       }
2047     else if($mystatus=='gameover')
2048       {
2049         $oldcards = DB_get_all_hand($me);
2050         $oldcards = mysort($oldcards,$gametype);
2051
2052         if(isset($_SESSION['id']) && $myid==$_SESSION['id'])
2053           echo _('Your cards were').": <br />\n";
2054         else
2055           {
2056             $name = DB_get_name('userid',$myid);
2057             echo "$name's were: <br />\n";
2058           }
2059
2060         foreach($oldcards as $card)
2061           display_card($card,$PREF['cardset']);
2062
2063         $userids = DB_get_all_userid_by_gameid($gameid);
2064         foreach($userids as $user)
2065           {
2066             $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
2067
2068             if($userhash!=$me)
2069               {
2070                 echo "<br />";
2071
2072                 $name = DB_get_name('userid',$user);
2073                 $oldcards = DB_get_all_hand($userhash);
2074                 $oldcards = mysort($oldcards,$gametype);
2075                 echo "$name's cards were: <br />\n";
2076                 foreach($oldcards as $card)
2077                   display_card($card,$PREF['cardset']);
2078               }
2079           };
2080       }
2081     echo "</div>\n";
2082
2083     /* if the game is over do some extra stuff, therefore exit the swtich statement if we are still playing*/
2084     if($mystatus=='play')
2085       break;
2086
2087     /* the following happens only when the gamestatus is 'gameover' */
2088     /* check if game is over, display results */
2089     if(DB_get_game_status_by_gameid($gameid)=='play')
2090       {
2091         echo _('The game is over for you... other people still need to play though');
2092       }
2093     break;
2094   default:
2095     myerror("error in testing the status");
2096   }
2097
2098 /* output other games where it is the users turn
2099  * make sure that the people looking at old games don't see the wrong games here
2100  */
2101 if( $gamestatus != 'gameover' )
2102   {
2103     /* game isn't over, only valid user can get here, so show menu */
2104     display_user_menu($myid);
2105   }
2106 else if(  $origmystatus != 'gameover' )
2107   {
2108     /* user just played the very last card, game is now over, it's still ok to show the menu though */
2109     display_user_menu($myid);
2110   }
2111 else if(  $mystatus == 'gameover' &&
2112           isset($_SESSION['id']) )
2113   {
2114     /* user is looking at someone else's game, show the menu for the correct user */
2115     display_user_menu($_SESSION['id']);
2116   }
2117 else
2118   {
2119     echo "<div class=\"usermenu\">\n";
2120     echo "It's your turn in these games:<br />\n";
2121     echo "Please log in to see this information.\n";
2122     echo "</div>\n";
2123   }
2124
2125 /*
2126  * display gameinfo: re/contra, comment-box, play-card button, games played by others
2127  */
2128
2129 echo "<div class=\"gameinfo\">\n";
2130
2131 /* get time from the last action of the game */
2132 $r = DB_query_array("SELECT mod_date from Game WHERE id='$gameid' " );
2133 $gameend = time() - strtotime($r[0]);
2134
2135 /* comment box */
2136 if($gamestatus == 'play' || $gameend < 60*60*24*7)
2137   {
2138     echo '  '._('A short comment').":<input name=\"comment\" type=\"text\" size=\"20\" maxlength=\"100\" />\n";
2139   }
2140
2141 /* re-contra */
2142 if($gamestatus == 'play' )
2143   {
2144     $myparty = DB_get_party_by_hash($me);
2145     output_form_calls($me,$myparty);
2146   }
2147
2148 /* play-card button */
2149 if($gamestatus == 'play' || $gameend < 60*60*24*7)
2150   {
2151     echo "  <input type=\"submit\" value=\""._('submit')."\" />\n";
2152   }
2153
2154 /* has this hand been played by others? */
2155 $other_game_ids = DB_played_by_others($gameid);
2156 if(sizeof($other_game_ids)>0 && $mystatus=='gameover')
2157   {
2158     $mypos = DB_get_pos_by_hash($me);
2159     echo "  <p>See how other played the same hand: \n";
2160     foreach($other_game_ids as $id)
2161       {
2162         $otherhash = DB_get_hash_from_game_and_pos($id,$mypos);
2163         $othername = DB_get_name('hash',$otherhash);
2164         echo "    <a href=\"$INDEX?action=game&amp;me=$otherhash\">$othername</a> ";
2165       }
2166     echo "  </p>\n";
2167   }
2168
2169 echo "</div>\n"; /* end gameinfo */
2170
2171 /* make sure that we don't show the notes to the wrong person
2172  * (e.g. other people looking at an old game)
2173  */
2174 if( $mystatus != 'gameover' ||
2175     (  $mystatus == 'gameover' &&
2176        isset($_SESSION['id'])  &&
2177        $myid == $_SESSION['id']))
2178   output_user_notes($myid,$gameid,$mystatus);
2179
2180 echo "</form>\n";
2181
2182 $gamestatus = DB_get_game_status_by_gameid($gameid);
2183 if($mystatus=='gameover' &&
2184    ($gamestatus =='gameover' || $gamestatus =='cancel-nines' || $gamestatus =='cancel-trump') &&
2185    isset($_SESSION['id']) && $_SESSION['id']==$myid)
2186   {
2187     $session = DB_get_session_by_gameid($gameid);
2188     $result  = DB_query("SELECT id,create_date FROM Game".
2189                         " WHERE session=$session".
2190                         " ORDER BY create_date DESC".
2191                         " LIMIT 1");
2192     $r = -1;
2193     if($result)
2194       $r = DB_fetch_array($result);
2195
2196     if(!$session || $gameid==$r[0])
2197       {
2198         /* suggest a new game with the same people in it, just rotated once (unless last game was solo) */
2199         $names = DB_get_all_names_by_gameid($gameid);
2200         $type  = DB_get_gametype_by_gameid($gameid);
2201
2202         if($type=='solo')
2203           {
2204             $solo = DB_get_solo_by_gameid($gameid);
2205
2206             if($solo!='silent') /* repeat game with same first player */
2207               output_ask_for_new_game($names[0],$names[1],$names[2],$names[3],$gameid);
2208             else /* rotate normally */
2209               output_ask_for_new_game($names[1],$names[2],$names[3],$names[0],$gameid);
2210           }
2211         else if($gamestatus == 'cancel-nines' || $gamestatus == 'cancel-trump')
2212           output_ask_for_new_game($names[0],$names[1],$names[2],$names[3],$gameid);
2213         else /* rotate normally */
2214           output_ask_for_new_game($names[1],$names[2],$names[3],$names[0],$gameid);
2215       }
2216   }
2217 ?>