I am learning php atm and i decided to make a simple game but now im confronted with a problem. I have the following code:
<form action="wolf.php" method="POST">
<input type="submit" value="Attack" name="submit"/> <br />
<?php
$hp = 100;
if(isset($_POST['submit'])) {
$attack = $_POST['submit'];
$damage = mt_rand(5, 30);
$newhp = $hp - $damage;
if ($attkdamage = $hp - $damage ) {
echo "Your HP is: ". $newhp . "<br / >";
echo "You took: " . $damage . " damage!";
}
}
?>
As you can see I have a variable with an integer (100) and a simple mt rand. What I want is that after I submit and get a $newhp (100 - the random number), that number to replace $hp. and the next time I submit the button I want the value of $damage to be subtracted from the previous action, so basically to save the $newhp as $hp.
If possible storing this value in a session variable that will be saved in the browser you use, for more information read here $_SESSION
<?php
session_start();
if(!isset($_SESSION["hp"]))
$_SESSION["hp"]=100;
if(isset($_POST['submit'])) {
$attack = $_POST['submit'];
$damage = mt_rand(5, 30);
$newhp = $_SESSION["hp"] - $damage;
if ($attkdamage = $_SESSION["hp"] - $damage ) {
echo "Your HP is: ". $newhp . "<br / >";
echo "You took: " . $damage . " damage!";
}
echo "<pre>previus hp " .$_SESSION["hp"];
$_SESSION["hp"]= $newhp;
echo "next hp " . $_SESSION["hp"]."</pre>";
}
?>
Related
I want to create an application that shows multiplication, addition, subtraction and division with 2 random numbers. I made a function that shows random numbers:
function Numbers() {
echo(mt_rand() . "<br>");
echo(mt_rand() . "<br>");
echo(mt_rand(1,10));
}
Numbers();
Can someone explain to me how I can make it go +/- and x each other?
I now changed my code to this:
function Numbers() {
$Number1= echo(mt_rand() . "<br>");
$Number2= echo(mt_rand() . "<br>");
$Number1 + $Number2;
$Number1 - $Number2;
$Number1 / $Number2;
}
Numbers();
Here's an example for the addition, you figure out the rest:
$a = mt_rand();
$b = mt_rand();
echo "$a + $b = " . ($a + $b);
function printRnd()
{
$a_ = rand(1,10);
$b_ = rand(1,10);
echo "a={$a_}, b={$b_}<br><br>";
$plus_ = $a_+$b_;
$minus_ = $a_-$b_;
$multi_ = $a_*$b_;
$divid_ = $a_/$b_;
echo "a+b={$plus_}<br>";
echo "a-b={$minus_}<br>";
echo "a*b={$multi_}<br>";
echo "a/b={$divid_}<br>";
}
printRnd();
$number1 = mt_rand(1,9);
$number2 = mt_rand(1,9);
$total = $number1 * $number2;
echo "<form method='post'>";
echo $number1 . " x " . $number2 . " = <input type='number' name='num1' required /><br>";
echo "<input type='submit' value='submit!' name='done'>";
echo "</form>";
if (isset($_POST['done'])) {
if (isset($_POST['num1']) == $total) {
echo "Correct!";
} else {
echo "Wrong!";
}
}
It always says Correct! And I dont know why ( im a beginner ), I just want to check if num1 is equal to $total
You have many problems in your code :
you must first check if the post is submit then if its wrong type the form
if (isset($_POST['done'])) {
//your code
}
else {
//your form
}
save $total in session to reuse it when the form submit, in your case $total have different value every time
isset() return true or false you can't comparison true or false with integer value if you want to use isset your code must be like this:
if(isset($_POST['num1']) && $_POST['num1'] == $total) {
}
You're comparing isset($var) to $total. They're both truthy so the condition is always true as long as 'num1' is defined in your POST data.
Maybe you should do something like :
isset($_POST['num1']) && $_POST['num1'] == $total
You should also probably cast 'num1' to a number
As said by Tom Udding, every time you refresh the page it calls ALL of that code again, so number1 and number2 are being randomly selected again.
Your current code has no way of saving the previous variable values. An unconventional way would be to add a hidden form field with the answer to the question, like below:
<?php
if (isset($_POST['done']) && isset($_POST['num1']))
{
//Get answer from form.
$total = $_POST['answer'];
if ($_POST['num1'] == $total)
{
echo "Correct!";
}
else
{
echo "Wrong!";
}
}
$number1 = mt_rand(1, 9);
$number2 = mt_rand(1, 9);
$total = $number1 * $number2;
echo "<form method='post'>";
echo $number1 . " x " . $number2 . " = <input type='number' name='num1' required /><br>";
//Added hidden form with answer.
echo "<input type='number' hidden name='answer' value='$total' />";
echo "<input type='submit' value='submit!' name='done'>";
echo "</form>";
?>
HOWEVER...
In a realistic rich web application, you wouldn't put your answer in your form for users to see, this is where you can use sessions to track your user's information as they traverse (or in your case refresh) your page.
So a more practical answer to your question would be the following:
<?php
session_start();
if (isset($_POST['done']) && isset($_POST['num1']))
{
$answer = $_SESSION['answer'];
if ($_POST['num1'] == $answer)
{
echo "Correct!";
} else
{
echo "Wrong!";
}
}
$number1 = mt_rand(1, 9);
$number2 = mt_rand(1, 9);
$total = $number1 * $number2;
$_SESSION['answer'] = $total;
echo "<form method='post'>";
echo $number1 . " x " . $number2 . " = <input type='number' name='num1' required /><br>";
echo "<input type='number' hidden name='answer' value='$total' />";
echo "<input type='submit' value='submit!' name='done'>";
echo "</form>";
?>
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.
This is my code:
<?php
$friendid = 10;
$friendname = "enco";
$max=count($_COOKIE['rooms']);
$i = $max + 1;
setcookie("rooms[$i]['type']", "1on1", time() + 3600, "/", ".mywebsite.com");
setcookie("rooms[$i]['name']", $friendname, time() + 3600, "/", ".mywebsite.com");
?>
The code below is in another page:
<?php
$max=count($_COOKIE['rooms']);
$k = 0;
for($k = 0; $k<$max; $k++) {
echo "Cookie 1 show: " . $_COOKIE['rooms'][$k]['type'] . "<br /><br />";
echo "Cookie 2 show: " . $_COOKIE['rooms'][$k]['name'] . "<br /><br />";
}
?>
But it does not work.
When I try to echo the cookies like I did in the example above, nothing appears.
My question is:
Are these structures correct:
setcookie("rooms[$i]['type']", "1on1", time() + 3600, "/", ".mywebsite.com");
setcookie("rooms[$i]['name']", $friendname, time() + 3600, "/", ".mywebsite.com");
in order to show these in another page (not in the same page where the cookies are written):
echo "Cookie 1 show: " . $_COOKIE['rooms'][$i]['type'] . "<br /><br />";
echo "Cookie 2 show: " . $_COOKIE['rooms'][$i]['name'] . "<br /><br />";
Thanks
PHP's superglobals _GET, _POST, _REQUEST, _COOKIE are all created at script startup, and then NEVER modified by PHP for the duration of the script's execution.
The cookie you create with setcookie() will therefore NOT be available in _COOKIE until the NEXT time you run this code.
I've looked online but all the $_POST and $_GET examples are for text not numbers.
This is not connecting to a database. It doesn't need form validation. It's just a single page project running locally on my system. I want to keep it as simple as possible.
The goal is to have an input where you can put in your hourly pay. For example 15.
Then when you press submit it posts back to the same page with a nice list of how much you make daily, weekly, monthly, and yearly.
Any help would be greatly appreciated.
<p>Input your Hourly Pay</p>
<form method="GET" action="" >
<input name="num1" type="text" >
<input type="submit" name="submit" value="Submit">
</form>
<?php
if ($_GET['num1']) {
$rate = $_GET['num1'];
return $rate;
}
$result_day= $rate * 8;
$result_week = $rate * 8 * 5;
$result_month = $rate * 8 * 5 * 4;
$result_year = $rate * 8 * 5 * 4 * 12;
echo "Rate: " . $rate . "<br>";
echo "Daily: " . $result_day . "<br>";
echo "Weekly: " . $result_week . "<br>";
echo "Monthly: " . $result_month . "<br>";
echo "Yearly: " . $result_year . "<br>";
?>
I did some correction, but the calculation is still your original:
<?php
if (isset($_GET['num1'])) {
$rate = $_GET['num1'];
$result_day= $rate * 8;
$result_week = $result_day * 5;
$result_month = $result_week * 4;
$result_year = $result_month * 12;
echo "Rate: " . $rate . "<br>";
echo "Daily: " . $result_day . "<br>";
echo "Weekly: " . $result_week . "<br>";
echo "Monthly: " . $result_month . "<br>";
echo "Yearly: " . $result_year . "<br>";
}else{
echo "Please enter your rate!";
}
Use the onchange event with Javascript on any of the fields. You can then use Javascript to calculate the rest of the values and update those fields.
No PHP required. No time lag with a new page required. Users will love it.