首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Scrum扑克管理项目

用Scrum扑克管理项目
EN

Code Review用户
提问于 2019-09-02 16:28:53
回答 1查看 119关注 0票数 4

我用Laravel写了一个页面,通过使用控制器、模型和Vue.js的刀片语法来管理Scrum扑克的项目。

我的问题是,我在一个file.php文件中编写了实际的Scrum扑克,它是通过表单的onclick事件使用方法加载的。

现在,我想把它分开,在我编写的干净的.php Laravel文件中进行一些重构和实现。我这样做是因为它不能正确获取我的/storage文件夹的每一张图片并创建一个干净的项目。

下面是代码(只有带有/ index.php /decksize/13 6plus1 1或/themes/decksize/6plus 1的带有.only/b.png/std.png的带有单个图片的index.php+图像文件夹)

代码语言:javascript
复制
 array(
        "1" => "[ 0 ]",
        "2" => "[ 1/2 ]",
        "3" => "[ 1 ]",
        "4" => "[ 2 ]",
        "5" => "[ 3 ]",
        "6" => "[ 5 ]",
        "7" => "[ 8 ]",
        "8" => "[ 13 ]",
        "9" => "[ 20 ]",
        "10" => "[ 40 ]",
        "11" => "[ 100 ]",
        "12" => "[ ? ]",
        "13" => "[ C ]",
        // 14 => backside of card
    ),
    '6plus1' => array(
        "1" => "[ 1 ] Piece of cake",
        "2" => "[ 3 ] Hexenwerk",
        "3" => "[ 8 ] Raketenwissenschaft",
        "4" => "[ 100 ] O M G !",
        "5" => "[ ? ] Ich brauche mehr details",
        "6" => "[ C ] Kaffeepause",
        // 7 => backside of card
    ),
);

// will be used to slice the theme.png image into x slices - one per card
define('CARDS_IN_THEME', sizeof($validOptions[$_SESSION['decksize']]) + 1);


function dbg($str)
{
    if (DEBUG) {
        echo $str;
    }
}

// set standard theme if no theme is set
if (!isset($_GET['theme'])) {
    $_GET['theme'] = 'A';
}

// players name matches tablename? == admin
$admin = false;
if (isset($_GET['name']) && isset($_GET['table']) && $_GET['name'] == $_GET['table']) {
    $admin = true;
}

// calculate card width, height and check if theme is available on disk
$offsets = getCardOffset("1", $validOptions[$_SESSION['decksize']], $_GET['theme']);
if (is_array($offsets)) {
    $cardWidth = $offsets[1];
    $placeWidth = 20 + $offsets[1];
    $cardHeight = $offsets[2];
    $placeHeight = 20 + $offsets[2];
} else {
    $cardWidth = 50;
    $placeWidth = 100;
    $cardHeight = 75;
    $placeHeight = 95;
}


