This is directed towards the Beginning Coding class
Starter Code
<?php
// Show the initial question and form
echo "You are in a cave. Do you go west or east?<br>";
echo "<form method='post'>";
echo "<input type='text' name='direction' placeholder='Enter west or east'>";
echo "<input type='submit' value='Submit'>";
echo "</form>";
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the user's answer
$direction = $_POST['direction'];
// Decide what to say based on the direction
if ($direction == "west") {
echo "<p>You chose to go west.</p>";
// Additional question for going west
echo "Do you want to light a torch?<br>";
echo "<form method='post'>";
echo "<input type='hidden' name='direction' value='west'>";
echo "<input type='text' name='torch' placeholder='Enter yes or no'>";
echo "<input type='submit' value='Submit'>";
echo "</form>";
// Check if torch question is answered
if (isset($_POST['torch'])) {
$torch = $_POST['torch'];
if ($torch == "yes") {
echo "<p>You light a torch. The cave brightens up!</p>";
//add more options here
} elseif ($torch == "no") {
echo "<p>You decide against lighting a torch. It's dark ahead.</p>";
//add more options here
} else {
echo "<p>Please enter 'yes' or 'no' for the torch question.</p>";
}
}
} elseif ($direction == "east") {
echo "<p>You chose to go east.</p>";
//add more options here
} else {
echo "<p>Please enter 'west' or 'east'.</p>";
}
}
?>
Code Explanation
Initial Setup
- Display Question and Form: The script starts by displaying a scenario where the player is in a cave and must decide whether to go “west” or “east”. It uses HTML to create a form where the user can input their choice.
echo "You are in a cave. Do you go west or east?<br>";
echo "<form method='post'>";
echo "<input type='text' name='direction' placeholder='Enter west or east'>";
echo "<input type='submit' value='Submit'>";
echo "</form>";
Handling User Input
- Form Submission Check: The script checks if the form has been submitted via POST method.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$direction = $_POST['direction'];
// Further logic based on $direction
}
Decision Based on Direction
-
West Option: