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