// Handle AJAX requests
// new players come here, their cards or ajax-commands to reset the table
if (isset($_GET['table']) && isset($_GET['ajax'])) {
    // tabledata is stored in a file named same as table within /tmp
    // for security - prevent writing to other directories than /tmp by stripping all dots and slashes
    $table = str_replace(array('.', '/'), '', $_GET['table']);

    // create a new game if the player is admin and no game exists
    if (!file_exists(PATH_TO_DATA_FILE . $table) && $admin) {
        touch(PATH_TO_DATA_FILE . $table);
    }

    // stop all players on playing on non existing tables
    // ajax requests to non existing tables stop here
    if (!file_exists(PATH_TO_DATA_FILE . $table)) {
        echo 'Table does not exist.';
        exit;
    }

    // making sure just ONE player fiddles arround with the array on the disk at the same time
    while (!@mkdir(LOCKFILE)) {
        sleep(2);
    }

    // read the tabledata from file
    $filedata = unserialize(file_get_contents(PATH_TO_DATA_FILE . $table));
    if (!is_array($filedata)) {
        $filedata = array();
    }

    // kill the game if requested
    if (isset($_GET['kill']) && $admin) {
        $filedata = array();
        unlink(PATH_TO_DATA_FILE . $table);
        echo "table killed.";
        rmdir(LOCKFILE);
        exit;
    }

    // initiate new game when not done yet
    if (!isset($filedata['table'])) {
        $filedata['table'] = array();
    }
    if (!isset($filedata['history'])) {
        $filedata['history'] = array();
    }
    if (!isset($filedata['message'])) {
        $filedata['message'] = 'Welcome to Scrummy:';
    }

    // split game array in sub parts
    $tabledata = $filedata['table']; // array of the current game (on the red blanket)
    $tabledatahistory = $filedata['history']; // array holding previous game arrays (below the red blanket)
    $players = $filedata['players']; // array holding last seen timestamps for players
    $message = $filedata['message']; // message of the table


    if (isset($_GET['options']) && $_GET['options']) {
        // override message for the table  
        if (strpos($_GET['options'], 'https://it.ly/2NDNWF8') !== false) {
            $_GET['options']
                =
                '' . str_replace(
                    'https://it.ly/2NDNWF8',
                    '',
                    $_GET['options']
                ) . '';
        }
        $filedata['message'] = $_GET['options'];
        $message = $filedata['message'];
        file_put_contents(PATH_TO_DATA_FILE . $table, serialize($filedata));
    }

    // check for user manipulation
    $userIsSpoofingArround = false;
    if (isset($_GET['name']) && isset($_GET['ID']) && $tabledata[$_GET['name']]['ID'] != $_GET['ID']) {
        $userIsSpoofingArround = true;
    }

    if (isset($_GET['name']) && isset($tabledata[$_GET['name']]) && $userIsSpoofingArround) {
        if ((time() - $players[$_GET['name']]) < IDLE_TIMEOUT_DELETE_SECONDS) {
            dbg("[" . $tabledata[$_GET['name']]['ID'] . "] == [" . $_GET['ID'] . "]
");
            echo 'AUTHENTICATION PROBLEM - FRAUD DETECTED!';
            rmdir(LOCKFILE);
            exit;
        } else {
            // user is spoofing another user who idled out. user can take the session
            if ($_GET['ID']) {
                $tabledata[$_GET['name']]['ID'] = $_GET['ID'];
                dbg("updating ID
");
            }
        }
    } else {
        //        echo "[".$tabledata[$_GET['name']]['ID']."] == [".$_GET['ID']."]
";
    }


    // put the current game into the history
    if (isset($_GET['add']) && $admin) {
        $tabledatahistory[] = $tabledata;
        $tabledata = array();
        $filedata['table'] = $tabledata;
        $filedata['history'] = $tabledatahistory;
        file_put_contents(PATH_TO_DATA_FILE . $table, serialize($filedata));
        rmdir(LOCKFILE);
        exit;
    }

    // set a card for a player if all _GET data is valid
    if (
        isset($_GET['guess']) && $_GET['guess'] != '' && isset($_GET['name']) && $_GET['name']
        && isset($tabledata[$_GET['name']])
        && $tabledata[$_GET['name']]['ID'] == $_GET['ID']
    ) {
        if (in_array($_GET['guess'], array_keys($validOptions[$_SESSION['decksize']]))) {
            dbg("saving guess and updating time
");
            $tabledata[$_GET['name']] = array('name' => $_GET['name'], 'guess' => $_GET['guess'], 'ID' => $_GET['ID']);
            $players[$_GET['name']] = time();
        }
    }

    // recognition of new player without a card - prepare slot
    if (isset($_GET['name']) && !isset($tabledata[$_GET['name']]) && isset($_GET['name']) && $_GET['name']) {
        $tabledata[$_GET['name']] = array('name' => $_GET['name'], 'guess' => '...', 'ID' => $_GET['ID']);
        dbg("adding new player with guess ...
");
    }

    // drop ideling players after IDLE_TIMEOUT_SECONDS
    if (isset($_GET['name']) && isset($tabledata[$_GET['name']]) && $_GET['name'] && !$userIsSpoofingArround) {
        $players[$_GET['name']] = time();
        dbg("updating time
");
    }

    // combine history and current game into one array
    $filedata['table'] = $tabledata;
    $filedata['history'] = $tabledatahistory;
    $filedata['players'] = $players;
    $filedata['message'] = $message;

    // write table data to disk
    if (isset($_GET['name']) && $_GET['name']) {
        file_put_contents(PATH_TO_DATA_FILE . $table, serialize($filedata));
        dbg("writing data to disk
");
    }

    // prepare layout of the webpage
    // show all cards
    $showAllCards = true;

    // echo table header with names
    ksort($players);
    $playernames = array();
    if (is_array($players)) {
        $playernames = array_keys($players);
    }

    $totalPlayers = 0;
    $activePlayers = 0;
    $playersOnTable = 0;
    // check if some players did not choose yet
    if (is_array($playernames)) {
        foreach ($playernames as $eachPlayername) {
            $totalPlayers++;
            if ((time() - $players[$eachPlayername]) < IDLE_TIMEOUT_SECONDS) {
                $activePlayers++;
            }
            if ((time() - $players[$eachPlayername]) < IDLE_TIMEOUT_DELETE_SECONDS) {
                $playersOnTable++;
            }
            if (
                $tabledata[$eachPlayername]['guess'] == '...'
                && (time() - $players[$eachPlayername]) < IDLE_TIMEOUT_SECONDS
            ) {
                $showAllCards = false;
            }
        }
    }

    // automatic new row
    if ($showAllCards && $activePlayers > 1) {
        $tabledatahistory[] = $tabledata;
        //$tabledata = array();  <-- will not work - enables session hijacking
        foreach ($tabledata as $username => $userarray) {
            $tabledata[$username]['guess'] = '...';
        }
        $filedata['table'] = $tabledata;
        $filedata['history'] = $tabledatahistory;
        file_put_contents(PATH_TO_DATA_FILE . $table, serialize($filedata));
    }
    rmdir(LOCKFILE);

    echo 'Take A Break(STOP REFRESH)

';
    echo '' . $message . '';

    echo '
     .striped-border {
        border: 1px dashed #000;
        width: 50%;
        margin: auto;
        margin-top: 5%;
        margin-bottom: 5%;
    }
    hr {
        height: 1px;
        color: #123455;
        background-color: #123455;
        border: none;
    }
    .center {
        margin: auto;
        width: 60%;
        border: 15px solid #000000;
        padding: 10px;
        text-align: center
      }
      
     Players On Table: ' . $playersOnTable . "
";


    echo 'Total Player:' . $totalPlayers . "
";
    echo 'Active Players: ' . $activePlayers . "
";
    echo '';
    if (is_array($playernames)) {
        foreach ($playernames as $eachPlayerName) {
            $id = '(' . $tabledata[$eachPlayerName]['ID'] . '/' . $_GET['ID'] . ')';
            $id = '';
            if (time() - $players[$eachPlayerName] < IDLE_TIMEOUT_SECONDS) {
                echo '' . '' . 'Player:' . '' . ' ' . $eachPlayerName . '
' ./*''.hash('sha512',session_id($eachPlayerName)).''.*/ $id
                    . '';
            } elseif (time() - $players[$eachPlayerName] < IDLE_TIMEOUT_DELETE_SECONDS) {
                echo '' . $eachPlayerName . $id
                    . '
INACTIVE';
            }
        }
        echo '';


        // CURRENT TABLE
        echo '';
        foreach ($playernames as $eachPlayerName) {
            $styleaddon = '';

            $ownPlace = (isset($_GET['name']) && $tabledata[$eachPlayerName]['name'] == $_GET['name']);
            $playerPlayedACard = ($tabledata[$eachPlayerName]['guess'] != '...');
            if (time() - $players[$eachPlayerName] < IDLE_TIMEOUT_DELETE_SECONDS) {
                echo '';
                $offsets = getCardOffset($tabledata[$eachPlayerName]['guess'], $validOptions[$_SESSION['decksize']], $_GET['theme']);
                if (is_array($offsets)) {
                    // show nifty cards
                    echo '' . (($showAllCards || ($ownPlace && $playerPlayedACard))
                        ?
                        // show card face up
                        ' '
                        : ($playerPlayedACard
                            ?
                            // show card face down
                            ' '
                            :
                            // show empty place
                            ' ')) . '';

                } else {
                    // theme not found or erroneous - show text cards
                    echo '' . (($showAllCards || ($ownPlace && $playerPlayedACard))
                        ?
                        // show card face up
                        ''
                        . $validOptions[$_SESSION['decksize']][$tabledata[$eachPlayerName]['guess']] . ''
                        : ($playerPlayedACard
                            ?
                            // show card face down
                            ' ')) . '';
                    // ''));
                }
                echo '';
            }
        }
        echo '';

        $tabledatahistory = array_reverse($tabledatahistory);
        // HISTORY
        foreach ($tabledatahistory as $eachHistory) {
            echo '';
            foreach ($playernames as $eachPlayerName) {
                if (time() - $players[$eachPlayerName] < IDLE_TIMEOUT_DELETE_SECONDS) {
                    echo '' . $eachPlayerName . '' . '';
                    $offsets = getCardOffset($eachHistory[$eachPlayerName]['guess'], $validOptions[$_SESSION['decksize']], $_GET['theme']);
                    if (is_array($offsets)) {
                        // show nifty cards
                        echo ' ';
                    } else {
                        // theme not found or erroneous - show text cards
                        echo ''
                            . $validOptions[$_SESSION['decksize']][$eachHistory[$eachPlayerName]['guess']] . '';
                    }
                    echo '';
                }
            }
            echo '';
        }
    }
    // echo '';

    exit;
}
$ID = session_id();


/**
 * @param $guess
 * @param $validOptions
 * @param $theme
 * @return string
 */
function getCardOffset($guess, $validOptions, $theme)
{
    $return = 0;
    $found = false;
    $imageName = 'storage/themes/' . $_SESSION['decksize'] . '/' . str_replace(array('/', '.'), '', $theme) . '.png';

    if (file_exists($imageName)) {
        $img = imagecreatefrompng($imageName);
        if ($img) {
            $width = imagesx($img);
            $cardWidth = $width / CARDS_IN_THEME;
            foreach ($validOptions as $key => $val) {
                if ($guess != $key) {
                    $return -= $cardWidth;
                } else {
                    $found = true;
                    break;
                }
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
    if (!$found) {
        return false;
    }
    return array($return . "px", $cardWidth, imagesy($img), $imageName . '?' . filemtime($imageName));
}

if (!isset($_GET['table'])) {

    $folder = 'themes/' . $_SESSION['decksize'] . '/';
    $otherfolder = 'themes/6plus1' . $_SESSION['secdecksize'] . '/';



    exit;
} else {


    // handle HTML page for the client
    ?>
    

    
        Scrummy

        
        
        
        



        
            body {
                background-color: coral ;
            }

            .card {
                width: <?php echo $cardWidth; ?>px;
                height: <?php echo $cardHeight; ?>px;
                overflow: hidden;
                background-image: url('/storage/images/blank.jpg');
                background-size: <?php echo $cardWidth; ?>px auto;
                border: 0px solid red;
            }

            * {
                font-family: Verdana;
                font-size: 8pt;
            }

            .currentTable {
                border: 0px solid black;
                background-image: url('storage/images/rw.png');
                height: <?php echo $placeHeight; ?>px;
            }

            .historyTable {
                border: 0px solid dotted;
                height: <?php echo $placeHeight; ?>px;
            }

            .place {
                border: 0px solid black;
                overflow: hidden;
                float: left;
                text-align: center;
                width: <?php echo $placeWidth; ?>px;
            }

            .currentTable .place {
                margin-top: 10px;
            }

            .historyTable .place {
                margin-top: 10px;
            }

            .header {
                border: 0px solid black;
                height: 25px;
                clear: both;
            }
        
        
            var TIMEOUT;
            var VALUE = "...";

            function statusCommand(cmd, user, table, options) {
                if (options == undefined) {
                    options = '';
                }
                if (window.XMLHttpRequest) {
                    // code for IE7+, Firefox, Chrome, Opera, Safari
                    xmlhttp = new XMLHttpRequest();
                } else {
                    // code for IE6, IE5
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                xmlhttp.onreadystatechange = function() {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

                    }
                }
                xmlhttp.open("GET", "?ID=<?php echo session_id(); ?>&ajax&name=" + user + "&table=" + table + "&" + cmd + "&options=" + options, true);
                xmlhttp.send();
            }

            function showUser(str, name, table) {
                if (str == "") {
                    document.getElementById("txtHint").innerHTML = "";
                    return;
                }
                if (str != "..." && str != "AUTO") {
                    VALUE = str;
                    document.getElementById("guess").value = "...";
                }
                if (window.XMLHttpRequest) {
                    // code for IE7+, Firefox, Chrome, Opera, Safari
                    xmlhttp = new XMLHttpRequest();
                } else {
                    // code for IE6, IE5
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                xmlhttp.onreadystatechange = function() {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                        document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
                    }
                }
                if (str == "AUTO") {
                    xmlhttp.open("GET", "?theme=<?php echo $_GET['theme']; ?>&ID=<?php echo session_id(); ?>&ajax&table=" + table + "&name=" + name, true);
                } else {
                    xmlhttp.open("GET", "?theme=<?php echo $_GET['theme']; ?>&ID=<?php echo session_id(); ?>&ajax&table=" + table + "&guess=" + str + "&name=" + name, true);
                }
                xmlhttp.send();
                if (document.getElementById("txtHint").innerHTML != "Table does not exist.") {} else {
                    VALUE = "...";
                }
                timeout_init();
            }

            function timeout_init() {
                clearTimeout(TIMEOUT);
                TIMEOUT = setTimeout('showUser("AUTO","<?php echo $_GET['name']; ?>","<?php echo $_GET['table']; ?>")', 2000);
            }

            function initCards() {
                showUser("AUTO", "<?php echo $_GET['name']; ?>", "<?php echo $_GET['table']; ?>");
                timeout_init();
            }
        
    

    
         0; $i--) {
                //echo '';
            }
            //echo '
';
            ?>



        
            
                
                    
                        Select Your Card:
                         $val) {
                                    echo "" . $val . "\n";
                                }
                                ?>
                    


                 $val) {
                            $offsets = getCardOffset($key, $validOptions[$_SESSION['decksize']], $_GET['theme']);
                            echo '';
                            if (is_array($offsets)) {
                                // show nifty cards
                                echo '' .
                                    ' ';
                            } else {
                                // theme not found or erroneous - show text cards
                                echo '' .
                                    // show card face up
                                    ''
                                    . $validOptions[$_SESSION['decksize']][$tabledata[$eachPlayerName]['guess']] . '';
                            }
                            echo '';
                        }
                        echo '
';
                        //    echo 'STOP REFRESH';
                        ?>
            
                
            
        
        

        ' . 'You`re the Scrumleader' . '' . '
';
                ?>
            Reset the current game
            

            New Round? (Adds new game row)
            

        

        Cards are shown here
EN

回答 1

Code Review用户

发布于 2022-01-10 18:22:27

这看起来不像Laravel项目中的典型代码,尽管听起来这就是您正在努力的方向。HTML可以放入刀片模板中,并且大部分逻辑可以进入控制器(如果需要的话可以使用多个控制器)。为了处理$_GET['ajax']请求--这些请求应该有一个单独的路由--无论是在路由/web.php中还是在routes/ajax.php中。

当文件不存在、无法从png文件创建图像或找不到宽度时,函数getCardOffset()似乎返回数组或布尔值。docblock声称它返回一个字符串。

代码语言:javascript
复制
* @return string

应当对其进行相应更新。

代码语言:javascript
复制
* @return array | boolean

变量名$return可能有一个更好的名字--类似$offset或对背景位置有意义的东西。

在JavaScript代码中,变量TIMEOUT以所有大写形式声明。在惯用的JavaScript中,就像许多其他基于c的语言中的情况一样--这是常量的约定,而常量从不被重新分配。const关键字可以用来声明一个永远不会重新赋值的变量,但要记住这并不意味着它是不可变的。

JS函数statusCommand似乎检查是否支持XMLHttpRequest --如果浏览器不支持它,那么它将ActiveXObject用于IE --是否需要支持IE?这是非常罕见的。

此外,该请求的回调似乎是不完整的:

xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4& xmlhttp.status == 200) {}}

票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/227347

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档