PHP Random Number Guessing Game.

Hey Y’all.

I am having trouble trying to figure out how to make a Guessing Number Game. Here are some of the requirements I am needing to do:

Inside the PHP code block at the top of the script file, define a function. The function should
compare the two parameters and return a number (-1, 0, or 1) that indicates whether the
first parameter is smaller than, larger than, or the same as the second parameter. Define
the function using following settings:
a. Name: compare_integers
b. Parameters: int1 and int2
c. Return values:
I. -1 if int1 is smaller than int2
II. 0 if int1 is the same as int2
III. 1 if int1 is larger than int2 (I have completed this part)
-Continue the script by creating a PHP variable named random. Set random using an IF …
ELSE statement as follows:
a. If a post data associated with the hidden form field named random exists,
retrieve the data, sanitize it, and then assign it to random.
b. If the post data does not exist, assign random a random number between 1
and 20.

  • Check whether a post data associated with a form field named guess exists. Hint: you may
    use filter_has_var function. This data is the player’s guess. If the data exists, perform
    followings:
    a. Retrieve the data, sanitize it, and then store it in a PHP variable named guess.
    b. Check to see if guess is in the range between 1 and 20.
    c. If guess is in the range, call the compare_integers function and pass guess
    and random to the function. Based on the return value, assign a string to a
    variable named message.
    i. If the return value is -1, set message to “Your guess ‘guess’ was too
    low.".
    ii. If the return value is 1, set message to “Your guess ‘guess’ was too
    high.".
    iii. If the return value is 0, set message to “Congratulations! You
    guessed the hidden number!!!"
    d. If guess is not in the range, set message to “"Invalid guess. Please enter a
    number between 1 and 20.”
  • Modify the tag for the hidden form field random so its value is the data stored in
    the PHP variable random.

Here is the code I have so far (the require attributes are from the same project, first part of it):

[php]

<?php $title = "Guessing the number game"; require ('includes/header.php'); function compare_integers($int1, $int2) { if ($int1 < $int2) { return -1; } if ($int1 == $int2) { return 0; } if ($int1 > $int2) { return 1; } } //$random = rand(1, 20); if (!filter_has_var(INPUT_POST, "random")) { $random = filter_input(INPUT_POST, "random", FILTER_SANITIZE_NUMBER_INT); }else { $random = rand(1, 20); } /*if (!filter_has_var(INPUT_POST, "guess")){ (!filter_input(INPUT_POST, "guess", FILTER_SANITIZE_NUMBER_INT); } else { if ('guess' == $random){ } }*/ ?> <?php echo $title ?>
<body>


    <!-- Main body of content -->
    <div id="mainbody">

        <!-- page specific content starts -->
        <h2>Guessing the Number</h2>
        <p>Enter a number between 1 and 20, then press the Guess button.</p>
        <form action="game.php" method="post">
            <p>
                <input type="number" name="guess" required />&nbsp;&nbsp;
                <input type="submit" value=" Guess " />
            </p>
            <!-- this hidden field is used to store the system generated random number -->
            <input type="hidden" name="random" value="<?php echo $random ?>" />
        </form>
        <!-- page specific content ends -->


    </div>


   <?php
    require ('includes/footer.php')
    ?>
</body>
[/php]

I am not needing the answer, but I want to see if I am on the right track and would like some tips, advice, and/or examples on how to achieve the random variable/if… else… part, the guess variable “filter_has_var” part, and the red text part. I am just really lost after trying to figure it out for 2-3 hours and looking at my notes and examples online (it isn’t clicking). Thanks!

You are kind of on the right track. I didn’t answer the whole game, but I think I pointed you in the right direction. I also pretty up the HTML with CSS.

Here’s a standard CSS reset:
reset.css

[code]/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, textarea, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: ‘’;
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}[/code]

And here’s the portion that I pointed (I hope in the right direction):
[php]<?php
if (filter_has_var(INPUT_POST, “random”)) {
$random = filter_input(INPUT_POST, “random”, FILTER_SANITIZE_NUMBER_INT);
} else {
$random = rand(1, 20);
}
if (filter_has_var(INPUT_POST, “guess”)) {
$guess = filter_input(INPUT_POST, “guess”, FILTER_SANITIZE_NUMBER_INT);
echo “Random number is " . $random . " guess is " . $guess . "
\n”;
}

?>

