You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP浏览器卡牌游戏跨玩家同步问题:定时刷新Div方案求助

Hey there! Let's work through this real-time sync issue you're facing with your PHP card game. The root problem here is that PHP is server-side—it generates page content once when the user loads the page, so you can't rely on it alone to update the UI for both players as the game progresses. Your current attempts with meta refresh and jQuery fade don't solve this because they aren't pulling fresh, shared game state from the server. Here's how to fix this step by step:

1. Fix the Game State Storage First

Your biggest immediate issue is that values like the coin flip result are generated fresh every time the page loads—this means two players in the same room might see different results! You need to store all shared game state (like coin flip, turn order, game status) in your database, not just generate it on the fly.

For example, update your startgame logic to save the coin flip to the database instead of generating it every load:

if(isset($_POST['startgame'])) {
    print "<br>Game started.<br>";
    print "heads or tails?<br>";
    print "<form method='post' action='game.php'> 
            <label><input type='text' name='headstails'></label><br> 
            <label><input type='submit' name='select' value='Select'></label><br><br> 
          </form>";
    
    // Generate coin flip once and save to the database
    $flip = rand(1,2);
    $coin = $flip == 1 ? "heads" : "tails";
    $roomnumber = $_SESSION['gamenumber'];
    $query = "UPDATE game{$roomnumber} SET coin_flip = '{$coin}', game_status = 'active'";
    mysqli_query($link, $query);
    
    populatefind($roomnumber);
}

Then, when processing the coin guess, pull the saved result from the database instead of using a new random value:

if(isset($_POST['headstails'])) {
    $roomnumber = $_SESSION['gamenumber'];
    // Get the saved coin flip from the database
    $query = "SELECT coin_flip FROM game{$roomnumber}";
    $result = mysqli_query($link, $query);
    $row = mysqli_fetch_assoc($result);
    $coin = $row['coin_flip'];
    
    $status = "";
    if($_POST['headstails'] == $coin) {
        $status = "find game player goes first";
        $updateQuery = "UPDATE game{$roomnumber} SET current_turn = 'find'";
    } else {
        $status = "host game player goes first";
        $updateQuery = "UPDATE game{$roomnumber} SET current_turn = 'host'";
    }
    mysqli_query($link, $updateQuery);
    
    // Don't print directly here—let AJAX pull this status later
}

2. Use AJAX to Pull Fresh Game State

Instead of refreshing the whole page or flipping existing divs, create a separate PHP script that fetches the latest game state from the database and returns it as HTML. Then use jQuery to periodically call this script and update your game UI.

Step 2.1: Create a get_game_state.php script

This script will generate the latest game UI (including your populatehost/populatefind content and game status messages):

<?php
session_start();
// Connect to your database (reuse your existing $link setup)
$roomnumber = $_SESSION['gamenumber'];
$currentUser = $_SESSION['username']; // Assume you store the logged-in user in session

// Fetch current game state
$query = "SELECT coin_flip, game_status, current_turn, host, find FROM game{$roomnumber}";
$result = mysqli_query($link, $query);
$gameState = mysqli_fetch_assoc($result);

// Build the HTML content
$output = "";

// Add game status messages
if($gameState['game_status'] == 'active' && $gameState['current_turn']) {
    $output .= "<p>{$gameState['current_turn']} game player goes first</p>";
}

// Add the game board using populatehost/populatefind
ob_start(); // Capture output from the populate functions
if($currentUser == $gameState['host']) {
    populatehost($roomnumber);
} else {
    populatefind($roomnumber);
}
$output .= ob_get_clean();

echo $output;
?>

Step 2.2: Update Your Frontend to Use AJAX

Replace your existing jQuery code with this, which will periodically fetch fresh state and update your game div:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(function() {
    // Refresh game state every 3 seconds (adjust as needed)
    setInterval(function() {
        $.get('get_game_state.php', function(freshContent) {
            // Replace the contents of your game div with fresh data
            $('#game-container').html(freshContent);
        });
    }, 3000);
});
</script>

3. Wrap Your Game Content in a Target Div

Make sure all your game UI (room info, board, status messages) is inside a single div that AJAX can update. For example:

// In your hostgame logic
if(isset($_POST['hostgame'])) {
    $roomnumber = rand();
    print $roomnumber;
    insertField($Ausername,$roomnumber);
    $query = "UPDATE game".$roomnumber." SET host='".$Ausername."' WHERE host='null'";
    mysqli_query($link, $query);
    
    // Wrap game content in the target div
    print "<div id='game-container'>";
    populatehost($roomnumber);
    print "</div>";
}

// Do the same for findgame and startgame logic—put all game content inside #game-container

Key Fixes Recap

  • Store shared state in the database: No more random values generated per page load—all players pull the same saved state.
  • AJAX for real-time updates: Periodically fetch fresh UI from the server instead of relying on full page refreshes or client-side only changes.
  • Avoid full page refreshes: The meta refresh is clunky and resets user context—AJAX updates only the game area.

This setup will ensure both players see the same game status (like coin flip results and turn order) as the game progresses.

内容的提问来源于stack exchange,提问作者2316354654

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:54:44