Link to home
Start Free TrialLog in
Avatar of sharingsunshine
sharingsunshineFlag for United States of America

asked on

Rock, Paper and Scisssors Game Logic Question

I have this code and when it is ran it shows the form the first time only.  Thereafter, it just shows the scores never showing the dropdown again.  How do I get it to show the dropdown so someone can continue to make their choices?

I am new to PHP so please tell me what is wrong with what I used.  

Thanks,

<?php
session_start();

?>



<?php


//if(isset($_POST['submit']) && !empty($_POST['submit'])){
if(isset($_POST['choices'])){

// As output of $_POST['choices'] is an array we have to use foreach Loop to display individual value
foreach ($_POST['choices'] as $select) {
	echo "<table>";
	echo "<tr>";
echo "You have selected :" .$select; // Displaying Selected Value
}

// computer picks random

$options = ['Rock', "Paper", "Scissors"];

$pieces = array_rand($options); 

echo "<td>The computer chooses " .$options[$pieces] ."</td>"; // will return name of computer random option

if(($select == 'Rock') && ($options[$pieces] == 'Scissors')){
 echo "<td>Player Wins</td>";
	$_SESSION['Score']= (int)$_SESSION['Score'] +1;
}
elseif(($select == 'Rock') && ($options[$pieces] == 'Rock')){
	echo "<td>No one wins</td>";
	$_SESSION['Score']= (int)$_SESSION['Score'];
}
elseif(($select == 'Rock') && ($options[$pieces] == 'Paper')){
	echo "<td>Computer wins!</td>";
	$_SESSION['compScore']= (int)$_SESSION['compScore'] +1;
}
elseif(($select == 'Paper') && ($options[$pieces] == 'Scissors')){
	echo "<td>Computer wins</td>";
	$_SESSION['compScore']= (int)$_SESSION['compScore'] +1;
}
elseif(($select == 'Paper') && ($options[$pieces] == 'Rock')){
	echo "<td>Player wins</td>";
	$_SESSION['Score']= (int)$_SESSION['Score'] +1;
}
elseif(($select == 'Paper') && ($options[$pieces] == 'Paper')){
	echo "<td>No one wins</td>";
	$_SESSION['Score']= (int)$_SESSION['Score'];
}
elseif(($select == 'Scissors') && ($options[$pieces] == 'Scissors')){
	echo "<td>No one wins</td>";
	$_SESSION['Score']= (int)$_SESSION['Score'];
}
elseif(($select == 'Scissors') && ($options[$pieces] == 'Rock')){
	echo "<td>Computer wins</td>";
	$_SESSION['compScore']= (int)$_SESSION['compScore'] +1;
}
elseif(($select == 'Scissors') && ($options[$pieces] == 'Paper')){
	echo "<td>Player wins</td>";
	$_SESSION['Score']= (int)$_SESSION['Score'] +1;
}

	echo "<td>" .$_SESSION['compScore']."</td>";
	echo "<td>" .$_SESSION['Score']."</td>";

	echo "</tr>";
	echo "</table>";
	empty($_POST['choices']) ;
}
else   {
echo '	<html><head>
  
 

    <title>Rock, Paper and Scissors</title>
     </head>
      <body><h1>Rock, Paper & Scissors</h1>
				
          <form action="" method="post">
						<table width="60%">
					<tr>
				<td>
			 <select name="choices[]">
  <option value="Rock">Rock</option>
  <option value="Paper">Paper</option>
  <option value="Scissors">Scissors</option>
					</select></td>
			
						<tr><td><input type="submit" name="submit" value="submit"></td>
							</tr></table>
		</form>
						
  </body>
</html>';
}
?>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Marco Gasi
Marco Gasi
Flag of Spain image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sharingsunshine

ASKER

Marco, thanks for getting me unstuck.

Ray, thanks for the link.  On using empty that was a last ditch effort to get the form to show.  I removed it and now it works great.
Glad to help you.. In addition to all Ray's articles here at EE, I suggest you this couple book sorted by ascending difficulty level:

1: PHP & MySQL: Novice to Ninja
2: PHP Master: Write Cutting-Edge Code
3: PHP Objects, Patterns and Practice
Just for fun, here's my take on the algorithm.  Have fun with PHP!
https://iconoun.com/demo/rock_paper_scissors.php
<?php // demo/rock_paper_scissors.php
/**
 * https://www.experts-exchange.com/questions/28954062/Rock-Paper-and-Scisssors-Game-Logic-Question.html
 */
