首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 猜單字遊戲完整實作:Session + Ajax 互動版

     編輯:PHP 相關知識

PHP 猜單字遊戲完整實作:Session + Ajax 互動版

本專案示範如何用 PHP + JavaScript (原生 Ajax) 打造一個單字拼字遊戲,包含難度選擇、錯誤次數限制、即時字母狀態更新、重新開始等完整遊戲循環。適合初學者理解 PHP Session 狀態管理與前後端非同步互動。

專案架構

  • 單一檔案:guess.php 包含邏輯、介面、Ajax 端點
  • 狀態管理:$_SESSION 儲存答案、猜測紀錄、剩餘機會
  • 前端互動:原生 XMLHttpRequest,無 jQuery 依賴
  • 單字來源:內建 BSD 授權條款文字,過濾長度 ≥ 5 純字母單字

核心 PHP 邏輯

<?php
session_start();
header('Content-Type: text/html; charset=utf-8');

$url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];

// --- 1. 單字庫建立 ---
function getRandomWord() {
    $text = 'Redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met Redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer Redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution Neither the name of Yii Software LLC nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT INDIRECT INCIDENTAL SPECIAL EXEMPLARY OR CONSEQUENTIAL DAMAGES INCLUDING BUT NOT LIMITED TO PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES LOSS OF USE DATA OR PROFITS OR BUSINESS INTERRUPTION HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY WHETHER IN CONTRACT STRICT LIABILITY OR TORT INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE';
    
    $words = preg_split('/[\s,]+/', $text);
    do {
        $word = strtoupper($words[array_rand($words)]);
    } while (strlen($word) < 5 || !ctype_alpha($word));
    return $word;
}

// --- 2. 遊戲狀態初始化 ---
if (!isset($_SESSION['word'])) {
    $_SESSION['word'] = getRandomWord();
    $_SESSION['guessed'] = str_repeat('_', strlen($_SESSION['word']));
    $_SESSION['wrong'] = 0;
}

// --- 3. Ajax 端點:開始遊戲(設定難度) ---
if (isset($_GET['op']) && $_GET['op'] === 'start') {
    $_SESSION['max_wrong'] = (int)$_GET['k'];
    $_SESSION['wrong'] = 0;
    $_SESSION['guessed'] = str_repeat('_', strlen($_SESSION['word']));
    exit;
}

// --- 4. Ajax 端點:重新開始 ---
if (isset($_GET['restart'])) {
    session_destroy();
    header("Location: $url");
    exit;
}

// --- 5. Ajax 端點:猜字母 ---
if (isset($_GET['op']) && $_GET['op'] === 'ajax') {
    $letter = strtoupper($_GET['k']);
    $word = $_SESSION['word'];
    $guessed = &$_SESSION['guessed'];
    $wrong = &$_SESSION['wrong'];
    $maxWrong = $_SESSION['max_wrong'];

    $found = false;
    for ($i = 0; $i < strlen($word); $i++) {
        if ($word[$i] === $letter && $guessed[$i] === '_') {
            $guessed[$i] = $letter;
            $found = true;
        }
    }

    if (!$found) $wrong++;

    // 回傳格式:guessed_string|status|message
    // status: 0=繼續, 1=勝利, 2=失敗
    $status = 0;
    $msg = '';
    if ($guessed === $word) {
        $status = 1; $msg = '成功!';
    } elseif ($wrong > $maxWrong) {
        $status = 2; $msg = '失敗,答案是 ' . $word;
    }

    echo implode('|', [$guessed, $status, $msg]);
    exit;
}
?>

前端 JavaScript 與 HTML

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>PHP 猜單字遊戲</title>
<style>
.letter-btn { display:inline-block; width:36px; height:36px; line-height:36px; text-align:center; margin:2px; border:1px solid #ccc; border-radius:4px; cursor:pointer; user-select:none; }
.letter-btn.used { background:#eee; color:#999; cursor:default; }
#word-display { font-size:2em; letter-spacing:0.5em; margin:20px 0; font-family:monospace; }
#result { font-size:1.5em; font-weight:bold; margin:10px 0; }
.difficulty { margin:10px 0; }
</style>
</head><body>

<div id="game-area">
<?php if (!isset($_SESSION['max_wrong'])): ?>
    <div class="difficulty">
        <label><input type="radio" name="diff" value="10" onclick="startGame(10)"> 簡單 (可錯 10 次)</label><br>
        <label><input type="radio" name="diff" value="6" onclick="startGame(6)"> 普通 (可錯 6 次)</label><br>
        <label><input type="radio" name="diff" value="3" onclick="startGame(3)"> 困難 (可錯 3 次)</label>
    </div>
<?php else: ?>
    <p>最多可錯 <strong><?php echo $_SESSION['max_wrong']; ?></strong> 次</p>
    <div id="word-display"><?php echo implode(' ', str_split($_SESSION['guessed'])); ?></div>
    <div id="keyboard">
        <?php for ($c = ord('A'); $c <= ord('Z'); $c++): ?>
            <span class="letter-btn" id="btn-<?php echo chr($c); ?>" onclick="guessLetter('<?php echo chr($c); ?>')><?php echo chr($c); ?></span>
        <?php endfor; ?>
    </div>
    <div id="result"></div>
    <p><a href="?restart=1">重新開始</a></p>
<?php endif; ?>
</div>

<script>
function ajax(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) callback(xhr.responseText);
    };
    xhr.send();
}

function startGame(maxWrong) {
    ajax('?op=start&k=' + maxWrong, function() { location.reload(); });
}

function guessLetter(letter) {
    var btn = document.getElementById('btn-' + letter);
    btn.classList.add('used');
    btn.onclick = null; // 禁用重複點擊

    ajax('?op=ajax&k=' + letter, function(resp) {
        var parts = resp.split('|');
        var guessed = parts[0];
        var status = parseInt(parts[1]);
        var msg = parts[2] || '';

        document.getElementById('word-display').textContent = guessed.split('').join(' ');

        if (status === 1) {
            document.getElementById('result').innerHTML = '<span style="color:green">🎉 ' + msg + '</span>';
            disableAllButtons();
        } else if (status === 2) {
            document.getElementById('result').innerHTML = '<span style="color:red">💀 ' + msg + '</span>';
            disableAllButtons();
        }
    });
}

function disableAllButtons() {
    document.querySelectorAll('.letter-btn').forEach(function(btn) {
        btn.classList.add('used');
        btn.onclick = null;
    });
}
</script>
</body></html>

學習重點總結

概念實作位置說明
Session 狀態管理PHP 頂部跨請求保存答案、猜測進度、錯誤計數
單一檔案多入口$_GET['op'] 分派同一檔案處理 HTML 輸出與 Ajax API
原生 AjaxJS ajax() 函式無框架依賴,理解 XMLHttpRequest 基礎
前後端資料協定回傳 guessed|status|msg簡單文字協定,易於除錯擴充
遊戲狀態機PHP 邏輯判斷進行中/勝利/失敗三態轉換

擴充建議

  • 加入單字提示(定義/中文翻譯)
  • 支援中文成語/諺語遊戲(需調整字母按鈕為注音/拼音)
  • 加入排行榜(資料庫儲存最少錯誤/最快完成)
  • 改用 WebSocket 實現即時對戰模式
  • 前端重構為 Vue/React 組件化架構
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved