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