error_reporting(E_ALL);
session_start();

// THREE INDEPENDENT VARIABLES
$choices =
[ 'R' => 'Rock'
, 'P' => 'Paper'
, 'S' => 'Scissors'
]
;
// NO CONTEST EXISTS UNTIL THE FORM HAS BEEN SUBMITTED
$contest = $winner = NULL;

// THE SESSION HOLDS OUR SCORE - ENSURE THE VARIABLES ARE INITIALIZED
if (empty($_SESSION['person'])) $_SESSION['person'] = 0;
if (empty($_SESSION['server'])) $_SESSION['server'] = 0;

// IF THERE IS A RESET REQUEST
if (!empty($_POST['xxx']))
{
    $_SESSION['person'] = $_SESSION['server'] = 0;
}

// IF THERE IS A CONTEST REQUEST
if (!empty($_POST))
{
    // MAKE A RANDOM CHOICE FOR THE SERVER
    $server_rps = array_rand( $choices );

    // NORMALIZE AND FILTER THE CLIENT CHOICE FOR THE PERSON
    $person_rps = !empty($_POST['rps']) ? $_POST['rps'] : FALSE;
    if (!$person_rps) goto makeform;
    $person_rps = strtoupper(substr(trim($person_rps),0,1));
    if (!array_key_exists($person_rps, $choices)) goto makeform;

    // SET THE CONTEST OUTCOMES
    $contest = $server_rps . $person_rps;

    switch($contest)
    {
        case 'RR' : goto tie;
        case 'PP' : goto tie;
        case 'SS' : goto tie;

        case 'RS' : goto server_win;
        case 'SP' : goto server_win;
        case 'PR' : goto server_win;

        default : goto person_win;
    }

    person_win: {
        $_SESSION['person']++;
        $winner = ', <b>Person</b> wins';
        goto makeform;
    }
    server_win: {
        $_SESSION['server']++;
        $winner = ', <b>Server</b> wins';
        goto makeform;
    }
    tie: {
        $winner = ', Tie';
    }
}

makeform: {
// REPORT THE CURRENT CONTEST
if ($contest)
{
    echo PHP_EOL . '<br>Current choices: ';
    echo PHP_EOL . 'Person: ' . $choices[$person_rps];
    echo ', ';
    echo 'Server: ' . $choices[$server_rps];
    echo $winner;
}
// REPORT THE CURRENT SCORES
echo PHP_EOL . '<br>Current scores: ';
echo PHP_EOL . 'Person: ' . $_SESSION['person'];
echo ', ';
echo 'Server: ' . $_SESSION['server'];

$form = <<<EOD
<form method="post">
<button type="submit" name="rps" value="R">Rock</button>
<button type="submit" name="rps" value="P">Paper</button>
<button type="submit" name="rps" value="S">Scissors</button>
<br>
<br>
<button type="submit" name="xxx" value="X">Reset Scores</button>
</form>
EOD;
echo $form;
}

// ACTIVATE THIS TO LIST THE SOURCE CODE
// highlight_file( __FILE__ );

Open in new window

I'd recommend you take a look at the HTML output of your script. That it works now, after simply taking out the else and always echoing the options for the first and next rounds of the game - that this works is merely graceful rendering of quirky HTML, in the normal case an output would need to start with <html> and not have its <html> tag somewhere in the middle.

So for outputting valid HTML you're still far off. Rays code may be a bit over the top for a PHP starter, so we can't expect you to write such clean code, but you can do better. As you want to output HTML anyway, you can rightaway start with <html> and all further necessary html up to the <body> tag, then test, whether there is submitted data and output this and computer choice and game result. Afterwards continue with the choices for either the first or subsequent games and then end all open html tags, so the structure of the script should be

1. HTML head code up to body starting tag
2. PHP: If there is a submitted choice, output user choice, computer choice and game result
3. HTML choice options
4. HTML footer, end of body, end of html.

By the way HTML5 makes creating valid HTML easier than it ever was before, not only because of the simple doctype annotation.

Bye, Olaf.
Ray, sure a beautiful set of code.  Thanks for posting it for me.