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

如何将自制Python文本类游戏嵌入HTML页面?

如何将Python文本类游戏嵌入HTML页面

以下是三种实用方案,覆盖从纯前端到前后端交互的不同场景:

方法1:PyScript(前端直接运行Python)

这是最轻量化的方案,无需后端服务,PyScript允许在HTML中直接编写/运行Python代码,完美适配文本类游戏的需求。

实现步骤

  • 在HTML头部引入PyScript的CDN资源
  • 用<py-script>标签编写游戏逻辑,或通过src引入外部Python文件
  • 借助HTML元素展示游戏文本,Python代码可直接操作DOM

代码示例

<!DOCTYPE html>
<html>
<head>
    <title>Python文本冒险游戏</title>
    <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
    <script defer src="https://pyscript.net/latest/pyscript.js"></script>
</head>
<body>
    <h1>城堡冒险</h1>
    <div id="game-output" style="padding:1rem; border:1px solid #ddd; min-height:200px;"></div>
    <input type="text" id="user-input" placeholder="输入指令,比如'开门'" style="margin-top:1rem; padding:0.5rem;">
    <button id="submit-btn" pys-onClick="handle_input">提交</button>

    <py-script>
        from pyscript import Element

        # 绑定DOM元素
        output_box = Element("game-output")
        input_box = Element("user-input")

        # 游戏状态初始化
        game_data = {"location": "城堡入口", "inventory": []}

        def start_game():
            output_box.write("欢迎来到城堡冒险!你站在城堡入口,面前是一扇厚重的木门。\n输入'开门'进入城堡。")

        def handle_input():
            cmd = input_box.element.value.strip().lower()
            input_box.clear()
            response = ""

            if cmd == "开门":
                if game_data["location"] == "城堡入口":
                    game_data["location"] = "大厅"
                    response = "你推开木门,进入了城堡大厅。桌上放着一把铜钥匙,输入'拿钥匙'获取它。"
                else:
                    response = "你现在不在入口,没法开门!"
            elif cmd == "拿钥匙":
                if game_data["location"] == "大厅" and "铜钥匙" not in game_data["inventory"]:
                    game_data["inventory"].append("铜钥匙")
                    response = f"你拿起了铜钥匙,背包里的物品:{', '.join(game_data['inventory'])}"
                else:
                    response = "这里没有钥匙可拿!"
            elif cmd == "查看":
                response = f"你现在在{game_data['location']},周围环境:{'大厅里有木桌、楼梯' if game_data['location'] == '大厅' else '门外是茂密的森林'}"
            else:
                response = "未知指令,请重新输入!"
            
            output_box.write(response)

        # 启动游戏
        start_game()
    </py-script>
</body>
</html>

方法2:后端Python + WebSocket实时交互

如果游戏逻辑复杂、需要保存用户进度,可采用后端运行游戏、前端通过WebSocket实时通信的方案。

实现步骤

  • 用Python的websockets库搭建后端服务,处理游戏逻辑
  • 前端通过JavaScript的WebSocket API连接后端,发送用户输入并展示游戏输出

代码示例

后端服务(Python)

import asyncio
import websockets

# 存储每个连接的游戏状态
client_states = {}

async def game_handler(websocket):
    # 初始化新用户的游戏状态
    client_states[websocket] = {"location": "城堡入口", "inventory": []}
    await websocket.send("欢迎来到城堡冒险!你站在城堡入口,面前是一扇厚重的木门。\n输入'开门'进入城堡。")

    async for message in websocket:
        cmd = message.strip().lower()
        state = client_states[websocket]
        response = ""

        if cmd == "开门":
            if state["location"] == "城堡入口":
                state["location"] = "大厅"
                response = "你推开木门,进入了城堡大厅。桌上放着一把铜钥匙,输入'拿钥匙'获取它。"
            else:
                response = "你现在不在入口,没法开门!"
        elif cmd == "拿钥匙":
            if state["location"] == "大厅" and "铜钥匙" not in state["inventory"]:
                state["inventory"].append("铜钥匙")
                response = f"你拿起了铜钥匙,背包里的物品:{', '.join(state['inventory'])}"
            else:
                response = "这里没有钥匙可拿!"
        else:
            response = "未知指令,请重新输入!"
        
        await websocket.send(response)

