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

如何用HTML替换PHP命令行文本冒险游戏中的fgets(STDIN)?

Adapting Your PHP Command-Line Text Adventure to the Browser

Absolutely feasible! I’ve helped folks adapt command-line PHP games to the browser plenty of times—let’s walk through exactly how to replace that fgets(STDIN) interaction and get your adventure running in a web page.

The core difference here is that command-line fgets(STDIN) waits for user input directly in the terminal, while browsers use HTML elements and JavaScript to handle user interaction. You’ve got two solid options depending on whether you want to keep your PHP logic or refactor for the frontend:


Option 1: Refactor Game Logic to JavaScript (Smooth, Client-Side Experience)

For lighter games, moving your logic to JavaScript eliminates backend round-trips and makes interactions feel instant. This is the most common approach for browser-based text adventures.

Step 1: Basic HTML Structure

First, create the UI elements to display game output and capture user input:

<div id="game-output" style="height: 300px; overflow-y: scroll; border: 1px solid #ccc; padding: 10px; margin-bottom: 10px;"></div>
<input type="text" id="user-input" placeholder="Type your choice here..." style="width: 70%; padding: 8px;">
<button id="submit-btn" style="padding: 8px 16px;">Submit</button>

Step 2: JavaScript Game Logic

Replace your PHP’s fgets(STDIN) loop with event listeners that handle user input, and track game state with variables:

// Track game state (replace with your actual game logic)
let gameState = "start";

// Helper function to add text to the game output
function addOutput(text) {
    const outputDiv = document.getElementById("game-output");
    // Format newlines as line breaks for the browser
    const formattedText = text.replace(/\n/g, "<br>");
    outputDiv.innerHTML += `<p>${formattedText}</p>`;
    // Auto-scroll to the latest message
    outputDiv.scrollTop = outputDiv.scrollHeight;
}

// Initialize the game
function startGame() {
    addOutput("Welcome to the Adventure!");
    addOutput("You're standing at a crossroads. Do you go north or south?");
}

// Handle user input
function processInput(userInput) {
    const cleanedInput = userInput.trim().toLowerCase();
    
    switch(gameState) {
        case "start":
            if (cleanedInput === "north") {
                addOutput("You climb a hill and find a hidden cabin!");
                gameState = "cabin";
            } else if (cleanedInput === "south") {
                addOutput("You stumble into a swamp and get stuck. Game over!");
                gameState = "gameOver";
            } else {
                addOutput("Sorry, I don't recognize that command. Try 'north' or 'south'.");
            }
            break;
        case "cabin":
            addOutput("Inside the cabin, you find a chest full of gold. You win!");
            gameState = "gameOver";
            break;
        case "gameOver":
            addOutput("Refresh the page to play again!");
            break;
    }
}

// Bind event listeners for input submission
document.getElementById("submit-btn").addEventListener("click", () => {
    const input = document.getElementById("user-input").value;
    if (input) {
        addOutput(`> ${input}`); // Show the user's input in the output
        processInput(input);
        document.getElementById("user-input").value = ""; // Clear the input box
    }
});

// Allow pressing Enter to submit
document.getElementById("user-input").addEventListener("keypress", (e) => {
    if (e.key === "Enter") {
        document.getElementById("submit-btn").click();
    }
});

// Start the game when the page loads
startGame();

Option 2: Keep PHP Logic with AJAX (For Complex Game Logic)

If your game has intricate PHP logic you don’t want to rewrite, you can use AJAX to send user input to a PHP backend and fetch the game’s response. This uses PHP sessions to track game state between requests.

Step 1: Backend PHP (game.php)

Modify your existing PHP code to handle HTTP requests instead of command-line input:

<?php
session_start(); // Use sessions to persist game state across requests

// Initialize game state if it doesn't exist
if (!isset($_SESSION["gameState"])) {
    $_SESSION["gameState"] = "start";
    echo json_encode([
        "output" => "Welcome to the Adventure!\nYou're at a crossroads. North or south?"
    ]);
    exit;
}

// Get user input from the POST request
$userInput = isset($_POST["input"]) ? trim(strtolower($_POST["input"])) : "";
$response = [];

// Process game logic (replace with your actual code)
switch ($_SESSION["gameState"]) {
    case "start":
        if ($userInput === "north") {
            $response["output"] = "You reach a cabin with a treasure chest!";
            $_SESSION["gameState"] = "cabin";
        } elseif ($userInput === "south") {
            $response["output"] = "A swamp monster grabs you. Game over!";
            $_SESSION["gameState"] = "gameOver";
        } else {
            $response["output"] = "Invalid command. Try 'north' or 'south'.";
        }
        break;
    case "cabin":
        $response["output"] = "You open the chest and win! Congrats!";
        $_SESSION["gameState"] = "gameOver";
        break;
    case "gameOver":
        $response["output"] = "Game over. Refresh to play again.";
        break;
}

echo json_encode($response);
?>

Step 2: Frontend HTML & AJAX

Create the UI and use JavaScript to communicate with the PHP backend:

<div id="game-output" style="height: 300px; overflow-y: scroll; border: 1px solid #ccc; padding: 10px; margin-bottom: 10px;"></div>
<input type="text" id="user-input" placeholder="Type your choice..." style="width: 70%; padding: 8px;">
<button id="submit-btn" style="padding: 8px 16px;">Submit</button>

<script>
function addOutput(text) {
    const outputDiv = document.getElementById("game-output");
    const formattedText = text.replace(/\n/g, "<br>");
    outputDiv.innerHTML += `<p>${formattedText}</p>`;
    outputDiv.scrollTop = outputDiv.scrollHeight;
}

// Fetch initial game state on page load
function initGame() {
    fetch("game.php")
        .then(res => res.json())
        .then(data => addOutput(data.output))
        .catch(err => addOutput(`Error loading game: ${err.message}`));
}

// Send user input to PHP backend
function sendInput(input) {
    if (!input.trim()) return;
    addOutput(`> ${input}`);
    
    fetch("game.php", {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body: `input=${encodeURIComponent(input)}`
    })
    .then(res => res.json())
    .then(data => addOutput(data.output))
    .catch(err => addOutput(`Error sending input: ${err.message}`));
}

// Bind submission events
document.getElementById("submit-btn").addEventListener("click", () => {
    const input = document.getElementById("user-input").value;
    sendInput(input);
    document.getElementById("user-input").value = "";
});

document.getElementById("user-input").addEventListener("keypress", (e) => {
    if (e.key === "Enter") {
        document.getElementById("submit-btn").click();
    }
});

initGame();
</script>

Quick Tips

  • Style the UI: Add CSS to make the game look nicer (e.g., monospace font for output, custom colors).
  • Validate Input: Add checks to handle empty inputs or invalid commands, just like you would in the command line.
  • Save Progress: For longer games, you can use localStorage (frontend) or a database (backend) instead of sessions to persist progress.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:32:19