Games_Chess
[ class tree: Games_Chess ] [ index: Games_Chess ] [ all elements ]

Source for file HTMLChess.php

Documentation is available at HTMLChess.php

  1. <?php
  2. require_once 'Games/Chess/Standard.php';
  3. require_once 'Games/Chess/Losers.php';
  4. require_once 'Games/Chess/Crazyhouse.php';
  5.  
  6. if (!version_compare(phpversion()'4.2.0''>=')) {
  7.     die('Requires PHP version 4.2.0 or greater');
  8. }
  9.  
  10. // hack control
  11. if (!isset($_GET['start']|| !is_string($_GET['start'])) {
  12.     $_GET['start''';
  13. }
  14. if (strlen($_GET['start']!= 2{
  15.     $_GET['start''';
  16. elseif ($_GET['start'!= '' && !preg_match('/[a-h][1-8]/'$_GET['start'])) {
  17.     $_GET['start''';
  18. }
  19.  
  20. if (!isset($_GET['goto']|| !is_string($_GET['goto'])) {
  21.     $_GET['goto''';
  22. elseif (strlen($_GET['goto']!= 2{
  23.     $_GET['goto''';
  24. elseif (!preg_match('/[a-h][1-8]/'$_GET['goto'])) {
  25.     $_GET['goto''';
  26. }
  27.  
  28. if (!empty($_GET['promote']&& !in_array($_GET['promote']array('Q''R',
  29.       'N''B'))) {
  30.     $_GET['promote''Q';
  31. }
  32. /**
  33. * Creates the game and maintains persistence through sessions
  34. * Call this at the top of the webpage
  35. @param string name of the session containing the current game
  36. @param string name of the game variable (a {@link visualboard} class)
  37. */
  38. function setup_game($session_id$gamename)
  39. {
  40.     session_name($session_id);
  41.     session_start();
  42.     if (isset($_GET['newgame'])) {
  43.         session_destroy();
  44.     }
  45.     session_name($session_id);
  46.     session_register($gamename);
  47. }
  48.  
  49. /**
  50.  * The primary class - declare one of these at the top of the file
  51.  *
  52.  * Do it like this:
  53.  *
  54.  * <code>
  55.  * setup_game('mygame','x');
  56.  * $x = $_SESSION['x'];
  57.  * if (!isset($x)) $x = new visualboard;
  58.  * </code>
  59.  * @author Greg Beaver <cellog@users.sourceforge.net>
  60.  * @copyright Copyright 2002, Greg Beaver
  61.  * @version 1.0
  62.  */
  63. class visualboard
  64. {
  65.     /**
  66.      * The logical board
  67.      * @var Games_Chess 
  68.      */
  69.     var $_board;
  70.     /**
  71.      * Promotion contents
  72.      * @var false|array
  73.      */
  74.     var $promote = false;
  75.     /**
  76.      * Game type (Standard, Losers, Crazyhouse)
  77.      * @var string 
  78.      */
  79.     var $_type;
  80.     
  81.     /**
  82.      * Initializes {@link $moves, $board}
  83.      */
  84.     function visualboard($fen = false$type 'Standard')
  85.     {
  86.         $board 'Games_Chess_' $type;
  87.         $this->_board = new $board;
  88.         $this->_type $type;
  89.         $err $this->_board->resetGame($fen);
  90.         if ($this->_board->isError($err)) {
  91.             echo '<b>' .$err->getMessage('</b><br />';
  92.             $this->_board->resetGame();
  93.         }
  94.     }
  95.     
  96.     /**
  97.      * Prints javascript for the function addmove:
  98.      * {@source } 
  99.      */
  100.     function javascript()
  101.     {?>
  102. <script language="JavaScript" type="text/javascript">
  103. <!--
  104. function addMove(move, piece)
  105. {
  106.     if (document.forms[0].start.value == '')
  107.     {
  108.         document.forms[0].start.value = move;
  109.         switch (piece)
  110.         {
  111.             case "P" :
  112.             case "Q" :
  113.             case "R" :
  114.             case "B" :
  115.             case "N" :
  116.             case "K" :
  117.             break;
  118.             default :
  119.                 piece = null;
  120.             break;
  121.         }
  122.         document.forms[0].startpiece.value = piece;
  123.     } else
  124.     {
  125.         if (document.forms[0]["goto"].value == '')
  126.         {
  127.             document.forms[0]["goto"].value = move;
  128.             first = document.forms[0].startpiece.value;
  129.             if (first) {
  130.                 if (first == "P") {
  131.                     first = "";
  132.                     if (piece) {
  133.                         first = document.forms[0].start.value.charAt(0) + "x";
  134.                     }
  135.                 } else {
  136.                     if (piece) {
  137.                         first += "x";
  138.                     }
  139.                 }
  140.             }
  141.             if (confirm("Do this move? (" + first + move + ")"))
  142.             {
  143.                 document.forms[0].submit();
  144.             } else {
  145.                 document.forms[0].start.value = '';
  146.                 document.forms[0].startpiece.values = '';
  147.                 document.forms[0]["goto"].value = '';
  148.                 document.forms[0].SAN.value = '';
  149.             }
  150.         }
  151.     }
  152. }
  153.  
  154. function doPlacement(piece)
  155. {
  156.     switch (piece) {
  157.         case "P" :
  158.             name = "Pawn";
  159.         break;
  160.         case "Q" :
  161.             name = "Queen";
  162.         break;
  163.         case "R" :
  164.             name = "Rook";
  165.         break;
  166.         case "B" :
  167.             name = "Bishop";
  168.         break;
  169.         case "N" :
  170.             name = "Knight";
  171.         break;
  172.     }
  173.     square = prompt("Where should the " + name + " be placed (a1-h8, a1 is lower left)?", "e4");
  174.     if (square) {
  175.         document.forms[0].SAN.value = piece + "@" + square;
  176.         document.forms[0].start.value = "";
  177.         document.forms[0]["goto"].value = "";
  178.         if (square.charAt(1) == "<?php echo $this->_board->toMove(== 'W' ? 8 : 1; ?>") {
  179.             if (confirm("promote to Queen?"))
  180.             {
  181.                 document.forms[0].SAN.value += "=Q";
  182.             } else 
  183.             {
  184.                 if (confirm("promote to Rook?"))
  185.                 {
  186.                     document.forms[0].SAN.value += "=R";
  187.                 } else
  188.                 {
  189.                     if (confirm("promote to Knight?"))
  190.                     {
  191.                         document.forms[0].SAN.value += "=N";
  192.                     } else
  193.                     {
  194.                         if (confirm("promote to Bishop?"))
  195.                         {
  196.                             document.forms[0].SAN.value += "=B";
  197.                         } else
  198.                         {
  199.                             document.forms[0].SAN.value += "=Q";
  200.                         }
  201.                     }
  202.                 }
  203.             }
  204.         }
  205.         document.forms[0].submit();
  206.     }
  207. }
  208. //-->
  209. </script>
  210. <?php
  211.     }
  212.  
  213.     function doCaptured($captured)
  214.     {
  215.         $imagepath dirname(__FILE__. DIRECTORY_SEPARATOR . 'images';
  216.         echo '<table border="1">';
  217. //        echo '<tr><td>&nbsp;</td><td colspan="2">White</td><td colspan="2">Black</td></tr>';
  218.         foreach ($captured['W'as $piece => $number{
  219.             echo '<tr><td>';
  220.             if (file_exists($imagepath '/' $piece '.gif')) {
  221.                 $image $piece '.gif';
  222.                 $imgsize = GetImageSize($imagepath . DIRECTORY_SEPARATOR . $image);
  223.                 $click ($this->_board->toMove(== 'W' && $number?
  224.                     '<a href="#" onclick="doPlacement(\'' $piece '\')">' :
  225.                     '';
  226.                 echo $click '<img src="images/' $image '" border="0" width="' $imgsize[0.
  227.                      '" height="' $imgsize[1'" alt="'$piece '">';
  228.                 echo ($click '</a>' '');
  229.             else {
  230.                 echo $piece;
  231.             }
  232.             echo '</td><td>' $number '</td>';
  233.             $number $captured['B'][$piece];
  234.             echo '<td>';
  235.             if (file_exists($imagepath '/' $piece '.gif')) {
  236.                 $image 'dark/' $piece '.gif';
  237.                 $imgsize = GetImageSize($imagepath . DIRECTORY_SEPARATOR . $image);
  238.                 $click ($this->_board->toMove(== 'B' && $number?
  239.                     '<a href="#" onclick="doPlacement(\'' $piece '\')">' :
  240.                     '';
  241.                 echo $click '<img src="images/' $image '" border="0" width="' $imgsize[0.
  242.                      '" height="' $imgsize[1'" alt="'$piece '">';
  243.                 echo ($click '</a>' '');
  244.             else {
  245.                 echo $piece;
  246.             }
  247.             echo '</td><td>' $number '</td></tr>';
  248.         }
  249.         echo '</table>';
  250.     }
  251.  
  252.     /**
  253.      * Grabs the next move from form variables start, goto, kingcastle and queencastle
  254.      *
  255.      * If $_GET['start'] is not used, it checks for $_GET['kingcastle'] and tries
  256.      * to castle kingside if found.  Otherwise, it looks for $_GET['queencastle']
  257.      * and tries to castle queenside
  258.      */
  259.     function domove()
  260.     {
  261.         if (!empty($_GET['from']&& !empty($_GET['to']&& !empty($_GET['promote'])) {
  262.             $err $this->_board->moveSquare($_GET['from']$_GET['to'],
  263.                                              $_GET['promote']);
  264.             if ($this->_board->isError($err)) {
  265.                 echo '<b>' .$err->getMessage('</b><br />';
  266.             }
  267.             $this->promote = false;
  268.             return;
  269.         }
  270.         if (!empty($_GET['SAN'])) {
  271.             $err $this->_board->moveSAN($_GET['SAN']);
  272.             if ($this->_board->isError($err)) {
  273.                 echo '<b>' .$err->getMessage('</b><br />';
  274.             }
  275.             return;
  276.         }
  277.         if (!empty($_GET['start']&& !empty($_GET['goto'])) {
  278.             if ($this->_board->isPromoteMove($_GET['start']$_GET['goto'])) {
  279.                 $this->promote = array($_GET['start']$_GET['goto']);
  280.                 return;
  281.             else {
  282.                 $this->promote = false;
  283.             }
  284.             $err $this->_board->moveSquare($_GET['start']$_GET['goto']);
  285.             if ($this->_board->isError($err)) {
  286.                 echo '<b>' .$err->getMessage('</b><br />';
  287.             }
  288.         elseif (isset($_GET['kingcastle'])) {
  289.             $err $this->_board->moveSAN('O-O');
  290.             if ($this->_board->isError($err)) {
  291.                 echo '<b>' .$err->getMessage('</b><br />';
  292.             }
  293.         elseif (isset($_GET['queencastle'])) {
  294.             $err $this->_board->moveSAN('O-O-O');
  295.             if ($this->_board->isError($err)) {
  296.                 echo '<b>' .$err->getMessage('</b><br />';
  297.             }
  298.         }
  299.     }
  300.     
  301.     /**
  302.      * This function prints the javascript that will ask the user what to promote the pawn to
  303.      *
  304.      * Using the alert() function, this method asks the user if they want a queen.
  305.      * If they click Cancel, it asks if they want a rook, then knight, then
  306.      * bishop.  If they cancel on bishop, it promotes to queen
  307.      * to avoid any illogical possibilities
  308.      */
  309.     function dopromote()
  310.     {
  311.     ?>
  312. <form action="<?php echo $_SERVER['PHP_SELF'].'?'.session_name().'='.session_id(?>" name="chess" id="chess">
  313. <input type="hidden" name="promote" value=""><input type="hidden" name="from" value="">
  314. <input type="hidden" name="to" value="">
  315. <input type="submit" name="newmove" value="New move"></form>
  316. <script language="JavaScript" type="text/javascript">
  317. <!--
  318.  
  319. function promote(from, to)
  320. {
  321.     document.forms[0].from.value = from;
  322.     document.forms[0].to.value = to;
  323.     if (confirm("promote to Queen?"))
  324.     {
  325.         document.forms[0].promote.value = 'Q';
  326.         document.forms[0].submit();
  327.     } else 
  328.     {
  329.         if (confirm("promote to Rook?"))
  330.         {
  331.             document.forms[0].promote.value = 'R';
  332.             document.forms[0].submit();
  333.         } else
  334.         {
  335.             if (confirm("promote to Knight?"))
  336.             {
  337.                 document.forms[0].promote.value = 'N';
  338.                 document.forms[0].submit();
  339.             } else
  340.             {
  341.                 if (confirm("promote to Bishop?"))
  342.                 {
  343.                     document.forms[0].promote.value = 'B';
  344.                     document.forms[0].submit();
  345.                 } else
  346.                 {
  347.                     document.forms[0].promote.value = 'Q';
  348.                     document.forms[0].submit();
  349.                 }
  350.             }
  351.         }
  352.     }
  353. }
  354. promote('<?php print $this->promote[0"', '" $this->promote[1]?>');
  355. //-->
  356. </script>
  357. <?php
  358.     }
  359.     
  360.     /**
  361.     * Print out the chess game in its entirety: the board, move list and control buttons
  362.     *
  363.     * first, it checks for a pawn promotion and adds the promote move to {@link $moves} using
  364.     * {@link game::addpromote()}.  Then it moves the next piece by calling {@link domove()}.
  365.     * Then it checks for stalemate and checkmate, and stops the gameplay if either condition is met.
  366.     * It creates a visual representation of the board using {@link abstractboard::createrows()}, and
  367.     * displays the chessboard by linking together the display of each row on the chessboard using
  368.     * {@link row::draw()}, and finally the movelist using {@link game::draw()}
  369.     */
  370.     function draw()
  371.     {
  372.         $this->domove();
  373.         if ($this->promote)
  374.         {
  375.             return $this->dopromote();
  376.         }
  377.         $board $this->_board->toArray();
  378.         if ($this->_type == 'Crazyhouse'{
  379.             $captured $board['captured'];
  380.             $board $board['board'];
  381.         }
  382.         $checkmate $this->_board->inCheckmate();
  383.         $fen $this->_board->renderFen();
  384.         $colors = array('#999933''#FFFFFF');
  385.         $textcolors = array('#FFFFFF''#000000');
  386.         $cycle = 0;
  387.         if (!$checkmate$this->javascript();
  388.         echo '<table border="1">';
  389.         $imagepath dirname(__FILE__. DIRECTORY_SEPARATOR . 'images';
  390.         foreach($board as $square => $piece{
  391.             if ($square{0== 'a'{
  392.                 echo '<tr>';
  393.                 $cycle ($cycle + 1% 2;
  394.             }
  395.             echo '<td width="30" bgcolor="' .$colors[$cycle]'"><font color="' .$textcolors[$cycle]'">';
  396.             $upperpiece $piece strtoupper($piece: false;
  397.             echo "<a href=\"#\" onClick=\"addMove('$square', '$upperpiece');return false;" .
  398.                 "\" id=\"$square\">";
  399.  
  400.  
  401.             if ($piece{
  402.                 if (file_exists($imagepath '/' strtoupper($piece'.gif')) {
  403.                     if ($piece != strtoupper($piece)) {
  404.                         $image 'dark/' $piece '.gif';
  405.                     else {
  406.                         $image $piece '.gif';
  407.                     }
  408.                     $imgsize = GetImageSize($imagepath . DIRECTORY_SEPARATOR . $image);
  409.                     echo '<img src="images/' $image '" border="0" width="' $imgsize[0.
  410.                          '" height="' $imgsize[1'" alt="'$piece '">';
  411.                 else {
  412.                     echo $piece;
  413.                 }
  414.             else {
  415.                 if (file_exists($imagepath '/blank.gif')) {
  416.                     if ($this->_board->getDiagonalColor($square== 'W'{
  417.                         $image 'blank.gif';
  418.                     else {
  419.                         $image 'dark/blank.gif';
  420.                     }
  421.                     $imgsize = GetImageSize($imagepath . DIRECTORY_SEPARATOR . $image);
  422.                     echo '<img src="images/' $image '" border="0" width="' $imgsize[0.
  423.                          '" height="' $imgsize[1'" alt="'$piece '">';
  424.                 else {
  425.                     echo '&nbsp;';
  426.                 }
  427.             }
  428.             echo '</a>';
  429.             echo '</font></td>';
  430.             if ($square{0== 'h'{
  431.                 echo '</tr>';
  432.             }
  433.             $cycle ($cycle + 1% 2;
  434.         }
  435.         echo '</table>';
  436.  
  437.         $side $this->_board->toMove(== 'W' 'White' 'Black';
  438.         $gameOver $this->_board->gameOver();
  439.         if ($gameOver{
  440.             $winner $gameOver == 'W' 'White' 'Black';
  441.             if ($stalemate $this->_board->inStalemate())
  442.             {
  443.                 print "<h1>STALEMATE</h1>";
  444.             elseif ($draw $this->_board->inDraw())
  445.             {
  446.                 print "<h1>DRAW</h1>";
  447.             elseif ($this->_board->inCheckmate()) {
  448.                 if (!is_a($this->_board'games_chess_standard')) {
  449.                     $winner $side;
  450.                 else {
  451.                     $winner ($side == 'White''Black' 'White';
  452.                 }
  453.                 print "<h1>CHECKMATE! $winner WINS!</h1>";
  454.             else {
  455.                 print "<h1>$winner WINS!</h1>";
  456.             }
  457.         }
  458.  
  459. ?><form action="<?php echo $_SERVER['PHP_SELF'].'?'.session_name().'='.session_id(?>" name="chess" id="chess">
  460. <?php         if (!$gameOverecho "<b>{$side} to move</b><br>";
  461. if (isset($captured)) {
  462.     echo "<b>Crazyhouse captured pieces available for placement:</b><br>";
  463.     $this->doCaptured($captured);
  464. }
  465.  ?><input type="hidden" value="" name="startpiece">
  466. from <input type="text" name="start" size="2" maxlength="2"> to <input type="text" name="goto" size="2" maxlength="2">
  467. <input type="submit" name="newmove" value="New move"><br>
  468. (alternate) SAN move: <input type="text" name="SAN" size="5"><br>
  469. Reset with new FEN: <input type="text" name="FEN" size="70"><br>
  470. <br><input type="reset"><br>
  471. <?php $this->castlebutton()?><br><br>
  472.  
  473. <input type="submit" name="newgame" value="New Game"><input type="submit" name="newlosergame" value="New Losers Game"><input type="submit" name="newcrazyhousegame" value="New Crazyhouse Game"></form><?php if (!$gameOver?>
  474. for a friend to join, click here <a href="mailto:example@example.com?Subject=Join my chess game!&Body=<?php
  475. echo htmlentities("go to <a href=\"http://" $_SERVER['SERVER_NAME'$_SERVER['PHP_SELF'
  476. "?mygame=".session_id()."\">Here</a> to play me in chess! http://$_SERVER[SERVER_NAME]$_SERVER[PHP_SELF]?mygame=" .
  477. session_id())?>">Email my friend</a>
  478.  
  479. <form action="<?php echo $_SERVER['PHP_SELF'].'?'.session_name().'='.session_id(?>">
  480. <input type="submit" value="Check to see if opponent has moved"></form>
  481. <?php }
  482.         
  483.         echo "<blockquote>Current position FEN: <strong>$fen</strong></blockquote>";
  484.         $moves $this->_board->getMoveList(true);
  485.         echo '<table border="1"><th colspan="3" align="center">Moves</th><tr>' .
  486.              '<td>#</td><td>White</td><td>Black</td></tr>';
  487.         foreach($moves as $num => $moveset{
  488.             echo '<tr>';
  489.             echo "<td>$num</td>";
  490.             if (isset($moveset[0])) {
  491.                 echo "<td>$moveset[0]</td>";
  492.             else {
  493.                 echo "<td>&nbsp;</td>";
  494.             }
  495.             
  496.             if (isset($moveset[1])) {
  497.                 echo "<td>$moveset[1]</td>";
  498.             }
  499.             echo '</tr>';
  500.         }
  501.         echo '</table>';
  502.     }
  503.     
  504.     /**
  505.     * Prints the castling buttons after checking castling rights
  506.     *
  507.     * If castling rights have been taken away by a king or rook move, the button is not displayed.  This function
  508.     * uses {@link Games_Chess::canCastleKingside(), Games_Chess::canCastleQueenside()} to find out.
  509.     */
  510.     function castlebutton()
  511.     {
  512.         if ($this->_board->canCastleKingside())
  513.         echo '<input type="submit" name="kingcastle" value="Castle Your King Kingside">';
  514.         if ($this->_board->canCastleQueenside())
  515.         echo '<input type="submit" name="queencastle" value="Castle Your King Queenside">';
  516.     }
  517. }
  518.  
  519. setup_game('mygame','x');
  520. $x $_SESSION['x'];
  521. $fen = isset($_GET['FEN']$_GET['FEN': false;
  522. if (!isset($x|| isset($_GET['newgame']|| $fen
  523.       || isset($_GET['newlosergame']|| isset($_GET['newcrazyhousegame'])) {
  524.     if (isset($_GET['newcrazyhousegame'])) {
  525.         $x = new visualboard($fen'Crazyhouse');
  526.     elseif (isset($_GET['newlosergame'])) {
  527.         $x = new visualboard($fen'Losers');
  528.     else {
  529.         $x = new visualboard($fen'Standard');
  530.     }
  531. }
  532. ?>
  533. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  534.  
  535. <html>
  536. <head>
  537.     <title>PHP Chess!</title>
  538. </head>
  539.  
  540. <body>
  541. <h1>Welcome to <a href="http://www.chiaraquartet.net">The Chiara Quartet's</a> PHP Chess</h1>
  542. <?php
  543. $x->draw();
  544. $_SESSION['x'$x;
  545. ?>
  546.  
  547.  
  548. </body>
  549. </html>

Documentation generated on Mon, 11 Mar 2019 13:52:43 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.