Foreach statement to grab a different part of different HTML documents - php

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.

Related

Assistance required with basic Rock, Paper, Scissors game

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 ( ...

Foreach code working - but asking for optimalization

The below code works and does output exactly what i want. I made a foreach loop getting the values of a specific field ($CustomFields...) which is part of a framework variable. Then is only counts that field when the condition is "group".
After that i want to het the average price of all fields / count.
// ########### Get average hourly rate for group classes
$itemsperhour = array();
$countperhour = 0;
foreach($listings as $listing) {
if ($CustomFields->fieldValue('jr_typeoflesson',$listing,false,false) == 'group') {
$itemsperhour[] = $CustomFields->field('jr_hourlyrateus',$listing,false,false);
$countperhour = $countperhour + 1;
}
}
//print_r($items);
if ($countperhour > 0) {
$totalperhour = array_sum($itemsperhour);
$averageperhour =($totalperhour / $countperhour);
echo round($averageperhour,2);
} else {
echo "No data";
}
unset ($averageperhour);
As said, the snippet works. But may I ask how other people would write such a script related to optimise such a piece of code (for speed and readability?
PHP 5.6+
Jasper
Below is one way of optimizing:
$totalperhour = 0;
$countperhour = 0;
foreach($listings as $listing) {
if ($CustomFields->fieldValue('jr_typeoflesson',$listing,false,false) == 'group') {
$totalperhour += $CustomFields->field('jr_hourlyrateus',$listing,false,false);
$countperhour = $countperhour + 1;
}
}
if($countperhour > 0) {
$averageperhour =($totalperhour / $countperhour);
echo round($averageperhour,2);
$averageperhour = '';
} else {
echo "No data";
}
I would suppose to use array_reduce function for getting the average:
$averageperhour = array_reduce($listings, function($average, $listing) use (&$CustomFields)
{
static $sum = 0;
static $counter = 0;
if ($CustomFields->fieldValue('jr_typeoflesson', $listing, false, false) == 'group') {
$sum += $CustomFields->field('jr_hourlyrateus', $listing, false, false);
$counter ++;
$average = round(($sum / $counter), 2);
}
return $average;
}, 'No data');
echo $averageperhour;
Not sure about speed improvement (needs testing), but this variant seems to me like more readable.
How about this?
$itemsPerHour = [];
foreach($listings as $listing) {
if ($CustomFields->fieldValue('jr_typeoflesson', $listing, false, false) !== 'group') {
continue;
}
$itemsPerHour[] = $CustomFields->field('jr_hourlyrateus', $listing, false, false);
}
$countPerHour = count($itemsPerHour);
if ($countPerHour > 0) {
$averagePerHour = array_sum($itemsPerHour) / $countPerHour;
echo round($averagePerHour,2);
} else {
echo "No data";
}

Why doesn't subtraction sign work on while loop in php?

<?php
$hp = 0;
while($hp < 50) {
$flip = rand(0,2);
if ($flip == 1) {
echo "<p>X-Ray</p>";
$hp += 15;
} elseif ($flip == 2) {
echo "<p>Special Move</p>";
$hp += 10;
} else {
echo "<p>Punch</p>";
$hp += 5;
}
echo "<p>Total so far: $hp</p>";
echo "</br>";
}
?>
This is a PHP code. When I run it, it works fine. However, when I change it to this code below it doesn't.
<?php
$hp = 50;
while($hp > 1) {
$flip = rand(0,2);
if ($flip == 1) {
echo "<p>X-Ray</p>";
$hp -= 15;
} elseif ($flip == 2) {
echo "<p>Special Move</p>";
$hp -= 10;
} else {
echo "<p>Punch</p>";
$hp -= 5;
}
echo "<p>Total so far: $hp</p>";
echo "</br>";
}
?>
Please help. tHE CHANGES I MADE ARE THE HIGHLIGHTED ONES.
You never created $hp properly in the second version:
50;
doesn't do anything. It just tells php "here, have a 50", and php goes "gee, thanks, ok, whatever" and moves onwards. Then you have
while($hp > 1) {
Since $hp is undefined, it's null, and the code parses/executes as:
while($hp > 1) {
while(null > 1) {
while(0 > 1) {
FALSE -> exit loop
You never created $hp properly in the second version:
50;
If you do change it to $hp = 50;

PHP problems with a block of functions sending and working var one to the other one

This is the problem I'm having with code:
I have a function that creates an updating bar;
I have a function that creates a loop, each number of loop makes some other stuffs and the same number represent the progress of the bar (from 1 to 155);
this loop works when user make a "search" on the site for "all" countries;
BUT user can also make a "search" only choosing 1-5 different countries;
this way we have a function that makes the PROGRESS BAR, another one that makes the PROGRESS PART of the BAR that should understand how to progress.
So the point is that I don't know how make the function for progress bar to interpret the situation in order to know that user choosed only some countries and not "all" countries (the option will post to the function some "numbers of the loop" like "3", "4", "56"... corresponding to choosed country) - and this is the easy part (with maybe isset($var)).
The next hard part is that after that it will be called the PROGRESS BAR function with those "country-numbers" so that if you choose "Canada-USA-France" the numbers will be "34-12-45" and the progress bar will write "34%-12%-45%".
But it's incorrect because if you have 3 options choosed, it should be 33%-66%-99% (and not 34%-12%-45%)...
What I don't know is how to make that function understand that everytime the function receive the "country-number", and it comes from user choice different from "all", the function should get that number and modify it (and this can be made with an array) in order to adapt it to the correct bar progression so that if you have: 34, than 12 than 45, the function should understand that the 1st time 34 should become 33, the 2nd time 12 should become 66 and the 3rd time 45 should become 99 (or 100)...
Here is the code part of interest:
1. receiving _POST and verifying it:
function getData() {
$a = strtolower($_POST["CountryOne"]);
$b = strtolower($_POST["CountryTwo"]);
$c = strtolower($_POST["CountryThree"]);
$d = strtolower($_POST["CountryFour"]);
$d = strtolower($_POST["CountryFive"]);
$numPost = count($_POST);
if ($numPost == 0) {
echo("<p class='Verify'>Select an option to start search...<br></p>");
} else {
echo "<div class='Verify' id='progressbar' style='width:620px;height:16px'></div>
<div class='VerifyBar' id='information' style='width'></div>";
};
2. Jump to next part after checking it user choosed "all" or "some countries" - here is the loop:
function loopNum($x) {
$i = 0+$x;
$y = $x+3;
for ($x = $i; $x <= $y; $x++) {
$iscountryID = ("$country".$x."");
createUrl($iscountryID);
} if($y != 155) {
return loopNum($x);
} else if($y < 155) {
echo("<font size='2' face='Tahoma, Geneva, sans-serif' style='font-variant: small-caps' color='#FF0000'><i>ERROR: unxepected data extraction interruption</font></i><br>");
} else {
echo("<font size='2' face='Tahoma, Geneva, sans-serif' style='font-variant: small-caps' color='#00CC00'><i>FINISHED: data extraction ended</font></i><br>");
}};
3. than it makes a lot of other stuff and call progress bar function
function completeBar($iscountryID) {
//***** PART UNDER CONSTRUCTION WHERE I NEED HELP *****
$countryOne = strtolower($_POST["CountryOne"]);
$countryTwo = strtolower($_POST["CountryTwo"]);
$countryThree = strtolower($_POST["CountryThree"]);
$countryFour = strtolower($_POST["CountryFour"]);
$countryFive = strtolower($_POST["CountryFive"]);
if (($countryOne !== 'all') and ($countryTwo !== 'all') and ($countryThree !== 'all') and ($countryFour !== 'all') and ($countryFive !== 'all')) {
$numQuery = array("$countryOne","$countryTwo","$countryThree","$countryFour","$countryFive");
foreach ($numQuery as $value) {
if(is_numeric($value)) {
$j++;
}}; // AT THIS POINT I WOULD KNOW HOW MANY VALUES IN THE ARREY ARE DIFFERENT FROM "ALL" AND "NO_COUNTRY" OPTIONS AND SO ARE NUMERIC VALUES
//***** FROM HERE I DUNNO HOW TO PRECEED *****
} else { //the next part works with "all" option choosed
if ($iscountryID < 155) {
$i = $iscountryID;
$percent = $i."%";
$pxbar = 4*$i."px";
$percentage = round((($pxbar*100)/624),0); //bar is 624px long
// Javascript for updating the progress bar and information
echo '<script language="javascript">
document.getElementById("progressbar").innerHTML="<div style=\"width:'.$pxbar.';background-color:#ddd;\">'.$percentage.'% </div>";
document.getElementById("information").innerHTML="'.$i.'/155 country(s) processed... loading your data, hold on..."</script>';
// This is for the buffer achieve the minimum size in order to flush data
echo str_repeat(' ',1024*64);
// Send output to browser immediately
flush();
sleep(1);
} else if ($iscountryID == 155) { //so on loop complete
$i = $iscountryID;
$percent = $i."%";
$pxbar = 4*$i."px";
$percentage = round((($pxbar*100)/624),0);
echo '<script language="javascript">
document.getElementById("progressbar").innerHTML="<div style=\"width:'.$pxbar.';background-color:#ddd;\">'.$percentage.'% </div>";
document.getElementById("information").innerHTML="'.$i.'/155 country(s) processed... loading your data, hold on..."</script>';
echo str_repeat(' ',1024*64);
flush();
sleep(1);
// Tell user that the process is completed
echo '<script language="javascript">
document.getElementById("progressbar").innerHTML="<div style=\"width:'.$pxbar.';background-color:#ddd;\">100% </div>";
document.getElementById("information").innerHTML="<div>Process completed, all countries verified...</div>";
document.getElementById("information").style.color="green";
</script>';
echo str_repeat(' ',1024*64);
flush();
sleep(1);
}
}};
Ah... I've tried to make the following working but the problem is that with the following, I'll have the function updating the bar getting values from the array too fast. Using the VAR sent from the rest of the file, I'll have an updating bar that follows the updating output of the server.
function partialBar() {
$countryOne = strtolower($_POST["CountryOne"]);
$countryTwo = strtolower($_POST["CountryTwo"]);
$countryThree = strtolower($_POST["CountryThree"]);
$countryFour = strtolower($_POST["CountryFour"]);
$countryFive = strtolower($_POST["CountryFive"]);
$numQuery = array("$countryOne","$countryTwo","$countryThree","$countryFour","$countryFive");
foreach ($numQuery as $value) {
if(is_numeric($value)) {
$j++;
};
};
if ($j == 1) {
$iscountryID = 155;
completeBar($iscountryID);
} else if ($j == 2) {
$iscountryID = array("78","155");
completeBar($iscountryID[0]);
completeBar($iscountryID[1]);
} else if ($j == 3) {
$iscountryID = array("52","104","155");
completeBar($iscountryID[0]);
completeBar($iscountryID[1]);
completeBar($iscountryID[2]);
} else if ($j == 4) {
$iscountryID = array("39","78","117","155");
completeBar($iscountryID[0]);
completeBar($iscountryID[1]);
completeBar($iscountryID[2]);
completeBar($iscountryID[3]);
} else if ($j == 5) {
$iscountryID = array("31","62","93","124","155"); //these numbers are the corresponding loop number in other to get 20%-40%-60%-80%-100% from the completeBar() function
completeBar($iscountryID[0]);
completeBar($iscountryID[1]);
completeBar($iscountryID[2]);
completeBar($iscountryID[3]);
completeBar($iscountryID[4]);
} else echo ("<div class='Verify'>Something went wrong!</div>");
};
Here is solution:
make a counter in the central function in order to know how many times have been called, so you know which number of the array you have to call for the correct calculation of the % of progress bar.
Here is where the following functions are called:
if (($countryNameTitOne == 'all') or ($countryNameTitTwo == 'all')
or ($countryNameTitThree == 'all') or ($countryNameTitFour == 'all')
or ($countryNameTitFive == 'all')) {
completeBar($iscountryID);
} else {
$callCounter = callCounterFunc();
partialbar($iscountryID,$callCounter);
}};
Than here are the functions called:
function completeBar($iscountryID) {
if ($iscountryID < 155) {
$i = $iscountryID;
$percent = $i."%";
$pxbar = 4*$i."px";
$percentage = round((($pxbar*100)/624),0);
echo '<script language="javascript">
document.getElementById("progressbar").innerHTML="<div style=\"width:'.$pxbar.';background-color:#ddd;\">'.$percentage.'% </div>";
document.getElementById("information").innerHTML="'.$i.'/155 country(s) processed... loading your data, hold on..."</script>';
echo str_repeat(' ',1024*64);
flush();
sleep(1);
} else if ($iscountryID == 155) {
$i = $iscountryID;
$percent = $i."%";
$pxbar = 4*$i."px";
$percentage = round((($pxbar*100)/624),0);
echo '<script language="javascript">
document.getElementById("progressbar").innerHTML="<div style=\"width:'.$pxbar.';background-color:#ddd;\">'.$percentage.'% </div>";
document.getElementById("information").innerHTML="'.$i.'/155 country(s) processed... loading your data, hold on..."</script>';
echo str_repeat(' ',1024*64);
flush();
sleep(1);
echo '<script language="javascript">
document.getElementById("progressbar").innerHTML="<div style=\"width:'.$pxbar.';background-color:#ddd;\">100% </div>";
document.getElementById("information").innerHTML="<div>Process completed, all countries verified...</div>";
document.getElementById("information").style.color="green";
</script>';
echo str_repeat(' ',1024*64);
flush();
sleep(1);
}
};
function partialBar($iscountryID,$callCounter) {
$countryOne = strtolower($_POST["CountryOne"]);
$countryTwo = strtolower($_POST["CountryTwo"]);
$countryThree = strtolower($_POST["CountryThree"]);
$countryFour = strtolower($_POST["CountryFour"]);
$countryFive = strtolower($_POST["CountryFive"]);
$numQuery = array("$countryOne","$countryTwo","$countryThree","$countryFour","$countryFive");
foreach ($numQuery as $value) {
if(is_numeric($value)) {
$j++;
}};
if ($j == 1) {
if ($callCounter == 1) {
$iscountryID = 155;
completeBar($iscountryID);
};
} else if ($j == 2) {
$iscountryID = array("78","155");
if ($callCounter == 1) {
completeBar($iscountryID[0]);
} else if ($callCounter == 2) {
completeBar($iscountryID[1]);
};
} else if ($j == 3) {
$iscountryID = array("52","104","155");
if ($callCounter == 1) {
completeBar($iscountryID[0]);
} else if ($callCounter == 2) {
completeBar($iscountryID[1]);
} else if ($callCounter == 3) {
completeBar($iscountryID[2]);
};
} else if ($j == 4) {
$iscountryID = array("39","78","117","155");
if ($callCounter == 1) {
completeBar($iscountryID[0]);
} else if ($callCounter == 2) {
completeBar($iscountryID[1]);
} else if ($callCounter == 3) {
completeBar($iscountryID[2]);
} else if ($callCounter == 4) {
completeBar($iscountryID[3]);
};
} else if ($j == 5) {
$iscountryID = array("31","62","93","124","155");
if ($callCounter == 1) {
completeBar($iscountryID[0]);
} else if ($callCounter == 2) {
completeBar($iscountryID[1]);
} else if ($callCounter == 3) {
completeBar($iscountryID[2]);
} else if ($callCounter == 4) {
completeBar($iscountryID[3]);
} else if ($callCounter == 5) {
completeBar($iscountryID[4]);
};
} else echo ("<div class='Verify'>Something went wrong!</div>");
};
function callCounterFunc() {
static $calls = 0;
++$calls;
return $calls;
};

Recursive function loops infinitely [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am working on a personal project, a bot that plays connect 4. So something is seriously wrong with the recursive function I have written to manage the bots move. No errors are thrown, and any debug info I can be shown does not tell me anything useful. Additionally, I am sure that I have not overflown my stack and that my php.ini file is good to go. This script just runs (consumes a sane amount of memory) and never returns. Only about 2400 function calls should be happening, so this script should return after only a second or two. This has stumped me for days. I believe there is something I have not properly researched. Additonally I should mention that the game board is a simple 2D array to simulate a 7 x 7 board. ai_move_helper is the recursive function and I just cannot figure out why it will not function correctly.
// this class is a code igniter library
class ConnectFour
{
public function __construct()
{
// these are expensive opperations this will give the server enough time
set_time_limit(0);
ini_set('memory_limit', '2048M');
}
public $board_width = 7;
public $board_length = 7;
public $game_array = array();
public $depth_limit = 3;
// this function gets a human made move from a CI controller ($game board)
// and returns the board after the new AI move is applied
public function ai_player_move($game_array, $active_players_move)
{
$this->game_array = $game_array;
$this->game_array = $this->calculate_ai_move($active_players_move);
return $this->game_array;
}
public function calculate_ai_move($active_players_move)
{
$move_weight_array = array();
$prime_game_board = array();
// we hardcast the active player because at this point we know it is the AI
// here we also have to prime the move computer
for($q = 0; $q < $this->board_length; $q++)
{
// MAGIC NUMBERS are the active players!!!
$prime_game_board[] = $this->apply_prime_move($q, 2, $this->game_array);
$move_weight_array[] = $this->ai_move_helper($prime_game_board[$q], 2, 0);
}
//choose your move
for($u = 0; $u < $this->board_length; $u)
{
if($move_weight_array[$u][0] == 1)
{
return $prime_game_board[$u];
}
}
// otherwise return a random acceptable move
$random = rand(0, 6);
return $prime_game_board[$random];
}
public function ai_move_helper($game_board, $active_player, $depth)
{
// build the object that will be needed at this level of recusion
$depth = $depth + 1;
$score_object = new stdClass;
$move_array = array();
$game_boards_generated_at_this_level = array();
$new_game_boards_generated_at_this_level = array();
$return_end_state_detected = 0;
$score_agregate = array();
if($this->depth_limit < $depth)
{
$score_agregate[0] = 0;
$score_agregate[1] = 0;
return $score_agregate;
}
$active_player = ($active_player == 1) ? 2 : 1;
// check for possible moves
for($i=0; $i < $this->board_width; $i++)
{
// calculate all of the possible recusions (all of the next moves)
$game_boards_generated_at_this_level[$i] = $this->apply_ai_move($i, $active_player, $game_board);
// this is the recusive level
$score_agregate = $this->ai_move_helper($game_boards_generated_at_this_level[$i]->game_board, $active_player, $depth);
}
// check to see if there are more moves of if it is time to return
foreach($game_boards_generated_at_this_level as $game_state)
{
//compute the agragate of the scores only for player two (AI)
if($active_player == 2)
{
$score_agregate[0] = $score_agregate[0] + $game_state->score_array[0];
$score_agregate[1] = $score_agregate[1] + $game_state->score_array[1];
}
}
return $score_agregate;
}
public function apply_ai_move($move, $active_players_move, $board_to_use)
{
$board_for_function = array();
$location_of_new_pieces = 0;
$return_object = new stdClass;
// this makes sure that this function is being called with the right board
if(!empty($board_to_use))
{
$board_for_function = $board_to_use;
} else {
$board_for_function = $this->game_array;
}
// check that this move is possible
if(!$this->move_possible($move, $board_for_function))
{
$return_object->game_board = NULL;
$return_object->score_array = NULL;
return $return_object;
}
// this part of the function applies a valid move
foreach($board_for_function[$move] as $column_key => $column_space)
{
// check if you are at the edge of an empty row
if(!array_key_exists(($location_of_new_pieces + 1), $board_for_function[$move]) && $column_space == '_')
{
$board_for_function[$move][$location_of_new_pieces] = ($active_players_move == 1) ? 'x' : 'o';
break;
}
// check if the next place has stuff in it too
if($column_space != '_')
{
// check the edge of the board to make sure that exists
if(array_key_exists(($location_of_new_pieces - 1), $board_for_function))
{
$board_for_function[$move][$location_of_new_pieces - 1] = ($active_players_move == 1) ? 'x' : 'o';
break;
} else {
echo "well fuck...1"; exit;
}
}
$location_of_new_pieces++;
}
$return_object->game_board = $board_for_function;
// now check if this state is a win loss or draw
$test_for_complete = $this->check_for_winner_or_draw($board_for_function, $active_players_move);
// this is a draw
if($test_for_complete == -1)
{
$return_object->score_array = array(0, 1);
} else if($test_for_complete > 3) {
$return_object->score_array = array(1, 0);
} else {
$return_object->score_array = array(0, 0);
}
return $return_object;
}
public function apply_prime_move($move, $active_players_move, $board_to_use)
{
$location_of_new_pieces = 0;
foreach($board_to_use[$move] as $column_key => $column_space)
{
// check if you are at the edge of an empty row
if(!array_key_exists(($location_of_new_pieces + 1), $board_to_use[$move]) && $column_space == '_')
{
$board_to_use[$move][$location_of_new_pieces] = ($active_players_move == 1) ? 'x' : 'o';
break;
}
// check if the next place has stuff in it too
if($column_space != '_')
{
// check the edge of the board to make sure that exists
if(array_key_exists(($location_of_new_pieces - 1), $board_to_use))
{
$board_to_use[$move][$location_of_new_pieces - 1] = ($active_players_move == 1) ? 'x' : 'o';
break;
} else {
echo "well fuck...1"; exit;
}
}
$location_of_new_pieces++;
}
return $board_to_use;
}
public function move_possible($move, $game_board)
{
// check that this move is not going to fall out of the board
if($game_board[$move][0] != "_")
{
return FALSE;
} else {
return TRUE;
}
}
public function check_for_winner_or_draw($game_array, $active_player_move)
{
$present_possible_winner = "";
$count_to_win = 0;
$game_not_a_draw = FALSE;
for($i = 0; $i < $this->board_length; $i++)
{
for($j = 0; $j < $this->board_width; $j++)
{
// start checking for a winner
if($game_array[$i][$j] != "_")
{
$present_possible_winner = $game_array[$i][$j];
// check for a winner horizontally
for($x = 0; $x < 4; $x++)
{
if($j+$x < $this->board_width)
{
if($game_array[$i][$j+$x] == $present_possible_winner)
{
$count_to_win = $count_to_win + 1;
}
}
}
if($count_to_win > 3)
{
return $present_possible_winner; // this player has won
} else {
$count_to_win = 0;
}
// check for a winner horizontally
for($y = 0; $y < 4; $y++)
{
if($i+$y < $this->board_width)
{
if($game_array[$i+$y][$j] == $present_possible_winner)
{
$count_to_win = $count_to_win + 1;
}
}
}
if($count_to_win > 3)
{
return $present_possible_winner; // this player has won
} else {
$count_to_win = 0;
}
// check for a winner up to down diagonal
for($z = 0; $z < 4; $z++)
{
if(($i+$z < $this->board_width) && ($j+$z < $this->board_length))
{
if($game_array[$i+$z][$j+$z] == $present_possible_winner)
{
$count_to_win = $count_to_win + 1;
}
}
}
if($count_to_win > 3)
{
return $present_possible_winner; // this player has won
} else {
$count_to_win = 0;
}
// check for a winner down to up diagonal
for($w = 0; $w < 4; $w++)
{
if(($i+$w < $this->board_width) && ($j-$w >= 0))
{
if($game_array[$i+$w][$j-$w] == $present_possible_winner)
{
$count_to_win = $count_to_win + 1;
}
}
}
if($count_to_win > 3)
{
return $present_possible_winner; // this player has won
} else {
$count_to_win = 0;
}
}
}
}
// check for a drawed game and return accordingly
for($i = 0; $i < $this->board_length; $i++)
{
for($j = 0; $j < $this->board_width; $j++)
{
if($game_array[$i][$j] == "_")
{
$game_not_a_draw = TRUE;
}
}
}
if(!$game_not_a_draw)
{
return -1;
}
return 0;
}
// this is a private debugging function that I wrote for this script
public function debug($value = NULL, $name = NULL, $exit = NULL)
{
if(!empty($name))
{
echo $name . "<br />";
}
echo "<pre>";
var_dump($value);
echo "</pre>";
if($exit)
{
exit;
}
}
}
Well I found it: The calculate ai move had an infinite loop in it...
//choose your move
for($u = 0; $u < $this->board_length; $u)
{
if($move_weight_array[$u][0] == 1)
{
return $prime_game_board[$u];
}
}
Should be
//choose your move
for($u = 0; $u < $this->board_length; $u++)
{
if($move_weight_array[$u][0] == 1)
{
return $prime_game_board[$u];
}
}
Back to work for me...

Categories