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