PHP - Random Number Game
Hello,
I am trying to create a simple game random number guessing game in PHP. Currently, I have an HTML page with a form on it where the user enters a number. Then when the user clicks the submit button on the form, their number is passed onto the second page. On the second page, I have some PHP code that generates a random number between 1 and 20, then it checks to see if the two numbers are the same. If they are the same, it says correct. If the guess is higher, it says so. If the guess is lower, it says so. I also made it display a form to re-guess the number (if the initial guess was incorrect). The problem I have is when the user attempts to re-guess the number. Whenever the user attempts to enter a new guess, the random number changes. I want to make it so that the random number stays the same as it is. Any help? Here is the Code for the first HTML page: Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>phpNumberGame</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="main"></div> <div id="enterNumber"> <form action="result.php" method="post"> Enter a number: <input type="text" name="inputnumber" /><br /> <input type="submit" value="Guess" /> </form> </div> </body> </html> Here is the code for the second page: Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>result</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="main"></div> <div id="enterNumber"> <?php $number_actual = rand (1,20); $number_guess = $_REQUEST["inputnumber"]; echo "You chose: " . $number_guess . "<br />"; echo "The random number is: " . $number_actual . "<br />"; if ($number_guess==$number_actual) echo "You guessed <b>Correctly!</b>"; elseif ($number_guess<$number_actual) { echo "You are too <b>Low</b>!"; echo "<br />"; echo "<br />"; echo "Try guessing again..."; echo "<form> <input type='text' name='inputnumber' /> <input type='submit' value='Guess' /> </form>"; } elseif ($number_guess>$number_actual) { echo "You are too <b>High</b>!"; echo "<br />"; echo "<br />"; echo "Try guessing again..."; echo "<form> <input type='text' name='inputnumber' /> <input type='submit' value='Guess' /> </form>"; } ?> </div> </body> </html> Here is what I have so far on my website, you can see it he http://joshkautz.com/phpNumberGame/phpNumberGame.html I think I included everything necessary for people to give input, if not please let me know and I will give more information! Do I need to redo things completely? Any advice would be greatly appreciated. Thanks a ton! Similar TutorialsCan someone help me create this?? Upon outside entry, a random number is chosen between 1 and 10. Use this function to generate the guess number $guessnum = rand(1,10); // you may change the variable name The user tries to guess this number by choosing from a selection list of possibilities. The user "loses" if there are three failed attempts. For reentrant activations the selection list must be sticky and the same guess number must be maintained. The guess number and the attempt number must both be propagated through hidden inputs. Here is a screen shot: Upon outside entry, or using the "Start Over" hyperlink (with the list activated): Let's suppose the number to be guessed is 6. I select 4 and guess it. Response should say "Try #1" I select 9 and guess it. Response should say "Try #2" I select 3 and guess it. Response should say "You Lose" At this point assume that we must "Start Over". This time, suppose the generated number is 8. I select 8 and guess it. Response should say "You Win" Again, assume we must "Start Over". As above, I have a lottery style site that picks a random number between 1-8 but my users complain for some reason that this is not enough. So i was told to look into using fopen and random.org to generate a random number. Anyone have experience of this and perhaps a code snippet for me to look at and possibly use? help will be appreciated. Wow, I have no clue what I'm doing.. I'm trying to make a random game and if you roll a 6, you will win 500 rp and I'm trying to insert the 500 rp into the user who is logged in ($_SESSION['username'). But I... just don't know where to begin. Here is my crappy coding that I just.. am stumped on: <p><?php $dice = rand(1,6); if($dice == 1){ echo "You rolled a <br><b>1</b>"; }if($dice == 2){ echo "You rolled a <br><b>2</b>"; }if($dice == 3){ echo "You rolled a <br><b>3</b>"; }if($dice == 4){ echo "You rolled a <br><b>4</b>"; }if($dice == 5){ echo "You rolled a <br><b>5</b>"; }if($dice == 6){ echo "You rolled a <br><b>6</b>"; } $winner = "500"; if($dice == 6); { include("haha.php"); $cxn = mysqli_connect($dbhost,$dbuser,$dbpassword,$dbdatabase); $sql = "INSERT INTO Member (rp) VALUES ('$winner')"; mysqli_query($cxn,$sql); } ?> Hi!
I was assigned to create a simple php game as a part of my grade, but i got stuck. I'm not really a php expert and this isnt really working. I managed to get some of the code/game working, but it's pointless imo. I'm looking for someone who would take 3 mins and fix this code for me. The game is called "Random number guessing game." From the title you can see that the game is not really complicated.
Code:
<html> <head> <title></title> </head> <body> <h1> Ugani Random!</h1> <? php if(isset($_POST['submit'])) $x = $_POST['x']; $num = $_POST['num']; $x = rand(1, 10) if($num<$x) { echo " Your number is higher! "<br /> } if($num==$x) { echo " Correct! Press Reset to try again! "<br /> } if($num>$x) { echo " Your number is lower! "<br /> } ?> <p> <form> <input type="number" name="quantity"> <br /> <button type="submit" value="<? echo $x?>">Submit</button> <button type="reset" value="<? echo $num?>">Reset</button> </form> </p> </body> </html> I have just did this php code for the high-low game but the $tries variable always goes down to 0 when I refresh..Can someone help me to return the $tries to browser with the url? Thank you
<html>
<?php function High_Low($guess){
I developed this game and I couldn't figure how to make random only on available shot glasses but it would still random with unavailable shot glasses. I simple give up. I plan to share this php once I nailed it down but apparently, not successful. Now, I'm share with you anyway. If you can solve the problem and please let us know! http://pastebin.com/F3N05ExK i wanted to choose 5 random numbers from 0-20. each number represents an index in an array. is there a way to pick out 5 random items from the array. say if random number generator piked a number 22, the last item in the array is at index 20, it wud then have to go to index 0. thanks! hello, i am trying to see how i can pick a random number between 1-15 and exclude certain numbers. so i have a staff list that once a random number is created it inserts it into the staffnumber field. so the next time i create a random number for a staff, i want to make sure that the random number doesnt select an existing staffnumber. thanks! Hi Guys I have a code what inserts very simple queries to database, im trying to add a random reference number for each enrty using $reference = rand(111111111111,999999999999); but each time I add an entry it gives me the same random number previously generated for previous entry can you help pleasE? is there a way to make a random number input into mysql? like if i add a new customer to a table, i want to assign a random number to that customer. I need to choose a random number that doesn't currently exist in the database I'm hoping someone can show me how to get a random decimal number. I've googled and can't find anything that works. I need to find a random number between 1.0 and 10.0 I can get a random whole number no problem, but decimals aren't working. When I finally get that working, ideally I'd like to be able to find a random number between two decimals (like above) but also have a small chance of getting a decimal slightly higher than the two given. So, for example, maybe a random decimal between 3.5 and 6.0, but a slight chance of getting 6.2? Thank you very much for any help! Hi all, sorry cos there is no code. please how can i generate pairs (in twos, threes, fours or five) from a given set of numbers. the numbers are to be typed in the form text field and when click generate(submit button) it brings out the pair of numbers. thanks in advance my form Code: [Select] <form id="form1" name="form1" method="post" action=""> <table width="100%" border="0" cellspacing="2" cellpadding="1"> <tr> <td width="21%">Input Numbers : </td> <td width="79%"><input name="numbers" type="text" id="numbers" size="50" /></td> </tr> <tr> <td> </td> <td><input name="generate" type="submit" id="generate" value="Generate" /></td> </tr> <tr> <td colspan="2"> </td> </tr> <tr> <td colspan="2"> </td> </tr> <tr> <td colspan="2"> </td> </tr> <tr> <td colspan="2"> </td> </tr> </table> </form> Is it possible to remember the last created random number with PHP or do I need to make use of MySQL? I want to generate an equation with submit button 1 and echo it out, and then I want the script to calculate the printed out equation with submit button 2. The problem: As soon as I click submit button 2, the numbers change into different random numbers, since the PHP starts scanning from the top of the file again as soon as the second button has been pressed. $gen = $_POST['gen']; $calc = $_POST['calc']; $x1 = random_number (); $x2 = random_number (); $op = random_op (); echo " <form action='' method='POST'> <input type='submit' name='gen' value='Generate' /><br /> <input type='submit' name='calc' value='Calculate' /> </form> "; if ($gen) { echo "$x1 $op $x2 = ? <br /><br />"; } if ($calc) { switch ($op) { case '+' : $row_1 = $x1 + $x2; break; case '-' : $row_1 = $x1 - $x2; break; case '*' : $row_1 = $x1 * $x2; break; case '/' : $row_1 = $x1 / $x2; break; } echo "$x1 $op $x2 = $row_1"; } I could of course insert the generated numbers into the database and fetch it out again, but I was wondering if it's possible to remember the numbers (even when the 2nd submit buttons has been pressed) within PHP as well? thanks. This isn't for anything practical, I'm just fiddling. Anyways, I'm wondering if there's anyway to make this more efficient since at higher lengths it could become really heavy. $l is length of the number. function fixed_random($l) { $number = ""; do { $r = mt_rand(0, $l); $number .= $r; } while (strlen($number) < $l); return $number; } I am trying to make a function that will generate a random number letter combo but the letters can only be abcde, no others. It must come out in the format, 1a~3d~9b~ etc. This is what I have so far: Code: [Select] function randomNumLet($amount){ $theNos = array('1', '2', '3', '4', '5', '6', '7', '8', '9'); $theLet = array('a', 'b', 'c', 'd', 'e'); $combo = ''; for($i=0;$i<$amount;++$i) { $rand_num = array_rand($theNos, 1); $rand_let = array_rand($theLet, 1); $combo .= $theNos[$rand_num[0]].$theLet[$rand_let[0]].'~'; } return $combo; } $num_let = randomNumLet(2); echo $num_let; And it returns just '~~' with no numbers or letters. I'm a bit stuck here and would appreciate any help. How can I make the function output 1a~4d~ etc? Cheers, Joe I have 3 columns in my DB: email (primary), unique_code, timestamp Users enter their email address and it is added to the DB, including an alphanumeric 5 digit unique code in the 'unique_code' column and a timestamp in the 'timestamp' column. 1. The email address is being added, but not the unique code? What is the issue here and what can I should I specifically do to fix it? 2. The next thing is that I need to display that code to the user in where it says <?php echo $unique_code;?>. How can I do that? DB is as follows: Field Type Collation Attributes Null Default Extra Action email varchar(64) utf8_unicode_ci No None unique_code varchar(64) utf8_unicode_ci No None timestamp timestamp on update CURRENT_TIMESTAMP No CURRENT_TIMESTAMP INDEXES PRIMARY BTREE Yes No email 7 A Full code Code: [Select] <?php require "includes/connect.php"; $msg = ''; if($_POST['email']){ // Requested with AJAX: $ajax = ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'); try{ if(!filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)){ throw new Exception('Invalid Email!'); } $mysqli->query("INSERT INTO coming_soon_emails SET email='".$mysqli->real_escape_string($_POST['email'])."'"); if($mysqli->affected_rows != 1){ throw new Exception('This email already exists in the database.'); } if($ajax){ die('{"status":1}'); } $msg = "Thank you!"; $mysqli->query("INSERT INTO coming_soon_emails VALUES('email', SUBSTRING(MD5(UUID()),FLOOR(RAND()*25),5), UNIX_TIMESTAMP())"); echo "Something went wrong:" . $mysqli->error; } catch (Exception $e){ if($ajax){ die(json_encode(array('error'=>$e->getMessage()))); } $msg = $e->getMessage(); } } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>example</title> <link rel="stylesheet" type="text/css" href="css/styles.css" /> </head> <body> <div id="container"> <form id="form" method="post" action=""> <input type="text" id="email" name="email" value="<?php echo $msg?>" /> <input type="submit" value="Submit" id="submitButton" /> </form> <div id="thankyou"> Thank you! <?php echo $unique_code;?></p> </div> </div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script> <script src="js/script.js"></script> </body> </html> Thank you! Hello, I'm currently creating a little script, and want to assign a random number to a row in the MySQL table as soon as it will be inserted. But that number may not have been used before. How will I do this? I tried if else thingies, but then the code would be very long (just in case it randomly picks 10 times after each other a number that exists). $randomnumber = rand(10000000, 99999999); if(mysql_num_rows(mysql_query("SELECT * FROM table WHERE randomnumber='".$randomnumber."')) == 1) { $randomnumber = rand(10000000, 99999999); if(mysql_num_rows(mysql_query("SELECT * FROM table WHERE randomnumber='".$randomnumber."')) == 1) { $randomnumber = rand(10000000, 99999999); }else { // Insert into database } }else { // Insert into database } I hope you understand my problem. Regards, How to generate a unique random number in php??? Any one who can help me? I'm looking for a random number generator, that chooses a number every hour, and when it does it will be out of 100 (these are player ID's) once the number is chosen, I would like 10 Crystals (special payment) to be given to the number (ID). Is this possible and if so, please help. This is all I have (generator) function createRandomAGTNO() { do { $agt_no = mt_rand(1,100); $valid = true; if (preg_match('/(\d)\1\1/', $agt_no)) $valid = false; // Same digit three times consecutively elseif (preg_match('/(\d).*?\1.*?\1.*?\1/', $agt_no)) $valid = false; // Same digit four times in string } while ($valid === false); return $agt_no; } Please reply ASAP? |