Exploring the world of interactive storytelling through a basic PHP text adventure

I recently completed coding a text adventure using functions like fgets(STDIN) that works in the command line. Now, I want to convert it to run on HTML (internet browser) but I'm facing a challenge. I am unsure how to transition from this:

$choose=0;

while($choose!=1 && $choose!=2 && $choose!=3)
{
    $choose =fgets(STDIN);

    if ($choose==1)
    {
        print "..."
    }

to this:

<html>    
<head>
    <center> <b> <font size="12"> RPG Game </font> </b> </center>
</head>

<form method="POST" action="Game.php">
    <label> Choose :
        <button type="submit" name="submit">1</button> 
        <button type="submit" name="submit2">2</button> 
        <button type="submit" name="submit3">3</button> 
    </label>
    </select>        
</form>

<?php
    $value1=$_POST['submit'];
    $value2=$_POST['submit2'];

    function display()
    {
        echo "..."

        if(isset($value1))
        {   
            echo "Option 1";
        }
        elseif(isset($_POST['2']))
        {
            echo "Option 2";
        }
    }
?>

Do you have any suggestions or methods that could assist me with this task? Is it feasible to achieve?

Answer №1

It seems like you are almost there, but there are a few issues that need addressing:

  1. function display() - You are referencing $value1 within your function without passing it as a parameter (function display($value1)), meaning it will never be defined. (refer to Variable Scope for clarification.)

  2. if (isset($value1)) - If you choose to pass $value1 as a parameter, it will always be set unless you pass a null value.

  3. You are not invoking your display() function anywhere in your code.

I suggest utilizing the $_POST values directly in your function, as demonstrated below:

function display()
{
    echo "...";

    if (isset($_POST['submit']))
    {
        echo "Option 1";
    } elseif (isset($_POST['submit2']))
    {
        echo "Option 2";
    } elseif (isset($_POST['submit3']))
    {
        echo "Option 3";
    }
}

Don't forget to call your function after defining it.

display();

Regarding the while loop in your console application awaiting input, the HTTP version already handles this functionality automatically. PHP sends the form to the browser, allowing the user to interact with it until submission.

Answer №2

function showOutput()
{
    print "You have arrived at your destination";

    if (isset($_POST['submit']))
    {
        print "Option 1";
    } 
    elseif (isset($_POST['submit2']))
    {
        displayAlternateOutput();
    }
}

function displayAlternateOutput()
{
    print "Now you are at a different location";
}

showOutput();

If the user selects the "submit2" option, the output will be: "Now you are at a different location" instead of "You have arrived at your destinationNow you are at a different location".

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

PHP is experiencing issues when trying to insert data into the database

When I run a query in phpMyAdmin such as INSERT INTO table('نچجاعجان'); it appears correctly, but when I try to insert data through my PHP page, it displays in the field like this: ÙاننناÙنعن The col ...

What advantages does the use of $(e).attr(name,value) offer compared to using e.setAttribute(name,value)?

Scenario: The variable "e" represents an element of type "HtmlElement" and not a "css selector" I am referring to any attribute, not just the standard allowed ones like "atom-type" or "data-atom-type". Regardless of the attribute name, will it function wi ...

JavaScript multiplying an array in HTML

Snippet of HTML code <input name="productCode[]" value="" class="tInput" id="productCode" tabindex="1"/> </td> <input name="productDesc[]" value="" class="tInput" id="productDesc" readonly="readonly" /></td> <input name="pr ...

The route to /admin is unreachable with Laravel

Recently, I began a new project using Laravel 5.7 and implemented the standard Laravel Auth with artisan. As part of this process, a new route was added to routes/web.php as shown below: Route::get('/home', 'HomeController@index')-> ...

Constantly encountering incorrect passwords while attempting to authenticate using password_verify with database connections

When I try to log in using password_verify with my database, it keeps showing an error message stating that the password is incorrect. In my database, I have set the password field as char 255. function login(){ global $db, $username, $errors; ...

Upon clicking the 'Add Image' button, TINYMCE dynamically incorporates an input

I am in search of creative solutions to address an issue I'm facing. Currently, I am utilizing TINYMCE to incorporate text into my webpage. However, I would like to enhance this functionality by having a feature that allows me to add an image along w ...

Is Amazon altering the names of their CSS selectors and HTML elements on the fly?

For my Amazon.es web scraper built with Selenium, I am using a CSS selector to determine the total number of pages it will iterate through. However, the selector name seems to change dynamically and I must update it daily. As someone not well-versed in H ...

Output the array value as the function's result

After reviewing various similar inquiries such as this, this, and this, I am still uncertain about the possibility of obtaining a concrete value through operations within a deeply nested array, without invoking a function or assigning a variable. For inst ...

Transmitting an array of objects via Ajax to PHP

Assistance Needed: I have created my object using the following code: var data = []; $("#report-container [id^='report-']").each(function(index) { var reportObject = { "subject" : "", "photo" : "", "rating" : "", ...

Failed PHP email sending using PEAR

Learn how to send emails using GMail SMTP server in PHP I've been attempting to make this work. Despite being told that "it's working code so use it" in the provided link, I'm facing issues. Specifically: <?php require_once "Ma ...

How to Use PHP to Remove XML Node Based on Specific Value

I'm attempting to delete a specific node from an XML file using PHP. Here is the structure of the XML: <ArrivingFlights> <flight> <to>Michelle</to> <from>Brianna xx</from> <imagepath>0001.jpg</ ...

most effective method for recycling dynamic content within Jquery mobile

My jQuery mobile app has a requirement to reuse the same content while keeping track of user selections each time it is displayed. I have successfully created the necessary html content and can append it to the page seamlessly. The process goes something ...

Export the user input query directly into an Excel document with only the visible HTML elements

My goal here is to allow the user to input a starting and ending date. Upon clicking the 'Extract to Excel file' button, a query will be executed to select all columns from a table where the dates fall between the input DATEFROM and DATETO. Simul ...

"Adding an Image to Another Image in HTML or JavaScript: A Step-by-Step

Hello there! I'm currently working on creating a status bar where I can add an image after another image. Let me explain my idea clearly. So, I have two images in GIF format: one is white and 10x10px, and the other one is black and also 10x10px. On ...

Stopping jQuery fadeOut from setting the display property to 'hidden'

I am currently working on a project that involves creating a lightbox effect. I am using jQuery's fadeIn and fadeOut functions to display enlarged div elements. However, I have encountered an issue - when I use fadeOut on the enlarged div, the smaller ...

What is the best way to insert a new row into a table upon clicking a button with Javascript?

Hi everyone, I'm facing an issue with my code. Whenever I click on "Add Product", I want a new row with the same fields to be added. However, it's not working as expected when I run the code. Below is the HTML: <table class="table" id="conci ...

Only the main page is accessible quickly through Express

Currently, I am delving into learning Express and leveraging FS to load my HTML Page. My research on this topic only led me to references of using ASP.NET instead of Express. Here is a snippet from my Server.js file: var express = require('express&a ...

Encountering the error "java.lang.IndexOutOfBoundsException: Index: 1, Size: 1" while attempting to choose the second option in the dropdown menu

I need to choose the third option from a drop-down list that is enclosed in a div element. However, when I try to retrieve the items in the drop-down using Selenium, the size of the drop-down list is only showing as 1 even though there are actually 10 it ...

Caution: PHP's move_uploaded_file() function is unable to successfully relocate the audio file

I've implemented a straightforward Record Wave script using Recorder.js Encountering an Issue Recording works fine Playback of my recording is successful Downloading the recorded file from blob works smoothly The problem arises when trying to uploa ...

What could possibly be causing issues with this query to the database?

-Problem Still Unsolved- I am facing issues with calling a database, retrieving all the rows from a table and storing them in an array. I then try to pass this table as JSON data to my JavaScript and use it as parameters for a function. But when I run the ...