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