I have 5 variables that generate a random number and a sixth variable which is the users input.
Then I check to see if users input $userNum matches any of the random numbers. I know it's a dumb game, but I'm just messing around to learn more PHP
There has to be an easier way to do this.
if(isset($_POST['submit']))
{
$userNum = $_POST['userNum'];
$spot1 = rand(1, 100);
$spot2 = rand(1, 100);
$spot3 = rand(1, 100);
$spot4 = rand(1, 100);
$spot5 = rand(1, 100);
echo $spot1 ."<br>" .$spot2 ."<br>" .$spot3 ."<br>" .$spot4 ."<br>" .$spot5;
if($userNum == $spot1)
{
echo "you hit a mine!";
exit();
}
if($userNum == $spot2)
{
echo "you hit a mine!";
exit();
}
if($userNum == $spot3)
{
echo "you hit a mine!";
exit();
}
if($userNum == $spot4)
{
echo "you hit a mine!";
exit();
}
if($userNum == $spot5)
{
echo "you hit a mine!";
exit();
} else {
echo "you lived!";
}
}
You don't need to store spots in an array or anything like that just use a simple loop.
<?php
if(isset($_POST['submit'])){
$userNum = (int) $_POST['userNum'];
$hitMine = false;
for($i = 1; $i <= 5; $i++){
$randNum = rand(1, 100);
echo $randNum . '<br />';
if($randNum == $userNum){
$hitMine = true;
}
}
if($hitMine == true){
echo "you hit a mine!";
}
}
?>
I would make an array of the spots
$spot1 = rand(1, 100);
$spot2 = rand(1, 100);
$spot3 = rand(1, 100);
$spot4 = rand(1, 100);
$spot5 = rand(1, 100);
// Make an array of the spots.
$spots = array($spot1, $spot2, $spot3, $spot4, $spot5);
if(in_array($userNum, $spots)) {
echo "you hit a mine!";
exit();
} else {
echo "you lived!";
}
For 50 or more spots you can dynamicaly insert the values in the array assuming you use the rand() function in the real php-code:
$spots = Array();
for ($i = 0; $i < 50; $i ++) {
array_push($spots, rand(1,100));
}
or:
for ($i = 0; $i < 50; $i ++) {
$spots[$i] = rand(1,100);
}
You can use Switch Case in place of if else to make it better and quick.
if(isset($_POST['submit']))
{
$userNum = $_POST['userNum'];
$spot1 = rand(1, 100);
$spot2 = rand(1, 100);
$spot3 = rand(1, 100);
$spot4 = rand(1, 100);
$spot5 = rand(1, 100);
echo $spot1 ."<br>" .$spot2 ."<br>" .$spot3 ."<br>" .$spot4 ."<br>" .$spot5;
Switch($userNum)
{
Case $spot1:
Case $spot2:
Case $spot3:
Case $spot4:
Case $spot5:
echo "you hit a mine!";
break;
default: echo "you lived!";
break;
}
}
Just store the valid spots in an array.
$myhashmap = array();
$myhashmap['spot1'] = true;
$myhashmap['spot2'] = true;
if(isset($myhashmap[$userNum] ) )
{
echo "you hit a mine!";
exit();
}
Here's a link for more info about PHP arrays: http://www.tutorialspoint.com/php/php_arrays.htm
Related
I've tried with AliasNbPage() to get total pages of pdf. i do called '{nb}' to get total pages and it doesn't give output numbers instead of {nb}. there's another way to get total of pages ?
$tot = strval(explode('/', strval($this->pdf->PageNo().'/{nb}'))[1]);
$this->pdf->SetX(44);
$this->pdf->Cell(40,5,": ".$tot.' Pages',0,1);
//while i'm tried to convert the number to the text, it doesn't show.
$this->pdf->Cell(40,5,": ".numb_to_text(intval($tot)).' Pages',0,1);
function init_number($nilai) {
$nilai = abs($nilai);
$huruf = array("", "satu", "dua", "tiga", "empat", "lima", "enam", "tujuh", "delapan", "sembilan", "sepuluh", "sebelas");
$temp = "";
if ($nilai < 12) {
$temp = " ". $huruf[$nilai];
} else if ($nilai <20) {
$temp = $this->init_number($nilai - 10). " belas";
} else if ($nilai < 100) {
$temp = $this->init_number($nilai/10)." puluh". $this->init_number($nilai % 10);
} else if ($nilai < 200) {
$temp = " seratus" . $this->init_number($nilai - 100);
} else if ($nilai < 1000) {
$temp = $this->init_number($nilai/100) . " ratus" . $this->init_number($nilai % 100);
} else if ($nilai < 2000) {
$temp = " seribu" . $this->init_number($nilai - 1000);
} else if ($nilai < 1000000) {
$temp = $this->init_number($nilai/1000) . " ribu" . $this->init_number($nilai % 1000);
} else if ($nilai < 1000000000) {
$temp = $this->init_number($nilai/1000000) . " juta" . $this->init_number($nilai % 1000000);
} else if ($nilai < 1000000000000) {
$temp = $this->init_number($nilai/1000000000) . " milyar" . $this->init_number(fmod($nilai,1000000000));
} else if ($nilai < 1000000000000000) {
$temp = $this->init_number($nilai/1000000000000) . " trilyun" . $this->init_number(fmod($nilai,1000000000000));
}
return $temp;
}
function numb_to_text($nilai) {
$nilai = (int) $nilai;
if($nilai<0) {
$hasil = "minus ". trim($this->init_number($nilai));
} else {
$hasil = trim($this->init_number($nilai));
}
return $hasil;
}
Add $pdf->AliasNbPages(); After $pdf->AddPage();
The total number of pages can only be known just before the document is finished. For example:
$pdf = new FPDF();
$pdf->AddPage();
$pdf->AddPage();
$nb = $pdf->PageNo();
$pdf->Output();
$nb contains 2.
// Get the file into path
$path = 'LargePDF.pdf';
// Call a the function FunctionCountPages
$totalPageCount= FunctionCountPages($path);;
echo $totalPages;
function FunctionCountPages($path)
{
$pdftextfile = file_get_contents($path);
$pagenumber = preg_match_all("/\/Page\W/", $pdftextfile, $dummy);
return $pagenumber;
}
//I hope this work for you
Well, I have created a simple higher/lower game script. Its working fine, but I want to limit the user actions to 3. This means that the user will have to guess the number with 3 moves. On third action I will execute query and save the user to mysql. How I can limit the actions/moves?
<?php
session_start();
function Start_Again() {
$number = rand(1,100);
$_SESSION['higherlower'] = $number;
echo "Select a Number below.";
Display_Form();
}
function Display_Form() {
echo "<table>";
for ($num=1;$num < 101;$num++) {
if (!preg_match("/(.*?)0/", $num)) { echo "<td><a href=\"?number=".$num."\">".$num."</td>"; }
else { echo "<td><a href=\"?number=".$num."\">".$num."</td></tr><tr>"; }
}
echo "</table>";
}
if (isset($_GET['number'])) {
$User_Number = $_GET['number'];
$Actual_Number = $_SESSION['higherlower'];
$count = 0;
if ($User_Number < $Actual_Number) { echo "Higher"; $count + 1; Display_Form(); }
elseif ($User_Number > $Actual_Number) { echo "Lower"; $count + 1; Display_Form(); }
elseif ($User_Number == $Actual_Number) { echo "Bingo, Correct Guess!<br>"; Start_Again(); }
echo $count;
}elseif (!isset($_POST['higherlower'])) { Start_Again(); }
?>
When you initialize the game, simply store the amount of tries in your session.
$_SESSION['tries'] = 3;
Then, when the user picks a number, lower the tries and check if it's 0.
$_SESSION['tries']--;
if ($_SESSION['tries'] <= 0) {
die("Enough! You've been clicking numbers all afternoon.");
}
Full Implementation
<?php
/**
* Higher-lower game
*/
if (!isset($_SESSION)) {
session_start();
}
function Start_Again() {
$number = rand(1,100);
$_SESSION['higherlower'] = $number;
$_SESSION['tries'] = 3;
echo "Select a Number below.";
Display_Form();
}
function Display_Form() {
echo "<table>";
$chunks = array_chunc(range(1, 100), 10);
foreach ($chunks as $chunk) {
echo "<tr>";
foreach ($chunk as $num) {
echo "<td><a href=\"?number=".$num."\">".$num."</td>";
}
echo "</tr>";
}
echo "</table>";
}
if (isset($_GET['number'])) {
$User_Number = $_GET['number'];
$Actual_Number = $_SESSION['higherlower'];
if ($_SESSION['tries'] <= 0) {
die("Oops! You're bad at this!");
}
if ($User_Number < $Actual_Number) { echo "Higher"; $count + 1; Display_Form(); }
elseif ($User_Number > $Actual_Number) { echo "Lower"; $count + 1; Display_Form(); }
elseif ($User_Number == $Actual_Number) { echo "Bingo, Correct Guess!<br>"; Start_Again(); }
$_SESSION['tries']--;
echo $_SESSION['tries'] . 'chances left';
} elseif (!isset($_POST['higherlower'])) {
Start_Again();
}
You are already starting a session so you can store the value in a session variable i.e. $_SESSION['count'];
session_start();
if( !isset( $_SESSION['count] ) ) $_SESSION['count'] = 1;
Later on in the code you will need to update the counter $_SESSION['count']++;
And check whether the person has used up all the guesses
if( $_SESSION['count'] > 3 ) { ..... }
I have this little tid-bit of my code, which is eventually sent to a MySQL database. The rest of the code is sound, but this code likes to give me empty data some of the time. Is there any way to prevent this from happening?
Edit: Here's the whole chunk
//random Species
$sp_one = mt_rand(1,10);
$one_species = "Water Leaper";
//random Genetics
if($one_species == "Water Leaper")
{
$one_gene = mt_rand(1,5);
if($one_gene < 3)
{
$one_genetics = "1";
}
else if($one_gene < 5)
{
$one_genetics = "2";
}
else
{
$one_genetics = "3";
}
}
//random Gender
$one_sex_num = mt_rand(1,2);
if($one_sex_num == 1)
{
$one_gender = "Female";
}
if($one_sex_num == 2)
{
$one_gender = "Male";
}
//Entering it
$sql="INSERT INTO creatures (species, sex, location, genetics)
VALUES('{$one_species}','{$one_gender}', 's1','{$one_genetics}')";
mysqli_query($con,$sql);
First, your if clauses seem a bit redundant. More concise code:
if ($one_gene <3) { $one_genetics = "1"; }
elseif ($one_gene <5) { $one_genetics = "2"; }
else { $one_genetics = "3"; }
This should always return a value - if everything else fails, "3".
Maybe better even:
$one_genetics = ($one_gene + 1) / 2; // integer division
I don't know what you are doing exacly but maby you can take a look at this:
<?php
$animals = array();
$animals[] = array('dog', 78, array('Komondor','Old English Sheepdog'));
$animals[] = array('Drosophila', 8, array('Vestigal','Ebony'));
$number_animals = count($animals) - 1;
$list_size = 30;
for($q = 1; $q <= $list_size; $q++){
$rand = rand(0, $number_animals);
$animal = $animals[$rand];
$number_species = count($animal[2]) - 1;
$rand = rand(0, $number_species);
$randsex = rand(0, 1);
$species = $animal[2][$rand];
$sex = ($randsex ? 'male' : 'female');
$genes = $animal[1];
echo "$q: $species - $sex - $genes <br>";
}
?>
See a live demo at: here
It pics random animals with specs if you want you can modify to your own wishes.
The way I have made the following code is so that it gets the four newest images and HTML documents in a specific folder, and then displays them in order of date posted. Even though it gets the image sorting correct, the overlay system I'm using isn't working correctly.
NEW EDIT for this paragraph: I have fixed most problems except for one. For some reason now, the overlays have decided two trade images, so image 1 displays image 2's overlay, whilst image 2 displays image one's overlay.
If somebody can help, it would be greatly appreciated. I can give an example of the problem at the website I use the code on. The website, click on the thumbnails in the blue box-ish area.
<?php
$i = 1;
$maxiterations = 4;
foreach (glob("news_archive/*.png") as $path)
{
if($i < $maxiterations)
{
$docs[filemtime($path)] = $path;
}
else
{
break;
}
}
asort($docs);
$i2 = 1;
$maxiterations2 = 4;
foreach (glob("news_archive/*.html") as $path2)
{
if($i2 < $maxiterations2)
{
$docs2[filemtime($path2)] = $path2;
}
else
{
break;
}
}
asort($docs2);
$var1;
$var2;
$var3;
$var4;
foreach($docs2 as $timestamp2 => $path2)
{
if($i2 <= $maxiterations2)
{
if($i2 == 1)
{
$var1 = $path2;
}
elseif($i2 == 2)
{
$var2 = $path2;
}
elseif($i2 == 3)
{
$var3 = $path2;
}
elseif($i2 == 4)
{
$var4 = $path2;
}
$i2 = $i2 + 1;
}
else
{
break;
}
}
$varcount = 1;
$varcountmax = 4;
foreach($docs as $timestamp => $path)
{
if($varcount <= $varcountmax)
{
if($varcount == 1)
{
$prersub=substr($var1, 13, 16);
$output="<img class='scroll' src='$path' rel='#$prersub' />";
echo($output);
}
if($varcount == 2)
{
$prersub=substr($var2, 13, 16);
$output="<img class='scroll' src='$path' rel='#$prersub' />";
echo($output);
}
if($varcount == 3)
{
$prersub=substr($var3, 13, 16);
$output="<img class='scroll' src='$path' rel='#$prersub' />";
echo($output);
}
if($varcount == 4)
{
$prersub=substr($var4, 13, 16);
$output="<img class='scroll' src='$path' rel='#$prersub' />";
echo($output);
}
$varcount = $varcount + 1;
}
}
?>
Edit: I still have not solved the issue and differences in parts, when corrected, break other parts of the site completely.
Basically this is related to a squash application where we have 2 scores. One is from winner point of view and another from loser point of view.
eg.
Score1: 11-5,11-5,11-5 (Winner point of view)
Score2: 5-11, 5-11,5-11 (Loser point of view)
Now in my logic i want to find which is the winner score and which is the loser score.
I have written my logic in the below way and it does work. But i want to know if their is any other better/optimized way of writing this.
$high1 = 0;
$high2 = 0;
$score1 = "2-11,5-11,4-11,4-4";
$score2 = "11-2,11-5,11-4,4-4";
$score1Array = explode(",",$score1);
$size = sizeof($score1Array);
for($i = 0; $i < $size; $i++) {
$checkscore1 = explode("-",$score1Array[$i]);
if($checkscore1[0] < $checkscore1[1]) {
$high1++;
}else if($checkscore1[0] > $checkscore1[1]) {
$high2++;
}
}
if($high1 > $high2) {
$winningScore = $score2;
$losingScore = $score1;
}else{
$winningScore = $score1;
$losingScore = $score2;
}
echo $winningscore;
echo $losingscore;
What about something like this:
function is_winning($score) {
$split_scores = preg_split('/(-|,)/', $score);
$wins = $losses = 0;
for($i = 0; $i < count($split_scores) / 2; $i += 2) {
if($split_scores[$i] > $split_scores[$i + 1])
$wins++;
if($split_scores[$i] < $split_scores[$i + 1])
$losses++;
}
return $wins > $losses;
}
Assuming $score is formatted as in your question. You can then use it like this:
$score1 = "2-11,5-11,4-11,4-4";
$score2 = "11-2,11-5,11-4,4-4";
if(is_winning($score1)) {
$winning_score = $score1;
$losing_score = $score2;
} else {
$winning_score = $score2;
$losing_score = $score1;
}
echo $winning_score;
echo $losing_score;
The idea is to split the score into an array where the even numbered indexes have the left score and the odd numbered indexes the right score. We then count the number of wins and the number of losses. If there's more wins then losses then we return true since the score was a winning score. If there's not more wins then losses we simply return false.
This should work
$score1 = "2-11,5-11,4-11,4-4";
$score2 = "11-2,11-5,11-4,4-4";
$l = $r = 0;
$score1_sets_arr = explode(',', $score1);
foreach ($score1_sets_arr as $set_score) {
$set_score_arr = explode('-', $set_score);
if ($set_score_arr[0] > $set_score_arr[1]) {
$l++;
} else {
$r++;
}
}
if ($l > $r) {
$winning_score = $score1;
$losing_score = $score2;
} else {
$winning_score = $score2;
$losing_score = $score1;
}
you can use this :
<?php
$high1 = 0;
$high2 = 0;
$score1 = "2-11,5-11,4-11,4-4";
$score2 = "11-2,11-5,11-4,4-4";
$explode = explode(",",$score1);
for($i=0;$i< sizeof($explode);$i++){
$explode2= explode("-", $explode[$i]);
if($explode2[0] <= $explode2[1]){
echo $explode2[0]."-";
echo $explode2[1]." ";
}
}
echo "<br />";
for($i=0;$i< sizeof($explode);$i++){
$explode2= explode("-", $explode[$i]);
if($explode2[1] >= $explode2[0]){
echo $explode2[1]."-";
echo $explode2[0]." ";
}
}
?>
for Winner point of view, all big score in left,otherwise in right. so u can just detect the first score.
$score1Array = explode(",",$score1);
$checkscore1 = explode("-",$score1Array[$i]);
if($checkscore1[0] < $checkscore1[1]) {
echo $score2;
echo $score1;
}else{
echo $score1;
echo $score2;
}
Fix: above code is wrong,try this:
$score1value = eval(str_replace(",","+",$score1));
$score2value = eval(str_replace(",","+",$score2));
if($score1value < $score2value) {
echo $score2;
echo $score1;
}else{
echo $score1;
echo $score2;
}