This is a game of guessing number, I want the page to keep track of the wins, losses and totals and the %of winning by using sessions. I want to reset everything when I click "reset", but when I click reset everything equals to zero and there will be a warning saying "dividing by zero". How do I rearrange this php for it to only do the %calculation when the game is played but not when it's being reset?
<?php
// initialize wins and losses
if ($_SESSION['wins'] == "") {
$_SESSION['wins'] = 0;
}
if ($_SESSION['losses'] == "") {
$_SESSION['losses'] = 0;
}
echo "<h1>PHP SESSIONS</h1>";
if ($_GET['reset'] == "yes") {
$_SESSION['wins'] = 0;
$_SESSION['losses'] = 0;
$_SESSION['total'] = 0;
echo "<p>The game has been reset.</p>";
} else {
$randNum = rand(1,5);
echo "<p>The random number is <b>" . $randNum . "</b></p>";
if ($randNum == 3) {
echo "<p>The number equalled 3. YOU WIN!</p>";
$_SESSION['wins'] = $_SESSION['wins'] + 1;
} else {
echo "<p>The number did NOT equal 3. YOU LOSE!</p>";
$_SESSION['losses'] = $_SESSION['losses'] + 1;
}
$_SESSION['total'] = $_SESSION['total'] + 1;
}
$_SESSION ['percentage'] = (($_SESSION['wins']) / ($_SESSION['total'])) * 100 ;
echo "<p>WINS: " . $_SESSION['wins'] . " | LOSSES: " . $_SESSION['losses'] . "| TOTAL: " . $_SESSION['total'] . "</p>";
echo "<p>Percentage of Winning: ". $_SESSION ['percentage'] . " % </p>"
?>
ROLL AGAIN :)
RESET :)
Move up the line in which you are dividing:
$_SESSION ['percentage'] = (($_SESSION['wins']) / ($_SESSION['total'])) * 100 ;
Put it inside the else bracket. Once I reformatted your code, it was easy to see the problem. I'd advise always using proper indenting. :)
When $_GET['reset'] == 'yes' is satisfied, you are setting $_SESSION['total'] = 0.
Then, you're dividing $_SESSION['wins'] by a 0 valued $_SESSION['total'] in the following line (which is executed regardless of the current state of $_SESSION['total']:
$_SESSION ['percentage'] = (($_SESSION['wins']) / ($_SESSION['total'])) * 100 ;
It's easier to see what's going on when the code is properly formatted. Have a look:
if ($_GET['reset'] == "yes") { // reset called
$_SESSION['wins'] = 0;
$_SESSION['losses'] = 0;
$_SESSION['total'] = 0; // set to zero(0)
echo "<p>The game has been reset.</p>";
} else {
$randNum = rand(1,5);
echo "<p>The random number is <b>" . $randNum . "</b></p>";
if ($randNum == 3) {
echo "<p>The number equalled 3. YOU WIN!</p>";
$_SESSION['wins'] = $_SESSION['wins'] + 1;
} else {
echo "<p>The number did NOT equal 3. YOU LOSE!</p>";
$_SESSION['losses'] = $_SESSION['losses'] + 1;
}
$_SESSION['total'] = $_SESSION['total'] + 1;
}
$_SESSION ['percentage'] = (($_SESSION['wins']) / ($_SESSION['total'])) * 100; // chance that $_SESSION['total'] is zero(0)
So again, when you call the reset action, $_SESSION['total'] is given a value of int(0). Later in the script you then divide by that int(0), giving you the error in question. Make sense?
So you first need to ensure $_SESSION['total'] is greater than 0 before dividing by it.
Related
I've been working on a console-based Hangman Game with PHP and have come across a somewhat big issue.
When the user guesses the correct word, it functions as needed. It reveals the letter and continues to ask the user to guess the next.
Now, the issue comes when the player gets it wrong. My intentions were when the user gets a letter wrong, the $playerErrors variable gets +1 value, and once $playerErrors has a value of 6, aka the player has made 6 wrong guesses, the program terminates. This is not what happens however, instead, if the word they're guessing has 5 letters for example, and they guessed 1 letter wrong, they will get +5 $playerErrors instead of just +1 $playerErrors.
So as a result of the player getting say 5 $playerErrors in one guess, the player will really only have 1 or 2 lives instead of 6.
Here is the code from the main section:
while ($playerErrors < 6) {
if (strpos($shwWord, '_') === false){
echo "You won! Congratulations!\n";
break;
}
$guess = readline('Guess a letter: ');
for ($g = 0; $g < count($secretArray); $g+=1) {
if ($guess === $secretArray[$g]){
$displayedLetters[$g] = $guess;
}
else{
$playerErrors += 1;
echo "Errors: " . $playerErrors;
echo "\n";
}
}
$shwWord = implode(' ', $displayedLetters);
echo "\n $shwWord \n\n";
}
if ($playerErrors >= 6) {
echo "you lost" . PHP_EOL;
}
You are incrementing the errors within your 'check letters' loop, meaning that you increment once for each 'wrong letter'.
Try this code:
while ($playerErrors < 6) {
if (strpos($shwWord, '_') === false){
echo "You won! Congratulations!\n";
break;
}
$guess = readline('Guess a letter: ');
$foundLetter = false;
for ($g = 0; $g < count($secretArray); $g+=1) {
if ($guess === $secretArray[$g])
{
$displayedLetters[$g] = $guess;
$foundLetter = true;
}
}
if (!$foundLetter)
{
$playerErrors += 1;
echo "Errors: " . $playerErrors;
echo "\n";
}
$shwWord = implode(' ', $displayedLetters);
echo "\n $shwWord \n\n";
}
if ($playerErrors >= 6) {
echo "you lost" . PHP_EOL;
}
I'm trying to add up all numbers that are output in my code, how can I do this?
$tall1 = 0;
for ($tall1=0; $tall1 <= 100; $tall1++) {
if ($tall1 % 3 == 0) {
echo $tall1 . " ";
$tall++;
}
}
$total = 0; //initialize variable
for ($tall1=0; $tall1 <= 100; $tall1++) {
if ($tall1 % 3 == 0) {
echo $tall1 . " ";
$total += $tall1; //add the printed number to the previously initialized variable. This is the same as writing $total = $total + $tall1;
}
}
echo "total: ".$total; //do something with the variable, in this case, print it
Some notes about your initial code:
$tall1 = 0; //you don't need to do this, it is done by the for loop
for (
$tall1=0; //this is where $tall1 is initialized
$tall1 <= 100;
$tall1++ //this is where $tall1 is incremented every time
) {
if ($tall1 % 3 == 0) {
echo $tall1 . " ";
$tall++; //this variable is not used anywhere. If you meant $tall1, then you don't need to do this, it is done by the for loop. If you did not mean $tall1, but wanted to count how many times the if statement runs, then you need to initialize this variable (place something like $tall=0; at the top)
}
}
I'm currently learning how to use do/while loops in PHP through codeacademy. I'm working on a challenge where you create a six-sided die and continue rolling until you get a six. Here's what I've come up with so far:
<?php
$roll = 1;
do {
echo “Roll Number " . $roll . ". Begin rolling for a 6.";
} while ($roll != 6); {
for ($rollNumber = 1; $roll != 6; $roll ++) {
$roll = rand(1, 6);
echo "On roll number " . $rollNumber . "You got a " $roll ".\n";
};}
?>
I though the best way to get started is by creating a roll variable that we can use once for the do loop to check if it's working:
$roll = 1;
I set the value to one instead of zero, because there's no zero number on a die, and we'll assume the player first rolls a one. Next I want to check if the do loop is working so I echo the following:
do {
echo “Roll Number " . $roll . ". Begin rolling for a 6.";
}
After making sure the do loop worked, I create the while condition:
while ($roll != 6) {
Then I want to create a rollNumber variable to keep track of what roll I'm on and increment it:
for ($rollNumber = 1; $roll != 6; $roll ++) {
next I set the value of the roll variable so that it generates a random number between 1 and 6:
$roll = rand(1,6);
Finally I want to echo the message "On roll number you got a ." :
echo “On roll number “ . $rollNumber . "You got a " $roll “.\n";}
For some reason the code's not working. Any suggestions or help would be much appreciated! Thanks.
You were on the right track with a while loop and rand(). The only other thing you needed was to set a count variable to display the roll number (you can just increment this variable on every "roll").
Your code could be simplified to this:
$c = $n = 1;
while ($n != 6) {
echo 'on roll number ' . $c++ . ' you rolled a ' . $n = rand(1, 6) . "\n";
}
Here's an example
You've made this way too complicated. There's no need for two loops.
$rolled = 0;
$numbers = range(1, 6); //generate array with 1-6
$counter = 0;
while($rolled!=6)
{
$counter++;
shuffle($numbers); //shuffle array
$rolled = $numbers[0]; //grab first item
echo '<br/>(Roll ' . $counter . ') ' . $rolled;
}
Why not have a function that returns the result of a roll, and then a loop that calls this function until it returns a 6?
<?php
function roll() {
return mt_rand(1, 6);
}
$roll = 1;
do {
if (roll() == 6) {
printf('You rolled a 6 on roll %d.', $roll);
break;
}
$roll++;
} while (0);
This do/while loop continues until the roll() function returns a 6.
I am trying to construct a php script that will page through an API. The api return ~25197 XML records. I am able to pass a start_offset and a end_offset to the API which will return a subset of the results.
The challenge I am having is that the for loop is not capturing the remaining records that are not within the 1000.
Example, the current for loop processes the records in blocks of 1000 (0-1000,1001-2000,2001-3000, etc.) I am not able to get the final block - 25,000 to 26,000. The for loop stop processing at 24,000 - 25,000. This leaves me with 197 unprocessed XML results.
<?php
//Set Start and Offset Parameters
$start_offset = 0;
$end_offset = 0;
$items_per_page = 1000;
$number = 0;
$counter = -2;
for ($count=0; $count<=100; $count++) {
$counter++;
//Validate that the counter is not null
if ($number != null){
echo "\n";
echo file_get_contents($static_url . "/sc_vuln_query-compliance.php?start=$start_offset&end=$end_offset&seq=$counter");
}
//Initialize the start and end offset variables
$end_offset = $number+=$items_per_page;
$start_offset = $number-$items_per_page+1;
//We want to start at record 0, reset start_offset back to 0 instead of 1
if($start_offset == 1) {
$start_offset = $number-$items_per_page;
}
// We are at the end of the total records, display the remaining
if ($number>$total_xml_records) {
$counter = $counter+1;
$padding = $end_offset + $items_per_page;
echo "\n";
echo file_get_contents($static_url. "/sc_vuln_query-compliance.php?start=$start_offset&end=$padding&seq=$counter");
break;
}
}
?>
Your code is at least buggy at this line $padding = $end_offset + $items_per_page; - here you raise the end for your last loop by another 1000 and therefor get ?start=25001&end=27000&seq=25.
Try $padding = $total_xml_records; instead, this will get you ?start=25001&end=25197&seq=25.
Anyway your code is quite complicated. Try this:
$total_xml_records = 25197; // index 0 .. 25196
$offset = 0;
$counter = 0;
while ($offset < $total_xml_records) {
echo "\n";
echo $static_url . "/sc_vuln_query-compliance.php?start=".($offset)."&end=".(min($offset+$items_per_page-1, $total_xml_records-1))."&seq=".($counter++);
$offset += $items_per_page;
}
I have this JavaScript equation which I'm now trying to transform to PHP.
JavaScript:
LVL=new Array();
LVL[1]=128;
LVL[0]=128;
m=.05;
for (i=1;i<101;i++) {
if (i>1) {
LVL[i]=Math.floor(LVL[i-1]+(LVL[i-1]*m));
m=m+.0015;
}
}
then it's a bunch of document.writes of a table and a for loop.
Here's what I have so far (which is NOT working):
<?php
$n = 1; // level
$m = .05; // exp modifier
$exp = floor($n*1+($n-1)*$m);
echo "Level " . $n . ", exp needed: " . $exp; // 128 exp
?>
The PHP output is: Level 1, exp needed: 1 and that's WRONG.
It SHOULD say: Level 1, exp needed: 128
What am I doing wrong?
A direct transcription:
$LVL = array();
$LVL[1] = 128;
$LVL[0] = 128;
$m = .05;
for ($i = 1; $i < 101; $i++)
{
if ($i > 1)
{
$LVL[$i] = floor($LVL[$i-1] + $LVL[$i-1]*$m);
$m = $m + .0015
}
}
You need to build the array as its built bottom-up
You do a couple of errors:
you use the index (the level) as it is the amount of the experience points needed to
reach the level.
you forgot the for (if you are testing the formula it is ok)
the code so far:
$lvl = array(128,128);
$modifier=.05;
for ($i=1;$i<101;i++) {
$lvl[$i]=floor($lvl[$i-1]*(1+$modifier));
$modifier+=0.0015;
}
foreach ($lvl as $level=>$points) {
echo "Level " . $level . ", exp needed: " . $points ."\n<br />"; // 128 exp
}