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