February 23, 201016 yr Allright so I have this PHP homework, basically I have to allow a user to enter a number into a text box between 10 and 60. PHP is then required to "simulate a dice rolling" 10 times using a for loop. The 10 "rolls" are then added together and compared to the users entry in the text box. It's a basic game, if the user guesses correctly they win etc. etc. Anyway, the code should explain things better, the only problem i am having is that the maximum of 10 rolls of the dice should be 60, but occasionally the result is more than this, more than often the number 66. Have no idea why its doing this. I've tried my best to explain, please ask questions if you don't understand what the hell im rambling on about. Cheers. Ignore the lack of standards in my markup. HTML <html> <head><title>question two html</title></head> <body> <form action="Q2.php" method="post"> <br> <h1>Enter a number between 10 and 60 in the box below. This is your guess. The object of the game is to try and get as close to the number the program calculates. .</h1> <br> <input type="text" maxlength="2" name="usersguess"> <br> <p> <input type="submit" value="Submit"> </p> <p> <input type="reset" value="Reset Form"> </p> </form> </body> </html> PHP <html> <head><title>question two php</title></head> <body> <?php $guess=$_POST["usersguess"]; $dice=rand(1,6); $sum; for ($i = 0; $i <= 10; $i++) { $dice; $sum= $sum + $dice; } $diff= abs($guess-$sum); if($guess<=9 || $guess>=61){ print "Invalid entry. Please enter a number between 10 and 60."; } elseif($guess==$sum){ print "WINNER!.You guessed $guess and the dice rolled $sum."; } elseif($diff<=5){ print "You were within 5. Unlucky !.You guessed $guess and the dice rolled $sum."; } else{ print "Unlucky this time.You guessed $guess and the dice rolled $sum."; } ?> </body> </html>
February 23, 201016 yr Change: for ($i = 0; $i <= 10; $i++) To: for ($i = 1; $i <= 10; $i++) Otherwise the first loop leaves i as 0, thus 11 loops occur Edit (noticed new problems): Replace (from your original post) this: $guess=$_POST["usersguess"]; $dice=rand(1,6); $sum; for ($i = 0; $i <= 10; $i++) { $dice; $sum= $sum + $dice; } With this: $guess = $_POST['usersguess']; $sum = 0; for ($i = 1, $i <= 10; $i++) { $dice = rand(1,6); $sum += $dice; } Edited February 23, 201016 yr by andyl
February 23, 201016 yr From quickly looking at it - I would have thought that the $dice=rand(1,6); line needs to be inside the for loop - or it will give you the same number for every roll. If the random number is 6 in your current script you are running the script from 0 to 10 so that the total number of rolls is 11 - if 6 is selected this will give you 66 as the total number? I may be wrong but at a quick glance this is how it looks. Good Luck
February 23, 201016 yr Author Cant believe I missed that. Thanks very much andyl and siriusfire. Everything works fine now.
Create an account or sign in to comment