function doMove()
{
    global $board, $isPromoting, $doUndo, $history, $numMoves;
    /* old PHP versions don't have _POST, _GET and _SESSION as auto_globals */
    if (!minimum_version("4.1.0")) {
        global $_POST, $_GET, $_SESSION;
    }
    /* if moving en-passant */
    /* (ie: if pawn moves diagonally without replacing anything) */
    if (($board[$_POST['fromRow']][$_POST['fromCol']] & COLOR_MASK) == PAWN && $_POST['toCol'] != $_POST['fromCol'] && $board[$_POST['toRow']][$_POST['toCol']] == 0) {
        /* delete eaten pawn */
        $board[$_POST['fromRow']][$_POST['toCol']] = 0;
    }
    /* move piece to destination, replacing whatever's there */
    $board[$_POST['toRow']][$_POST['toCol']] = $board[$_POST['fromRow']][$_POST['fromCol']];
    /* delete piece from old position */
    $board[$_POST['fromRow']][$_POST['fromCol']] = 0;
    /* if not Undoing, but castling */
    if ($doUndo != "yes" && ($board[$_POST['toRow']][$_POST['toCol']] & COLOR_MASK) == KING && $_POST['toCol'] - $_POST['fromCol'] == 2) {
        /* castling to the right, move the right rook to the left side of the king */
        $board[$_POST['toRow']][5] = $board[$_POST['toRow']][7];
        /* delete rook from original position */
        $board[$_POST['toRow']][7] = 0;
    } elseif ($doUndo != "yes" && ($board[$_POST['toRow']][$_POST['toCol']] & COLOR_MASK) == KING && $_POST['fromCol'] - $_POST['toCol'] == 2) {
        /* castling to the left, move the left rook to the right side of the king */
        $board[$_POST['toRow']][3] = $board[$_POST['toRow']][0];
        /* delete rook from original position */
        $board[$_POST['toRow']][0] = 0;
    }
    return true;
}
function doUndo()
{
    global $CFG_TABLE;
    global $board, $numMoves;
    /* old PHP versions don't have _POST, _GET and _SESSION as auto_globals */
    if (!minimum_version("4.1.0")) {
        global $_POST, $_GET, $_SESSION;
    }
    /* get the last move from the history */
    /* NOTE: MySQL currently has no support for subqueries */
    $tmpMaxTime = mysql_query("SELECT Max(timeOfMove) FROM " . $CFG_TABLE[history] . " WHERE gameID = " . $_SESSION['gameID']);
    $maxTime = mysql_result($tmpMaxTime, 0);
    $moves = mysql_query("SELECT * FROM " . $CFG_TABLE[history] . " WHERE gameID = " . $_SESSION['gameID'] . " AND timeOfMove = '{$maxTime}'");
    /* if there actually is a move... */
    if ($lastMove = mysql_fetch_array($moves, MYSQL_ASSOC)) {
        /* if the last move was played by this player */
        /* undo move */
        $fromRow = $lastMove['fromRow'];
        $fromCol = $lastMove['fromCol'];
        $toRow = $lastMove['toRow'];
        $toCol = $lastMove['toCol'];
        $board[$fromRow][$fromCol] = getPieceCode($lastMove['curColor'], $lastMove['curPiece']);
        $board[$toRow][$toCol] = 0;
        /* check for en-passant */
        /* if pawn moves diagonally without replacing a piece, it's en passant */
        if ($lastMove['curPiece'] == "pawn" && $toCol != $fromCol && is_null($lastMove['replaced'])) {
            if ($lastMove['curColor'] == "black") {
                $board[$fromRow][$toCol] = getPieceCode("white", "pawn");
            } else {
                $board[$fromRow][$toCol] = getPieceCode("black", "pawn");
            }
        }
        /* check for castling */
        if (($board[$fromRow][$fromCol] & COLOR_MASK) == KING && abs($toCol - $fromCol) == 2) {
            /* move rook back as well */
            if ($toCol - $fromCol == 2) {
                $board[$fromRow][7] = $board[$fromRow][5];
                $board[$fromRow][5] = 0;
            } else {
                $board[$fromRow][0] = $board[$fromRow][3];
                $board[$fromRow][3] = 0;
            }
        }
        /* restore lost piece */
        if (!is_null($lastMove['replaced'])) {
            if ($lastMove['curColor'] == "black") {
                $board[$toRow][$toCol] = getPieceCode("white", $lastMove['replaced']);
            } else {
                $board[$toRow][$toCol] = getPieceCode("black", $lastMove['replaced']);
            }
        }
        /* remove last move from history */
        $numMoves--;
        mysql_query("DELETE FROM " . $CFG_TABLE[history] . " WHERE gameID = " . $_SESSION['gameID'] . " AND timeOfMove = '{$maxTime}'");
        /* else */
        /* output error message */
    }
}
function createNewGame($gameID)
{
    global $CFG_TABLE;
    /* clear history */
    global $numMoves;
    /* old PHP versions don't have _POST, _GET and _SESSION as auto_globals */
    if (!minimum_version("4.1.0")) {
        global $_POST, $_GET, $_SESSION;
    }
    $numMoves = -1;
    mysql_query("DELETE FROM " . $CFG_TABLE[history] . " WHERE gameID = " . $_SESSION['gameID']);
    initBoard();
}
function fixOldPHPVersions()
{
    global $_fixOldPHPVersions;
    if (isset($_fixOldPHPVersions)) {
        return;
    }
    if (!minimum_version("4.1.0")) {
        global $_POST, $_GET, $_SESSION;
        $_POST = createNewHttpVars("POST");
        $_GET = createNewHttpVars("GET");
        //$_SESSION = createNewHttpVars("SESSION");
        if (!isset($HTTP_SESSION_VARS["_SESSION"])) {
            session_register("_SESSION");
        }
    }
    $_fixOldPHPVersions = true;
}
     $_SESSION['playerID'] = -1;
     session_unregister($_SESSION);
     echo "<script>window.location='index.php'</script>";
     exit;
     break;
 case 'InvitePlayer':
     /* prevent multiple pending requests between two players with the same originator */
     #$tmpQuery = "SELECT gameID FROM games WHERE gameMessage = 'playerInvited'";
     #$tmpQuery .= " AND ((messageFrom = 'white' AND whitePlayer = ".$_SESSION['playerID']." AND blackPlayer = ".$_POST['opponent'].")";
     #$tmpQuery .= " OR (messageFrom = 'black' AND whitePlayer = ".$_POST['opponent']." AND blackPlayer = ".$_SESSION['playerID']."))";
     $tmpQuery = "SELECT gameID FROM games WHERE (gameMessage = '' OR gameMessage='playerInvited')";
     $tmpQuery .= "AND ((whitePlayer = " . $_SESSION['playerID'] . " AND blackPlayer= " . $_POST['opponent'] . ")";
     $tmpQuery .= " OR (whitePlayer=" . $_POST['opponent'] . " AND blackPlayer=" . $_SESSION['playerID'] . "))";
     $tmpExistingRequests = mysql_query($tmpQuery);
     if (mysql_num_rows($tmpExistingRequests) == 0) {
         if (!minimum_version("4.2.0")) {
             init_srand();
         }
         if ($_POST['color'] == 'random') {
             $tmpColor = rand(0, 1) == 1 ? "white" : "black";
         } else {
             $tmpColor = $_POST['color'];
         }
         $tmpQuery = "INSERT INTO games (whitePlayer, blackPlayer, gameMessage, messageFrom, dateCreated, lastMove, ratingWhite, ratingBlack,ratingWhiteM, ratingBlackM,oficial,PVBlack,PVWhite) VALUES (";
         if ($tmpColor == 'white') {
             $white = $_SESSION['playerID'];
             $black = $_POST['opponent'];
         } else {
             $white = $_POST['opponent'];
             $black = $_SESSION['playerID'];
         }
function processMessages()
{
    global $CFG_TABLE;
    global $isUndoRequested, $isDrawRequested, $isUndoing, $isGameOver, $isCheckMate, $playersColor, $numMoves, $statusMessage, $CFG_USEEMAILNOTIFICATION;
    /* old PHP versions don't have _POST, _GET and _SESSION as auto_globals */
    if (!minimum_version("4.1.0")) {
        global $_POST, $_GET, $_SESSION;
    }
    if (DEBUG) {
        echo "Entering processMessages()<br>\n";
    }
    $isUndoRequested = false;
    $isGameOver = false;
    /* find out which player (black or white) we are serving */
    /* NOTE: When playing in the same computer $playersColor is always the player who logged in first */
    if (DEBUG) {
        echo "SharedPC..." . $_SESSION['isSharedPC'] . "<br>\n";
    }
    if ($_SESSION['isSharedPC']) {
        // Only the player to move is active in this case
        if (($numMoves == -1 || $numMoves % 2 == 1) && $playersColor == "white" || $numMoves % 2 == 0 && $playersColor == "black") {
            $currentPlayer = $playersColor;
        } else {
            // The player who logged in later is to move
            if ($playersColor == "white") {
                $currentPlayer = "black";
            } else {
                $currentPlayer = "white";
            }
        }
    } else {
        // The players are on different computers
        $currentPlayer = $playersColor;
    }
    if ($currentPlayer == "white") {
        $opponentColor = "black";
    } else {
        $opponentColor = "white";
    }
    /* *********************************************** */
    /* queue user generated (ie: using forms) messages */
    /* *********************************************** */
    if (DEBUG) {
        echo "Processing user generated (ie: form) messages...<br>\n";
    }
    /* queue a request for an undo */
    if ($_POST['requestUndo'] == "yes") {
        /* if the two players are on the same system, execute undo immediately */
        /* NOTE: assumes the two players discussed it live before undoing */
        if ($_SESSION['isSharedPC']) {
            $isUndoing = true;
        } else {
            $tmpQuery = "INSERT INTO " . $CFG_TABLE[messages] . " (gameID, msgType, msgStatus, destination) VALUES (" . $_SESSION['gameID'] . ", 'undo', 'request', '" . $opponentColor . "')";
            mysql_query($tmpQuery);
            // ToDo: Mail an undo request notice to other player??
        }
        updateTimestamp();
    }
    /* queue a request for a draw */
    if ($_POST['requestDraw'] == "yes") {
        /* if the two players are on the same system, execute Draw immediately */
        /* NOTE: assumes the two players discussed it live before declaring the game a draw */
        if ($_SESSION['isSharedPC']) {
            $tmpQuery = "UPDATE " . $CFG_TABLE[games] . " SET gameMessage = 'draw', messageFrom = '" . $currentPlayer . "' WHERE gameID = " . $_SESSION['gameID'];
            mysql_query($tmpQuery);
        } else {
            $tmpQuery = "INSERT INTO " . $CFG_TABLE[messages] . " (gameID, msgType, msgStatus, destination) VALUES (" . $_SESSION['gameID'] . ", 'draw', 'request', '" . $opponentColor . "')";
            mysql_query($tmpQuery);
        }
        updateTimestamp();
    }
    /* response to a request for an undo */
    if (isset($_POST['undoResponse'])) {
        if ($_POST['isUndoResponseDone'] == 'yes') {
            if ($_POST['undoResponse'] == "yes") {
                $tmpStatus = "approved";
                $isUndoing = true;
            } else {
                $tmpStatus = "denied";
            }
            $tmpQuery = "UPDATE " . $CFG_TABLE[messages] . " SET msgStatus = '" . $tmpStatus . "', destination = '" . $opponentColor . "' WHERE gameID = " . $_SESSION['gameID'] . " AND msgType = 'undo' AND msgStatus = 'request' AND destination = '" . $currentPlayer . "'";
            mysql_query($tmpQuery);
            updateTimestamp();
        }
    }
    /* response to a request for a draw */
    if (isset($_POST['drawResponse'])) {
        if ($_POST['isDrawResponseDone'] == 'yes') {
            if ($_POST['drawResponse'] == "yes") {
                $tmpStatus = "approved";
                $tmpQuery = "UPDATE " . $CFG_TABLE[games] . " SET gameMessage = 'draw', messageFrom = '" . $currentPlayer . "' WHERE gameID = " . $_SESSION['gameID'];
                mysql_query($tmpQuery);
            } else {
                $tmpStatus = "denied";
            }
            $tmpQuery = "UPDATE " . $CFG_TABLE[messages] . " SET msgStatus = '" . $tmpStatus . "', destination = '" . $opponentColor . "' WHERE gameID = " . $_SESSION['gameID'] . " AND msgType = 'draw' AND msgStatus = 'request' AND destination = '" . $currentPlayer . "'";
            mysql_query($tmpQuery);
            updateTimestamp();
        }
    }
    /* resign the game */
    if ($_POST['resign'] == "yes") {
        $tmpQuery = "UPDATE " . $CFG_TABLE[games] . " SET gameMessage = 'playerResigned', messageFrom = '" . $currentPlayer . "' WHERE gameID = " . $_SESSION['gameID'];
        mysql_query($tmpQuery);
        updateTimestamp();
        /* if email notification is activated... */
        if ($CFG_USEEMAILNOTIFICATION && !$_SESSION['isSharedPC']) {
            /* get opponent's player ID */
            if ($currentPlayer == 'white') {
                $tmpOpponentID = mysql_query("SELECT blackPlayer FROM " . $CFG_TABLE[games] . " WHERE gameID = " . $_SESSION['gameID']);
            } else {
                $tmpOpponentID = mysql_query("SELECT whitePlayer FROM " . $CFG_TABLE[games] . " WHERE gameID = " . $_SESSION['gameID']);
            }
            $opponentID = mysql_result($tmpOpponentID, 0);
            $tmpOpponentEmail = mysql_query("SELECT value FROM " . $CFG_TABLE[preferences] . " WHERE playerID = " . $opponentID . " AND preference = 'emailNotification'");
            /* if opponent is using email notification... */
            if (mysql_num_rows($tmpOpponentEmail) > 0) {
                $opponentEmail = mysql_result($tmpOpponentEmail, 0);
                if ($opponentEmail != '') {
                    /* notify opponent of resignation via email */
                    webchessMail('resignation', $opponentEmail, '', $_SESSION['nick'], $_SESSION['gameID']);
                }
            }
        }
    }
    /* ******************************************* */
    /* process queued messages (ie: from database) */
    /* ******************************************* */
    $tmpQuery = "SELECT * FROM " . $CFG_TABLE[messages] . " WHERE gameID = " . $_SESSION['gameID'] . " AND destination = '" . $currentPlayer . "'";
    $tmpMessages = mysql_query($tmpQuery);
    while ($tmpMessage = mysql_fetch_array($tmpMessages, MYSQL_ASSOC)) {
        switch ($tmpMessage['msgType']) {
            case 'undo':
                switch ($tmpMessage['msgStatus']) {
                    case 'request':
                        $isUndoRequested = true;
                        break;
                    case 'approved':
                        $tmpQuery = "DELETE FROM " . $CFG_TABLE[messages] . " WHERE gameID = " . $_SESSION['gameID'] . " AND msgType = 'undo' AND msgStatus = 'approved' AND destination = '" . $currentPlayer . "'";
                        mysql_query($tmpQuery);
                        $statusMessage .= "Undo approved";
                        break;
                    case 'denied':
                        $isUndoing = false;
                        $tmpQuery = "DELETE FROM " . $CFG_TABLE[messages] . " WHERE gameID = " . $_SESSION['gameID'] . " AND msgType = 'undo' AND msgStatus = 'denied' AND destination = '" . $currentPlayer . "'";
                        mysql_query($tmpQuery);
                        $statusMessage .= "Undo denied";
                        break;
                }
                break;
            case 'draw':
                switch ($tmpMessage['msgStatus']) {
                    case 'request':
                        $isDrawRequested = true;
                        break;
                    case 'approved':
                        $tmpQuery = "DELETE FROM " . $CFG_TABLE[messages] . " WHERE gameID = " . $_SESSION['gameID'] . " AND msgType = 'draw' AND msgStatus = 'approved' AND destination = '" . $currentPlayer . "'";
                        mysql_query($tmpQuery);
                        $statusMessage .= "Draw approved";
                        break;
                    case 'denied':
                        $tmpQuery = "DELETE FROM " . $CFG_TABLE[messages] . " WHERE gameID = " . $_SESSION['gameID'] . " AND msgType = 'draw' AND msgStatus = 'denied' AND destination = '" . $currentPlayer . "'";
                        mysql_query($tmpQuery);
                        $statusMessage .= "Draw denied";
                        break;
                }
                break;
        }
    }
    /* requests pending */
    $tmpQuery = "SELECT * FROM " . $CFG_TABLE[messages] . " WHERE gameID = " . $_SESSION['gameID'] . " AND msgStatus = 'request' AND destination = '" . $opponentColor . "'";
    $tmpMessages = mysql_query($tmpQuery);
    while ($tmpMessage = mysql_fetch_array($tmpMessages, MYSQL_ASSOC)) {
        switch ($tmpMessage['msgType']) {
            case 'undo':
                $statusMessage .= "Your undo request is pending";
                break;
            case 'draw':
                $statusMessage .= "Your request for a draw is pending";
                break;
        }
    }
    /* game level status: draws, resignations and checkmate */
    /* if checkmate, update games table */
    if ($_POST['isCheckMate'] == 'true') {
        mysql_query("UPDATE " . $CFG_TABLE[games] . " SET gameMessage = 'checkMate', messageFrom = '" . $currentPlayer . "' WHERE gameID = " . $_SESSION['gameID']);
    }
    // ToDo: Mail checkmate notification to opponent
    $tmpQuery = "SELECT gameMessage, messageFrom FROM " . $CFG_TABLE[games] . " WHERE gameID = " . $_SESSION['gameID'];
    $tmpMessages = mysql_query($tmpQuery);
    $tmpMessage = mysql_fetch_array($tmpMessages, MYSQL_ASSOC);
    if ($tmpMessage['gameMessage'] == "draw") {
        $statusMessage .= "Game ended in a draw";
        $isGameOver = true;
    }
    if ($tmpMessage['gameMessage'] == "playerResigned") {
        $statusMessage .= $tmpMessage['messageFrom'] . " has resigned the game";
        $isGameOver = true;
    }
    if ($tmpMessage['gameMessage'] == "checkMate") {
        $statusMessage .= "Checkmate! " . $tmpMessage['messageFrom'] . " has won the game";
        $isGameOver = true;
        $isCheckMate = true;
    }
}
Exemple #7
0
function writeHistory()
{
    global $numMoves;
    /* old PHP versions don't have _POST, _GET and _SESSION as auto_globals */
    if (!minimum_version("4.1.0")) {
        global $_POST, $_GET, $_SESSION;
    }
    /* based on player's preferences, display the history */
    $moves = array();
    // Make sure that $moves is defined
    switch ($_SESSION['pref_history']) {
        case 'verbous':
            $moves = writeVerbousHistory();
            break;
        case 'pgn':
            $moves = writeHistoryPGN();
            break;
    }
    $comma = '';
    echo "var moves = [";
    for ($i = 0; $i < count($moves); $i++) {
        echo $comma;
        if ($i % 4 == 0) {
            // Four moves on each line
            echo "\n";
        }
        echo "['" . $moves[$i][0] . "', '" . $moves[$i][1] . "']";
        $comma = ', ';
    }
    echo "];\n";
}
    function savePromotion()
    {
        global $db,$db_prefix, $history, $numMoves, $is_in_check;

        /* old PHP versions don't have _POST, _GET and _SESSION as auto_globals */
        if (!minimum_version("4.1.0"))
            global $_POST, $_GET, $_SESSION;

        if ($is_in_check)
        {
            $tmpIsInCheck = 1;
            $history[$numMoves]['is_in_check'] = 1;
        }
        else
            $tmpIsInCheck = 0;

        $history[$numMoves]['promotedTo'] = getPieceName($_POST['promotion']);

        $tmpQuery = "UPDATE {$db_prefix}history SET time_of)move=NOW(), promoted_to = '".getPieceName($_POST['promotion'])."', is_in_check = ".$tmpIsInCheck." WHERE game_id = '$game_id' AND timeOfMove = '".$history[$numMoves]['timeOfMove']."'";
        mysql_query($tmpQuery);

        updateTimestamp();

        /* if email notification is activated and move does not result in a pawn's promotion... */
        if ($CFG_USEEMAILNOTIFICATION)
        {
            if ($history[$numMoves]['replaced'] == null)
                $tmpReplaced = '';
            else
                $tmpReplaced = $history[$numMoves]['replaced'];

            /* get opponent's color */
            if (($numMoves == -1) || ($numMoves % 2 == 1))
                $oppColor = "black";
            else
                $oppColor = "white";

            /* get opponent's player ID */
            if ($oppColor == 'white')
                $tmpOpponentID = mysql_query("SELECT white_player FROM games WHERE game_id = ".$_SESSION['game_id']);
            else
                $tmpOpponentID = mysql_query("SELECT black_player FROM games WHERE game_id = ".$_SESSION['game_id']);

            $opponentID = mysql_result($tmpOpponentID, 0);

            /* if opponent is using email notification... */
            $tmpOpponentEmail = mysql_query("SELECT value FROM preferences WHERE playerID = ".$opponentID." AND preference = 'emailNotification'");
            if (mysql_num_rows($tmpOpponentEmail) > 0)
            {
                $opponentEmail = mysql_result($tmpOpponentEmail, 0);
                if ($opponentEmail != '')
                {
                    /* get opponent's nick */
                    $tmpOpponentNick = mysql_query("SELECT firstName FROM {$db_prefix}players WHERE playerID = ".$_SESSION['playerID']);
                    $opponentNick = mysql_result($tmpOpponentNick, 0);

                    /* get opponent's prefered history type */
                    $tmpOpponentHistory = mysql_query("SELECT value FROM preferences WHERE playerID = ".$opponentID." AND preference = 'history'");

                    /* default to PGN */
                    if (mysql_num_rows($tmpOpponentHistory) > 0)
                        $opponentHistory = mysql_result($tmpOpponentHistory, 0);
                    else
                        $opponentHistory = 'pgn';

                    /* notify opponent of move via email */
                    if ($opponentHistory == 'pgn')
                        webchessMail('move', $opponentEmail, moveToPGNString($history[$numMoves]['cur_color'], $history[$numMoves]['curPiece'], $history[$numMoves]['from_row'], $history[$numMoves]['from_col'], $history[$numMoves]['to_row'], $history[$numMoves]['to_col'], $tmpReplaced, $history[$numMoves]['promotedTo'], $is_in_check), $opponentNick);
                    else
                        webchessMail('move', $opponentEmail, moveToVerbousString($history[$numMoves]['cur_color'], $history[$numMoves]['curPiece'], $history[$numMoves]['from_row'], $history[$numMoves]['from_col'], $history[$numMoves]['to_row'], $history[$numMoves]['to_col'], $tmpReplaced, $history[$numMoves]['promotedTo'], $is_in_check), $opponentNick);
                }
            }
        }
    }