async def main():
    async with websockets.serve(game_handler, "localhost", 8765):
        await asyncio.Future()  # 保持服务运行

if __name__ == "__main__":
    asyncio.run(main())

前端HTML

<!DOCTYPE html>
<html>
<head>
    <title>城堡冒险</title>
</head>
<body>
    <h1>城堡冒险</h1>
    <div id="game-output" style="padding:1rem; border:1px solid #ddd; min-height:200px; overflow-y:auto;"></div>
    <input type="text" id="user-input" placeholder="输入指令" style="margin-top:1rem; padding:0.5rem;">
    <button onclick="sendCmd()">提交</button>

    <script>
        const ws = new WebSocket('ws://localhost:8765');
        const output = document.getElementById('game-output');
        const input = document.getElementById('user-input');

        ws.onmessage = function(event) {
            output.innerHTML += `<p>${event.data}</p>`;
            output.scrollTop = output.scrollHeight;
        };

        function sendCmd() {
            const cmd = input.value.trim();
            if (cmd) {
                ws.send(cmd);
                input.value = '';
            }
        }

        // 回车提交指令
        input.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') sendCmd();
        });
    </script>
</body>
</html>

方法3:Pyodide(Python转WebAssembly)

Pyodide将Python编译为WebAssembly,允许在浏览器中运行完整的Python环境,适合需要依赖第三方Python库的场景。

代码示例

<!DOCTYPE html>
<html>
<head>
    <title>城堡冒险</title>
</head>
<body>
    <h1>城堡冒险</h1>
    <div id="game-output" style="padding:1rem; border:1px solid #ddd; min-height:200px;"></div>
    <input type="text" id="user-input" placeholder="输入指令" style="margin-top:1rem; padding:0.5rem;">
    <button onclick="runCmd()">提交</button>

    <script src="https://cdn.jsdelivr.net/pyodide/v0.25.0/full/pyodide.js"></script>
    <script>
        let pyodide;

        // 初始化Pyodide和游戏逻辑
        async function init() {
            pyodide = await loadPyodide();
            await pyodide.runPython(`
                game_state = {"location": "城堡入口", "inventory": []}

                def start_game():
                    return "欢迎来到城堡冒险!你站在城堡入口,面前是一扇厚重的木门。\\n输入'开门'进入城堡。"

                def process_cmd(cmd):
                    cmd = cmd.strip().lower()
                    response = ""
                    if cmd == "开门":
                        if game_state["location"] == "城堡入口":
                            game_state["location"] = "大厅"
                            response = "你推开木门,进入了城堡大厅。桌上放着一把铜钥匙,输入'拿钥匙'获取它。"
                        else:
                            response = "你现在不在入口,没法开门!"
                    elif cmd == "拿钥匙":
                        if game_state["location"] == "大厅" and "铜钥匙" not in game_state["inventory"]:
                            game_state["inventory"].append("铜钥匙")
                            response = f"你拿起了铜钥匙,背包里的物品:{', '.join(game_state['inventory'])}"
                        else:
                            response = "这里没有钥匙可拿!"
                    else:
                        response = "未知指令,请重新输入!"
                    return response
            `);
            // 显示初始游戏文本
            const init_text = pyodide.runPython("start_game()");
            document.getElementById('game-output').textContent = init_text;
        }

        // 处理用户指令
        async function runCmd() {
            const cmd = document.getElementById('user-input').value.trim();
            if (!cmd) return;
            const response = pyodide.runPython(`process_cmd("${cmd}")`);
            document.getElementById('game-output').textContent = response;
            document.getElementById('user-input').value = '';
        }

        // 启动初始化流程
        init();
    </script>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 05:07:47