Guessing Game * { -webkit-box-sizing: border-box; box-sizing: border-box; } body { background-color: cornsilk; padding: 0; margin: 0; } div.container { display: block; width: 100%; max-width: 600px; height: auto; background-color: #fff; padding: 20px; margin: 20px auto; } div.container h1 { font-family: "Palatino Linotype", "Book Antiqua", Palatino, serif; font-size: 1.8rem; line-height: 1.5; text-align: center; } div.container p { font-family: Arial, Helvetica, sans-serif; font-size: 1.2rem; line-height: 1.5; text-align: center; } form#game { display: block; width: 100%; max-width: 360px; height: auto; background-color: #2e2e2e; padding: 10px; margin: 0 auto; } form#game fieldset { border: 1px solid #fff; padding: 20px; } form#game legend { font-family: "Palatino Linotype", "Book Antiqua", Palatino, serif; font-size: 1.2rem; color: #fff; padding: 0 5px; } form#game label { float: left; display: block; width: 100%; max-width: 200px; height: 30px; font-family: Arial, Helvetica, sans-serif; font-size: 1.0rem; line-height: 30px; color: #fff; } form#game input { clear: right; display: block; width: 100%; max-width: 95px; height: 30px; padding: 0 5px; } form#game input[type=submit] { display: block; width: 100px; height: 30px; border: none; outline: none; cursor: pointer; background-color: #69c; font-family: Arial, Helvetica, sans-serif; font-size: 1.2rem; text-transform: capitalize; color: #fff; margin: 15px auto 5px; }

The Guessing Game Instructions

Pick a number between 1 and 20 then press the Guess button!

The Guessing Game Number between 1 and 20 [/php]

You’re thinking False in terms and you should be thinking in terms of TRUE. In my opinion it’s also easier most of the time thinking in true terms. I think the rest should be easy peasy in solving the this.

Thanks for the CSS prettying up, but that is not a requirement. Our professor wants it minimized, since we are focusing on php for the class and that the first part of the project was to make the header and footer in its own PHP file with the require script.

I tried to edit the code for requirements that I put on my first post and I know I am doing it wrong, since the code isn’t affecting anything. I am also not sure where to put the message variable. The true/false Boolean isn’t what I need, it’s based on the if statement, calling upon the return value of the function!

Also, I am needing to “Add PHP code below the form to display the value stored in message in red color.” I know how to do that in CSS, but we never were taught to do that in PHP. I am assuming the “message” is the variable I made.

[php]

<?php $title = "Guessing the number game"; require ('includes/header.php'); function compare_integars($int1, $int2) { if ($int1 < $int2) { return -1; } if ($int1 == $int2) { return 0; } if ($int1 > $int2) { return 1; } } //Continue the script by creating a PHP variable named random. Set random using an IF … ELSE statement as follows: //If a post data associated with the hidden form field named random exists, retrieve the data, sanitize it, and then assign it to random. if (!filter_has_var(INPUT_POST, "random")) { $random = filter_input(INPUT_POST, "random", FILTER_SANITIZE_NUMBER_INT); }else { //If the post data does not exist, assign random a random number between 1 and 20. $random = rand(1, 20); } /*Check whether a post data associated with a form field named guess exists. Hint: you may use filter_has_var function. This data is the player’s guess. If the data exists, perform followings: */ if (!filter_has_var(INPUT_POST, "guess")){ //Retrieve the data, sanitize it, and then store it in a PHP variable named guess. $guess = filter_input(INPUT_POST, "guess", FILTER_SANITIZE_NUMBER_INT); } else { //Check to see if guess is in the range between 1 and 20. if ($guess == rand(1, 20)){ /*If guess is in the range, call the compare_integers function and pass guess and random to the function. Based on the return value, assign a string to a variable named message. (the next if statement has this!) */ compare_integars($guess, $random); } } //If the return value is -1, set message to “Your guess ‘guess’ was too low.". if ('compare_integars' == -1){ $message = "Your guess 'guess' was too low"; } //If the return value is 1, set message to “Your guess ‘guess’ was too high.". elseif ('compare_integars' == 1) { $message = "Your guess 'guess' was too high"; } //If the return value is 0, set message to “Congratulations! You guessed the hidden number!!!" elseif ('compare_integars' == 0) { $message = "Congratulations! You guessed the hidden number!!!"; } //If guess is not in the range, set message to “"Invalid guess. Please enter a number between 1 and 20.” else { $message = "Invalid Guess. Please enter a number between 1 and 20."; } ?> <?php echo $title ?>
<body>


    <!-- Main body of content -->
    <div id="mainbody">

        <!-- page specific content starts -->
        <h2>Guessing the Number</h2>
        <p>Enter a number between 1 and 20, then press the Guess button.</p>
        <form action="game.php" method="post">
            <p>
                <input type="number" name="guess" required />&nbsp;&nbsp;
                <input type="submit" value=" Guess " />
            </p>
            <!-- this hidden field is used to store the system generated random number -->
            <input type="hidden" name="random" value="<?php echo $random 

//Modify the tag for the hidden form field random so its value is the data stored in
//the PHP variable random. ?>" />

    </div>


   <?php
    require ('includes/footer.php')
    ?>
</body>
[/php]

[php] if (!filter_has_var(INPUT_POST, “random”)) {
$random = filter_input(INPUT_POST, “random”, FILTER_SANITIZE_NUMBER_INT);
}else {
//If the post data does not exist, assign random a random number between 1 and 20.
$random = rand(1, 20);
}[/php]

Logically speaking I think that is flawed, for the user has guessed the number. So it should be in my way of thinking :

[php]/* When the page is first run the $random variable Does Not exist, /
/
so the filter_has_var checks to see if it variable has value (or a variable) then it is true. However, /
/
the user has NOT inputed his/her guess so the hidden input field is empty or /
/
does not exist. */
if (filter_has_var(INPUT_POST, “random”)) {
$random = filter_input(INPUT_POST, “random”, FILTER_SANITIZE_NUMBER_INT);
} else {
$random = rand(1, 20);
}[/php]

I’m going to do this homework assign, but I will not show my solution. That way I can see what I’m telling you is right and that I’m steering you in the right direction. I am pretty sure I am.

Ignore my way of thinking for a second…I think you might be more on the right track than I am. I first have to do something to see.

Nope I was right.

[php]function compare_integers($int1, $int2) {
if ($int1 < $int2) {
return -1;
}
if ($int1 == $int2) {
return 0;
}
if ($int1 > $int2) {
return 1;
}
}

//$random = filter_has_var(INPUT_POST, ‘random’) ? htmlspecialchars($_POST[‘random’]) : rand(1, 20);

if (filter_has_var(INPUT_POST, “random”)) {
$random = filter_input(INPUT_POST, “random”, FILTER_SANITIZE_NUMBER_INT);
} else {
$random = rand(1, 20);
}

if (filter_has_var(INPUT_POST, “guess”)) {
$guess = filter_input(INPUT_POST, “guess”, FILTER_SANITIZE_NUMBER_INT);
$result = compare_integers($guess, $random);
}[/php]

I figured you basically had this part done yourself minus to ! or not. ;D

P.S. That’s still not right, but I give you a hint it has to do with validation.

OK, I have a completely working script and I am pretty positive it meets the requirements.

[size=24pt]SPOILER[/size] -> If you are curious I have the solution posted here -> https://github.com/Strider64/php_sandbox and the file is called guessing.php.

THANK YOU SOOOOOOO MUCH. I have been trying to fiddle around with this for about 2 days now. It looks like I was really close, but I didn’t put them totally together and that is why I was having trouble. You have been very helpful and I do appreciate that.

I do have some questions regarding your code (just for understanding purposes, since it does fit the requirements):

For the checking to see if the guess is in the range between 1 and 20, why is it used with the less than and greater than, instead of seeing if it works in the rand(1, 20)? That is where my brain went to first, so that is why I got confused.

For the switch statement you used, I was close for putting it in a if statement at the bottom, but why does it go into the same if statement that has the guess variable and why does the calling of the function need to have it’s own variable?

Why is the message variable, in the form field, in an if statement and what does the isset term mean? We very quickly went over that, but we mainly went over the filter_var, filter_has_var, etc… so that is something I wouldn’t have guessed to be used. I did look online for tips and found that used multiple times, but I didn’t use it in my first attempts, since I wasn’t sure if it was needed or where to put it exactly. I tried to take out the if statement and it was giving me an error, so why is the if statement needed fully for echoing the message variable?

I do apologize for the questions, but I am just trying to understand it fully. Again, I was so close and I was getting it, but 1-2 things I wasn’t doing right and I didn’t put the if/switch statement with the guess variable if statement.

Thanks again and you are amazing.

Basically a switch statement is a glorified if statement (well that’s how I look at it). You can get the same thing done using an if statement and maybe it might bet best if you did that? (I don’t know how picky your professor is going to be) So you would have three if statements, one for -1, one for 0 and one for 1 conditions instead of the switch statement.

Actually I think you can stick the function call compare_integers($guess, $random) instead of $result inside the switch statement, but to me it looks messy. The only way the program code will know what number is, is by using an if statement. the rand function just spits out a random number (in this case 1 to 20).

Actually the $message variable is in its own div element and I used the isset() instead of filter_has_var, for that is used to grab input of some kind (GET, POST). The reason is that the $message variable isn’t set yet for the user hasn’t guessed and clicked the submit button. Otherwise it will give some kind of error (can’t remember it exactly), but I think it should still work? Though it’s annoying to seeing that error message on the screen. I shouldn’t tell you this, but you can use the @ symbol to suppress errors, but that is very very bad programming…don’t do it. I know I have never used it and I shake my head at people who do and then ask for help.

I even learned something myself, I really hadn’t thought of using the filter_has_var() function and I admit I haven’t really came acrossed it (known about it).

He is fine with whatever, I just totally forgot about using a switch statement, since we use if statements a lot, but we are allowed to use whatever, since neither were specifically needed. I tried to do the -1, 0, and 1 for the if statement, and it didn’t work, but it worked with the switch, I just was curious about it.

I understand now, I just wasn’t sure why their was a variable with the function, but it is because of the switch, so that makes 100% sense now.

That was one of my only things I missed and was confused about: I wasn’t sure where to put the $message variable, but having it in an isset make total sense, I just wasn’t sure why it had to be put in an if statement. I took it out of the if statement and it was giving me an error, til I put a number in, then it would work fine, so it’s there for the “before a number is put in” time and I get it know. I have never been told about the @ symbol and wont use it, as I know about bad programming. I took many web page design classes and there are some easy and cheap ways to do something, but it isn’t best practice, so I won’t be using it. :slight_smile:

We use the filter_has_var() statement/function a lot, since we were doing practices using forms and other things with sanitizing and validating information. It’s good to learn new things. Thanks for all your help!

Sponsor our Newsletter | Privacy Policy | Terms of Service