Advertisement

PHP can't handle minimax

Started by May 27, 2009 05:22 PM
3 comments, last by DvDmanDT 15 years, 5 months ago
The following PHP code should print out the score of the starting position for the first player. The game is a simple one where players take turns adding 1 or 2 and the player to reach 21 wins. This is a real simple implementation where we start with the initial state and get the initial score for player1. The code is extremely straightforward, a recursive minimax, yet it times out. Is this a problem with PHP's recursion stack size or some memory limit? (in my opinion, the memory used for this case should be quite small)

<?php

$state = 0;
$depth = 0;

echo "The score is: ". score($state, $depth)."<br>";


function score ($s, $d)
{
	$m = 1;
	if (($s==21)&&($d%2)) return 1;
	if (($s==21)&&(!($d%2))) return -1;
	if($d%2)
	{
		for ($i=1; (($i<=2)&&($s+$i<=21)); $i++)
		{
			if(score($x+$i, $d+1)>=score($x+$m, $d+1)) $m = $i;
		}
	}
	else
	{
		for ($i=1; (($i<=2)&&($s+$i<=21)); $i++)
		{
			if(score($x+$i, $d+1)<=score($x+$m, $d+1)) $m = $i;
		}
	}
	return score($s+$m, $d+1);		
}

?>

http://www.sharpnova.com
You are doing a bunch of things wrong. At least:
* Wherever you said `$x', you meant `$s'.
* You should not make the same function call over and over again: Save the value in a local variable and reuse it.
Advertisement
Quote: Original post by AlphaCoder
The code is extremely straightforward, a recursive minimax, yet it times out.

Is this a problem with PHP's recursion stack size or some memory limit? (in my opinion, the memory used for this case should be quite small)

A time out is down to exactly what it says - time. PHP is for serving up web pages and it has limits on how much time it will spend on any single request so that it has a chance to serve other requests in a more timely fashion. So the code is too slow, basically.
You can use set_time_limit to postpone a PHP time-out
You might want to checkout phalanger at http://php-compiler.net. It compiles PHP code to .NET executables (can also be used as ASP.NET language I think). It could very well give you a speed boost.

This topic is closed to new replies.

Advertisement