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