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;
}
Related
<?php
if (isset($_GET['number'])){ // Loaded for first time?
if(isValid($_GET['number'])){
$isPrime = true;
// Please enter code here
// I have tried the codes here but idk why it cannot seem to work
$i = $_GET(['number']);
if ($number == 1) {
$isPrime = false;
return $isPrime;
}
for ($j = 2; $i <= $number/2; $i++){
if ($number % $i == 0)
$isPrime = false;
return $isPrime;
}
return $isPrime;
// End of code
if ($isPrime) {
echo "<p>".$i." is a prime number!</p>";
} else {
echo "<p>".$i." is not prime.</p>";
}
} else{
// User submitted something which is not a positive whole number
echo "<p>Please enter a positive whole number.</p>";
}
}
// check if the given number is a valid numeric value
// round() rounds a floating point value
function isValid($number) {
if(is_numeric($number) && $number > 0
&& $number == round($number, 0)) {
return true;
}
else {
return false;
}
}
?>
I have tried the above codes, however, I have encountered issues. Please help me out thank you! The codes I have tried are within the // Please enter code here to // End of code
When I run the php file the above image will be shown. The user have to type a number and it will check whether or not the user input is a prime number when user clicks on the "Go!" button.
You had many mistakes.
So I edited the whole code.
here it is:
<?php
if (isset($_GET['number'])) { // Loaded for first time?
if (isValid($_GET['number'])) {
$isPrime = true;
// Please enter code here
// I have tried the codes here but idk why it cannot seem to work
$i = $_GET['number'];
if ($i == 1) {
$isPrime = false;
}
for ($j = 2; $j <= $i / 2; $j++) {
if ($i % $j == 0)
$isPrime = false;
}
// End of code
if ($isPrime) {
echo "<p>" . $i . " is a prime number!</p>";
} else {
echo "<p>" . $i . " is not prime.</p>";
}
} else {
// User submitted something which is not a positive whole number
echo "<p>Please enter a positive whole number.</p>";
}
}
// check if the given number is a valid numeric value
// round() rounds a floating point value
function isValid($number)
{
if (is_numeric($number) && $number > 0
&& $number == round($number)) {
return true;
} else {
return false;
}
}
?>
<form action="index.php" method="get">
<input type="number" name="number">
<input type="submit" value="Go!">
</form>
I'm new to php and have been struggling to get my rock, paper, scissors game to work! I know what I'm trying to do but just can't get my head aound where I've gone wrong......it works for rock but for paper and scissors I'm getting two outputs!!Please help a novice out...thanks!!
P.S I know there are much slicker ways of doing this!!
<?php
// user enters a value R P or S - NEED TO RETURN A COUPLE OF
TIMES AFTER, not sure why?
echo "What do you select - R for rock, P for paper or S for
scissors?\n";
$input=
$R = stream_get_line(STDIN, 1, "\n");
$P = stream_get_line(STDIN, 1, "\n");
$S = stream_get_line(STDIN, 1, "\n");
//program converts the value into Rock, Paper or Scissors
switch ($input) {
case 'R' :
case 'r':
echo $R = "You selected Rock\n" ;
break;
case 'P' :
case 'p':
echo $P = "You selected Paper\n" ;
break;
case 'S' :
case 's':
echo $S = "You selected Scissors\n" ;
break;
}
//computer generates a random value 0,1,2 & converts to R P or S
echo "\nComputer is now making its selection....\n";
//$options = ('Rock=0, Paper=1, Scissors=2');
$output = (rand(0,2) );
echo $output;
if ($output== 0)
{
echo "\nComputer Selected Rock\n"; //goto Rock;
}
elseif ($output==1)
{
echo "\nComputer Selected Paper\n"; //goto Paper;
}
elseif ($output==2)
{
echo "\nComputer Selected Scissors\n"; //goto Scissors;
}
//compare user and computers choise
Rock:
if ($R && $output===0)//.($P && $output==1),($S && $output==2))
{
echo "\nITS A DRAW";
}
elseif ($R && $output===1)//.($P && $output==2).($S &&
$output==0))
{
echo "\nCOMPUTER WINS";
}
elseif ($R && $output===2)//.($P && $output==0).($S &&
$output==1))
{
echo "\nYOU WIN";
}
Paper:
if ($P && $output===1)
{
echo "\nITS A DRAW";
}
elseif ($P && $output===2)
{
echo "\nCOMPUTER WINS";
}
elseif ($P && $output===0)
{
echo "\nYOU WIN";
}
Scissors:
if ($S && $output===2)
{
echo "\nITS A DRAW";
}
elseif ($S && $output===0)
{
echo "\nCOMPUTER WINS";
}
elseif ($S && $output===1)
{
echo "\nYOU WIN";
}
You should inicialize $R, $P and $S to false first. Then read user input 1x into $input.
The rest of the script seams to be ok.
<?php
$R = $P = $S = false;
$input= stream_get_line(STDIN, 1, "\n");
// user enters a value R P or S - NEED TO RETURN A COUPLE OF TIMES AFTER, not sure why?
because
$input=
$R = stream_get_line(STDIN, 1, "\n");
$P = stream_get_line(STDIN, 1, "\n");
$S = stream_get_line(STDIN, 1, "\n");
You're calling stream_get_line() three times so your script wants three lines of input.
Also, I'm not sure if this was intended, but you're getting your user input seemingly purely by chance as $input = $R = stream_get_line() stores the first user input in $R and $input.
I'd suggest only doing $input = stream_get_line() and nothign else.
Then in your switch/case block you do e.g. echo $R = "..."; and further down you do if ($R && ...).
Evaluating strings as booleans is not recommended.
I would recommend something like
$R = $P = $S = false; // initialize all variables to false
switch ($input)
{
case "R":
$R = true; // set selected variable to true
echo "You have selected Rock\n";
break;
// ...
}
Finally, you seem to be using jump marks to comment your code.
Rock:
if ( ...
While this doesn't cause any problems (yet), it's generally considered bad style to abuse language features for documentation purposes.
These should become comments:
// Rock
if ( ...
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.
can any body help me how I can delete the white space at the end of the output.
This might be easy question but to be honest it took me more than 45 minutes and still nothing. Assignment
Write a PHP script that prints the numbers from the number inputted on form to zero. The numbers should be separated with a single space but the last number, zero, should not have a space after it. If the user inputs a number smaller than zero, print “The number should be at least zero!” The used form looks like this:
Luku:
Example output
5 4 3 2 1 0
my code:
<?php
$number=$_GET["number"];
if ($number < 0){
echo "The number should be at least zero!";
} else {
for($i=$number; $i>=0; $i=$i-1)
{
echo $i." ";
}
}
?>
You can use trim()
<?php
$number=$_GET["number"];
if ($number < 0){
echo "The number should be at least zero!";
} else {
$num = '';
for($i=$number; $i>=0; $i=$i-1)
{
$num .= $i." ";
}
echo trim($num);
}
?>
Try this:
echo implode(" ",range($number,0));
Magic and trickery ;)
You can use rtrim instead of trim to delete white spaces at the end of the string:
<?php
$number=$_GET["number"];
if ($number < 0){
echo "The number should be at least zero!";
} else {
for($i=$number; $i>=0; $i=$i-1)
{
$num .= $i." ";
}
}
$num = rtrim($num);
?>
You could use an if-statement:
<?php
$number=$_GET["number"];
if ($number < 0) {
echo "The number should be at least zero!";
} else {
for($i=$number; $i>=0; $i=$i-1)
{
echo $i . ($i != 0 ? " " : "");
}
}
Or you use trim:
<?php
$number=$_GET["number"];
$output = "";
if ($number < 0) {
echo "The number should be at least zero!";
} else {
for($i=$number; $i>=0; $i=$i-1)
{
$output .= $i . " ";
}
}
echo trim($output);
try this:
<?php
$number=$_GET["number"];
if ($number < 0) {
echo "The number should be at least zero!";
} else {
$string = $number;
for($i=$number-1; $i>=0; $i=$i-1)
{
$string .= " $i";
}
}
echo $string;
?>
I have a value as a number. For instance, 502.
I want to write a php if statement that will display some text if the value is lesser or greater than certain numbers, or between a range.
E.g.
number is 502, text will say: "Between 500-600"
number is 56, text will say: "Between 0-60"
etc.
So far I have this:
<?php $count=0;?>
<?php $board = getUserBoard($userDetails['userId']);?>
<?php if(is_array($board)):?>
<?php $boardCount = count($board);?>
<?php foreach($board as $key=>$value):?>
<?php
$boardPin = getEachBoardPins($value->id);
$count = $count + count($boardPin);
?>
<?php endforeach?>
<?php endif?>
And that gives me a number:
<?php echo $count;?>
I have tried writing...
<?php if(($count)): => 500 ?>
Over 500
<?php endif ?>
But I keep running into errors.
I'd like to create a list if possible with elseif statements denoting various number ranges.
E.g.
0-50, 51-250, 251-500 etc.
Can anyone help me?
Thanks.
The sanest, neatest and most widely used syntax for if conditions in PHP is:
if($value >=500 && $value <=600 )
{
echo "value is between 500 and 600";
}
if ($count >= 0 && $count < 100) {
echo 'between 0 et 99';
} elseif ($count < 199) {
echo 'between 100 and 199';
} elseif { ...
}elseif ($count < 599) {
echo 'between 500 and 599';
} else {
echo 'greater or equal than 600';
}
I wrote something like this a few years back (might be a better way to do it):
function create_range($p_num, $p_group = 1000) {
$i = 0;
while($p_num >= $i) {
$i += $p_group;
}
$i -= $p_group;
return $i . '-' . ($i + $p_group - 1);
}
print 'The number is between ' . create_range(502, 100) . '.';
It'll say 500-599, but you can adjust it to your needs.
I'm not sure what you need, but here is what I understand you ask:
function getRange($n, $limit = array(50, 250, 500)) { // Will create the ranges 0-50, 51-250, 251-500 and 500-infinity
$previousLimit = 0;
foreach ($limits as $limit) {
if ($n < $limit) {
return 'Between ' . ($previousLimit + 1) . ' and ' . $limit; //Return whatever you need.
}
$previousLimit = $limit;
}
return 'Greater than ' . $previousLimit; // Return whatever you need.
}
echo getRange(56); // Prints "Between 51 and 250"
echo getRange(501); // Prints "Greater than 500"
echo getRange(12, array(5, 10, 15, 20)); // Prints "Between 11 and 15"
function getRange($number){
$length=strlen($number);
$length--;
$r1=round($number,-$length);
if ($r1>$number){
$r2=$r1-pow(10,$length);
return ''.$number.' value is between '.$r2.'-'.$r1;
}
else {
$r2=$r1+pow(10,$length);
return ''.$number.' value is between '.$r1.'-'.$r2;
}
}
Try this.