Loop Iteration in Php Game - php

Trying to get it to loop through 3 times and after the 3rd time (if not guessed right) show the right answer.
Currently - its going through the guesses, but isnt showing how many guesses are left (should be deducting each # each attempt).
Anyone? If you could show me where I'm going wrong here.
<style type="text/css">
input {border:1px solid #ADD8E6; font-size:1.2em;}
input.spec {background-color:#ddd;}
</style>
<?php
echo "<fieldset><h1><legend>Testing your Academy Award Trivia</h1>";
$ages['Casablanca'] = "1943";
$ages['Around The World in 80 Days'] = "1956";
$ages['Patton'] = "1970";
$ages['Annie Hall'] = "1977";
$ages['Chariots of Fire'] = "1981";
$ages['Dances With Wolves'] = "1990";
$ages['Crash'] = "2005";
$ages['The Departed'] = "2006";
$rand_keys = array_rand($ages, 1);
$guesses = 3;
?>
<form method='post' name="inputyear" onsubmit="return validate(this);">
Give the year below won academy award<br><br>
<Strong>Movie:</strong> <input type='text' name='movie' class="spec" value='<?= $rand_keys ?>' readonly='readonly' /><br><br>
<Strong>Year it Won the Oscar:</Strong> <input type='text' name='year' size="30" /><br/><br>
<strong>You have: </strong> <?php $guesses; ?> guesses left<br><br>
<input type='submit' name='submit' value="Get Result" onClick="makeGuess()" />
</form>
<?php
$movie = isset($_POST['movie']) ? $_POST['movie'] : false;
$guessedYear = isset($_POST['year']) ? (int) $_POST['year'] : false;
if ($movie && $guessedYear) {
$realyear = $ages[$movie];
}
#$_SESSION[$movie]['$guesses']++;
if ($realyear && $_SESSION[$movie]['$guesses'] < 3) {
if ($guessedYear == $realyear) {
echo "Correct! " . "during year " . $realyear;
}
if ($guessedYear < $realyear) {
echo "Wrong, year too low";
$guesses--;
}
if ($guessedYear > $realyear) {
echo "Wrong, year too high";
$guesses--;
}
} elseif ($_SESSION[$movie]['$guesses'] >= 3) {
echo "Sorry, too many tries. the answer was " . $realyear;
} else {
echo "Sorry, You managed not to pick a year. Please try again";
$_SESSION[$movie]['guesscount']--;
}
?>

the return statement is leaving the loop and the script
get rid of both return statements
DC
Further to your comments on the duplicate question at...
Allowing 3 attempts at game - php
It would appear that this question is a 'homework' question as such and in fact with all questions no-one will give you the complete answer, nor in my opinion should they. We all expect that the person asking the question will take it upon themselves to investigate and understand the answers given.
Now in the case of your question, you appear to be missing a vital piece of information about how HTTP works (http is the protocol that drives all web pages and many other parts of the internet).
http is what's considered a stateless protocol, that is when you click on a link in a web page and go to another web page (or even the same web page), the new web page considers you a totally new visitor. It in effect has forgotten you.
Because this introduced issues for things like shopping carts (and PHP games) cookies were invented. this allowed the browser to carry around a small bit of information about you, in this way the web server or application remembered you. This has been extended into what respondents here are calling sessions.
A session is (usually) a cookie that stores an identifier. that identifier tells, in this case PHP, that you have been there before and where to find the information about you. PHP can load this information and make it available to you the programmer.
This happens EVERY TIME a page is loaded.
Now PHP does not know what to store in this 'session' it is up to you the programmer to decide what information needs to be stored. you need to tell PHP to save this information for the next time the page is loaded.
In your case its up to you to decide what needs to be remembered. Consider the reloading of the page to be a new 'iteration' of the loop. this should lead you to some obvious conclusions about what needs to be passed from one iteration to the next.
There you go. I haven't written the answer for you but hopefully have provided enough for you to pass your class in flying colours.
DC

I think you're problem is this line $rand_keys = array_rand($ages, 1);. Each time the user submits their answer a new $rand_keys is selected and fed into the dropdown regardless of what the submitted answer was.
So you'll want to check if there exists an answer (otherwise it's the first time the page is loaded). If there is an answer and it was correct then show a congrats message and generate a new movie id.
if($_POST['submit']) {
$movie = $_POST['movie'];
$guessedYear = $_POST['year'];
if ($guessedYear == $ages[$movie]) {
// well done you got it right, next movie
$rand_keys = array_rand($ages, 1);
}
else if ($guessedYear == $ages[$movie] && $_POST['tries'] >= 3) {
// took over 3 tries and didn't get it right, next movie
$rand_keys = array_rand($ages, 1);
}
else {
// find $movie index from $ages and use that
}
// you have one less try
$tries = $_POST['tries'] - 1;
}
else {
$rand_keys = array_rand($ages, 1);
$tries = 3;
}
Then in the form send the $tries variable along with the other ones, or as the other people here have said put it in the session variables. With that I think you should be able to remove the while loop completely.

After you fix what DeveloperChris says, you still need to put guesscount into as session or form field, and increment on each attempt.

if($guesscount < 3 && $guessedYear > $realyear){
echo "Wrong, year too high";
}
if($guesscount < 3 && $guessedYear > $realyear){
echo "Wrong, year too high";
}
duplicate code there. also i think you are looking for if{...}else if{..}else if{...}else{...}
and your question has nothing to do with javascript.

maybe core logic more like this?
$movie = isset($_POST['movie']) ? $_POST['movie'] : false;
$guessedYear = isset($_POST['year']) ? (int) $_POST['year'] : false;
if ($movie && $guessedYear) {
$realyear = $ages[$movie];
}
#$_SESSION[$movie]['guesscount']++;
if ($realyear && $_SESSION[$movie]['guesscount'] < 3) {
if ($guessedYear == $realyear) {
echo "Correct! " . "during year " . $realyear;
}
if ($guessedYear < $realyear) {
echo "Wrong, year too low";
}
if ($guessedYear > $realyear) {
echo "Wrong, year too high";
}
} elseif ($_SESSION[$movie]['guesscount'] >= 3) {
echo "Sorry, too many tries. the answer was " . $realyear;
} else {
echo "Sorry, You managed not to pick a year. Please try again";
$_SESSION[$movie]['guesscount']--;
}

Related

Different Style for each result

I try show all the hours of the day in order 8, 9, 10 ... but to distinguish the hours that are in the database from the hours that are not. For instance, to give a different color. Can anyone help? (I am not a programmer and I am just learning php alone, so any I would appreciate any help, but explain it in a simple way, please)
This gives me the hours that I have in the database in blue. But I cannot to get hours that are not in the database and I cannot give them another color and the right position: 8, 9,10, 11...
$result = mysqli_query($con, 'SELECT * FROM consulta
WHERE professional=1
AND client=0');
while ($row = mysqli_fetch_array($result)) {
if ($row['hour']=='09:00:00') { echo '<p style="color:blue;">9</p>'; }
elseif ($row['hour']=='10:00:00') { echo '<p style="color:blue;">10</p>'; }
elseif ($row['hour']=='11:00:00') { echo '<p style="color:blue;">11</p>'; }
elseif ($row['hour']=='12:00:00') { echo '<p style="color:blue;">12</p>'; }
}
Here's some sudo code for you. Make an array with all the hours in it. Then iterate that array instead of the result from the database.
for ($i = 0; $i < 24; $i++) {
if(in_array("$i:00:00", $row)) {
// hour was found in the database
echo '<p style="color:blue;">'.$i.'</p>';
} else {
// hour was not found
echo '<p style="color:red;">'.$i.'</p>';
}
}
This way you're iterating over hours that are in the database. Just them. So if 11 is not in the database, if simply won't show. You need a different logic.
You need to iterate over all 24 hours and for each hour check if it is in the database, if so, apply styling, if not, render normally. And a hint, it might be easier to defince CSS classes instead of using inline styling (<p class="db">9</p> instead of <p style="color:blue;">9</p>, and of course, having the db class defined properly; that way you only need to change one rule instead of styling of each element in case you want to change something).

PHP String that is equal to $_POST will not change later, or maybe it is something else

I've been learning PHP in my spare time, and this is one of my "Hello, World" type scripts I'm doing for practice.
This is the code below, and the default strings will not change so the code will end up looping into eternity for I have no idea why:
<?php
if (isset($_POST["pbankroll"], $_POST["pstartbet"]))
{
$bankroll = $_POST["pbankroll"];
$startBet = $_POST["pstartBet"];
//If using this code below instead of that above, everything will work fine:
//$bankroll = 200;
//$startBet = 25;
while($bankroll >= $startBet)
{
$evenOrOdd=mt_rand(0,1);
if ($evenOrOdd == 1)
{
$bankroll += $startBet;
echo "Win ...... Bankroll is now: " . $bankroll . "<br>";
}
else
{
$bankroll -= $startBet;
echo "Loss ..... Bankroll is now: " . $bankroll . "<br>";
}
}
echo "Probability, the Devourer of all Things!";
}
else
{
echo "Please enter a bankroll and starting bet above.";
}
?>
The form to it:
<form action="index.php" method="post">
Bankroll: <input type="text" name="pbankroll">
Start Bet: <input type="text" name="pstartbet">
<input type="submit">
</form>
I appreciate the help.
The HTML name pstartbet needs to be changed to pstartBet.
Edit to clarify:
The Start Bet input element in the HTML form has the name pstartbet with the 'B' in lowercase. When PHP checks for that value, it's looking for pstartBet with the B capitalized. One of these two names needs to be changed so the cases match.
As it is:
$startBet = $_POST["pstartBet"]; // doesn't exist
This means that $startBet will be null. When cast to a number by the mathematical operations this will result in 0 - so the value of $bankroll will never change, and the loop will continue forever.
First, you'll have to convert the incoming values to integer before using them in numerical operations:
$bankroll = intval($_POST["pbankroll"]);
$startBet = intval($_POST["pstartBet"]);
Or if they are float values use:
$bankroll = floatval($_POST["pbankroll"]);
$startBet = floatval($_POST["pstartBet"]);
Beside from this, the code can of course run forever. This is because of the pseudo randum numbers that are being used. If over a long time there are more 1's then 0's generated by mat_rand() then the code will run forever
Consider that truly random numbers cannot be generated by a computer. Apparently mt_rand generates a pseudo-random number in such a way that it's causing an infinite loop.
I would recommend setting the variables outside of the if clause & setting a default of '' which basically means 'empty' & then having the if check if those two variables are empty or not.
<?php
$bankroll = array_key_exists("pbankroll", $_POST) ? intval($_POST["pbankroll"]) : '';
$startBet = array_key_exists("pstartbet", $_POST) ? intval($_POST["pstartbet"]) : '';
if (!empty($bankroll) && !empty($startBet))
{
//If using this code below instead of that above, everything will work fine:
//$bankroll = 200;
//$startBet = 25;
while($bankroll >= $startBet)
{
$evenOrOdd=mt_rand(0,1);
if ($evenOrOdd == 1)
{
$bankroll += $startBet;
echo "Win ...... Bankroll is now: " . $bankroll . "<br>";
}
else
{
$bankroll -= $startBet;
echo "Loss ..... Bankroll is now: " . $bankroll . "<br>";
}
}
echo "Probability, the Devourer of all Things!";
}
else
{
echo "Please enter a bankroll and starting bet above.";
}
?>

Dynamic Text Using JavaScript & PHP?

I'm working on a little project, basically I have some text on my PHP/HTML page that is being echo'ed from a variable ($brief_string).
There is also a back, and continue button which basically subtracts or adds to another variable ($brief_page - which is pulled from my DB). The brief_string changes depending on the brief_page by using if statements. First problem I encounter is that when I hit continue (submit button) it resubmits/refreshes the page, causing my brief_page to reset back to 0.
So I'm thinking maybe I could use JS to hold the info and page variables and control the dynamic text, but then, how would I update my DB with the current page value via JS? Isn't it really easy to manually change/hack these values? I would preferably like my DB to be updated with the page number each time the use presses the back/continue button.
I would just like some advice really as I am a student trying to develop an interactive book like site (that uses a DB to save your current page).
Code:
<?
$brief_info = "brief info goes here";
$brief_page = 0; //< will soon be pulled off DB
if (isset($_GET['brief1Go'])) {
$brief_page = $brief_page + 1;
}
else if (isset($_GET['brief1Back'])) {
$brief_page = $brief_page - 1;
}
$breifController = "
<form action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\">
<input type=\"submit\" name=\"brief1Back\" id=\"brief1Back\" value=\"BACK\" />
</form>
<form action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\">
<input type=\"submit\" name=\"brief1Go\" id=\"brief1Go\" value=\"CONTINUE\" />
</form>";
if($brief_page == 0){
$brief1_info = "<b>Welcome Commander,</b> you are currently viewing the Mission Control Brief page, here you can view all your missions that you need to complete in order to advance through your prestiges. You will need to follow your briefs carefully in order to succeed. <br /><br />
";
}
else if($brief_page == 1){
$brief_info = "Okay, let me show you around the place ...";
}
else if($brief_page == 2){
$brief_info = "brief is on 2";
}
?>
Why not just use get vars entirely?
yes, start at 0 unless $_GET['page'] is set...
$brief_page = 0;
if(isset($_GET['page']))
$brief_page = $_GET['page'];
then only use links to your next and previous pages instead of some weird post thing.
Previous Next
where obviously the page numbers in the previous and next are just echoed from php
$prev = $brief_page - 1;
$next = $brief_page + 1;
The user specific things to store can easily be handled with sesisons, cookies or even other get vars if you want to introduce a horrible security hole. Your choice really.
I would definitely not do this via $_POST though. totally annoying. Go with all full on ajax if you want to do that. At least you won't pester the user with "are you sure you want to resubmit the form data" messages if they choose to refresh the page.

PHP can't iterate through too high or too low

[Disclaimer: I am new to PHP, and I am just learning, so please no flamers, it really hinders the learning process when one is trying to learn, thank you.]
The code below runs, the only problem is that it does not tell the user when the number is too high or too low, I am doing something wrong, but I can't see the error?
<?php
//Starts our php document
if (!$number)
//if we have already defined number and started the game, this does not run
{
Echo"Please Choose a Number 1-100 <p>";
//gives the user instructions
$number = rand (1,100) ;
//creates number
}
else {
//this runs if the game is already in progress
if ($Num >$number)
{
Echo "Your number, $Num, is too high. Please try again<p>";
}
//if the number they guessed is bigger than number, lets user know, guess was high
elseif ($Num == $number)
{
Echo "Congratulations you have won!<p>";
//if the number they guessed was correct it lets them know they won
Echo "To play again, please Choose a Number 1-100 <p>";
$number = rand (1,100) ;
//it then starts the game again by choosing a new value for $number that they can guess
}
else
{
Echo "Your number, $Num, is too low. Please try again<p>";
}
//if the answer is neither correct or to high, it tells them it is too low
}
?>
<form action = "<?php Echo $_SERVER[’PHP_SELF’]; ?>" method = "post"> <p>
<!--this sends the form back to the same page we are on-->
Your Guess:<input name="Num" />
<input type = "submit" name = "Guess"/> <p>
<!--Allows the user to input their guess-->
<input type = "hidden" name = "number" value=<?php Echo $number ?>>
<!--keeps passing along the number value to keep it consistent till it is guessed-->
</form>
</body>
</html>
I am assuming $Num is undefined and I am assuming you are assuming it will be defined be cause it is defined in the form.
Try this at the start of your script:
if(!empty($_POST)) {
$Num = (int) $_POST['Num'];
}
$number is not automatically set to the value the <input> field has. (It was in early versions of PHP). You now have to use $_POST['number'] and $_POST['Num'] for this.
register_globals in your php.ini is probably Off (and that's a good thing) and therefore you can only access those variables through $_POST['Num'] and $_POST['number'] (you can just assign $number=$_POST['number'] at the beggining of your script)
also, sending the secret $number through form is not nice, you might want to read about php sessions
Suggestions:
1) use echo, not Echo
2) do not forget to close the p tag

Struggling with hidden form field basics (PHP)

I'm having difficulty using hidden forms with PHP data. I cannot for the life of me figure out what I'm doing wrong.
My code should
Check to see if an attack succeeded;
If it succeeded, subtract damage from health;
Rewrite the $health variable.
Use the new $health value for the next round.
The problem is, it keeps resetting the health value.
Here is my code (it's set so that the attack always succeeds):
<?php
$health = $_REQUEST["health"];
$attack = rand(10,20);
$defend = rand(1,9);
$damage = rand(1,5);
$health =50;
if ($attack>$defend){
print "<p>Jim hit the robot for $damage.</p>";
$health = $health - $damage;
print "<p>The robot has $health health remaining.</p>";
} else {
print "<p>Jim missed.</p>";
print "<p>The robot has $health health remaining.</p>";
} // end if statement
print <<<HERE
<input type="text"
name="openMonsterHealth"
value="$health">
<input type="hidden"
name="hdnMonsterHealth"
value="$health">
<input type="submit"
value="click to continue">
HERE;
?>
If you want $health to follow you to the next page, use sessions.
PHP Manual on Sessions
Basically, you'd start your pages with
session_start();
if(isset($_SESSION['health'])) {
$health = $_SESSION['health'];
}
else {
//However you normally set health when the user is just starting
}
which would load the health value from the previous page, if you set it like this:
$_SESSION['health'] = $health;
PHP scripts automatically write and close sessions, so you don't have to worry about anything other than creating a variable in the session global array. Just don't forget to start your sessions when you want to retrieve the data in the session array from the previous page. Your users, however, will have to be able to accept cookies.
If you keep using hidden fields, a player could change that information before sending it back to you (plus, they're more trouble to keep track of).
edit:
Your bugs, however, are you're resetting your health to 50 on the 5th line of your code, you're not using the right variable name for health from the request, and you don't have any form tags.
<?php
if(isset($_REQUEST['hdnMonsterHealth']))
$health = $_REQUEST['hdnMonsterHealth'];
else
$health = 50;
$attack = rand(10,20);
$defend = rand(1,9);
$damage = rand(1,5);
if ($attack > $defend) {
print "<p>Jim hit the robot for $damage.</p>";
$health = $health - $damage;
print "<p>The robot has $health health remaining.</p>";
} else {
print "<p>Jim missed.</p>";
print "<p>The robot has $health health remaining.</p>";
} // end if statement
print <<<HERE
<form method="post">
<input type="text"
name="openMonsterHealth"
value="$health">
<input type="hidden"
name="hdnMonsterHealth"
value="$health">
<input type="submit"
value="click to continue">
</form>
HERE;
?>
Edit: Sorry for all of the weirdness, formatting is broken by this block of code, so I had to manually insert every < in the code with <. This code works now, however.
You still have a bug of negative health. I'm not writing your game for you, though.
Sorry, you haven't mentioned what scope your $health variable is. Does it belong to the session, or just for the lifetime of the request?
I'd strongly encourage using session variables, i.e.:
$_SESSION["health"] = $_SESSION["health"] - $_REQUEST["DAMAGE"];

Categories