单页多次复用表单:文本冒险游戏输入交互问题求助
文本冒险游戏输入功能修复指南
核心问题定位与修复步骤
1. 修复表单提交按钮
你的表单使用了<input type="button">,这个按钮不会触发表单提交动作,直接导致输入无响应。将其替换为提交按钮:
<input type="submit" value="Let's Go!">
2. 持久化游戏状态(解决单次输入后无后续响应的关键)
HTTP是无状态协议,每次页面刷新时$dwight对象的状态(当前房间、物品栏)会被重置。用PHP Session保存游戏状态:
在dwight.php最顶部开启Session:
session_start();
初始化或恢复游戏对象:
// 确保已引入Game类 if (!isset($_SESSION['game'])) { $dwight = new Game(); // 设置初始状态 $dwight->currRoom = 'the parking lot'; $dwight->currTable = 'parking_lot'; // 替换为你的实际初始表名 $dwight->inventory = []; // 初始化物品映射(根据你的游戏逻辑调整) $dwight->items = ["reception" => "Stapler", "boss_office" => "Toby"]; $_SESSION['game'] = $dwight; } else { $dwight = $_SESSION['game']; }
处理输入后更新Session中的状态:
if(!empty($_POST["inputDirection"])){ $direction = $_POST["inputDirection"]; $dwight->getNextRoom($conn, $direction); $_SESSION['game'] = $dwight; // 保存更新后的游戏状态 }
3. 修正PHP代码语法错误
getDirections方法中有多余的括号,导致逻辑异常:
// 原错误代码:if ($result)) { if ($result) { if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { echo " [" . $row["direction"] . "]"; } } }
4. 优化房间跳转逻辑
每个方向对应唯一目标房间,无需使用while循环,同时完善无效输入提示:
public function getNextRoom($conn, $direction) { $check = "SELECT destination, newtable FROM " . $this->currTable . " WHERE direction=?;"; $stmt = $conn->prepare($check); $stmt->bind_param("s", $direction); $stmt->execute(); $result = $stmt->get_result(); if ($result) { if ($result->num_rows > 0) { $row = $result->fetch_assoc(); $this->currRoom = $row["destination"]; $this->currTable = $row["newtable"]; } else { echo "That's not a valid direction. Try again."; } } else { echo "Database query failed."; } $this->printStatement($conn); }
技术方案选择建议
作为新手,优先使用「传统表单提交 + Session」方案,无需JavaScript基础就能实现持续输入功能,学习成本低。等你熟悉PHP后,再尝试AJAX实现无刷新页面更新。
修正后的dwight.php完整示例
<?php session_start(); $servername = "localhost"; $username = "your_db_user"; $password = "your_db_pass"; $db = "your_db_name"; require_once 'Game.php'; $conn = new mysqli($servername, $username, $password, $db); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // 初始化/恢复游戏状态 if (!isset($_SESSION['game'])) { $dwight = new Game(); $dwight->currRoom = 'the parking lot'; $dwight->currTable = 'parking_lot'; $dwight->inventory = []; $dwight->items = ["reception" => "Stapler", "boss_office" => "Toby"]; $_SESSION['game'] = $dwight; } else { $dwight = $_SESSION['game']; } ?> <div id="main"> <form action="dwight.php" method="POST"> <input type="text" name="inputDirection" placeholder="Where to?"> <input type="submit" value="Let's Go!"> </form> <?php if(!empty($_POST["inputDirection"])){ $direction = $_POST["inputDirection"]; $dwight->getNextRoom($conn, $direction); $_SESSION['game'] = $dwight; } else{ echo "You are in the parking lot. <br> Which direction would you like to go? [north]"; } ?> </div>
内容的提问来源于stack exchange,提问作者FreeKat
相关产品推荐
相关产品推荐

