Jump to content

Recommended Posts

I have a script I am putting together that simulate a cricket game. The only issue is, that there are a huge number of functions because there doesn't seem to be any other way to do this properly. As well as this, there a while() loop and all this seems to be leading to the page reaching a max 30 second timeout when generating the result.

 

My code is attached below, it is quite messy at the moment because i've just be working on it, but I was wondering if anyone has any solutions of how I can speed this up or change to prevent a timeout:

 

<?php
// Error reporting
error_reporting(E_ALL);

// Connect DB
mysql_connect("wickettowicket.adminfuel.com", "rockinaway", "preetha6488") or die(mysql_error());

// Select DB
mysql_select_db("wickettowicket") or die(mysql_error());

// MySQL queries to find batsmen and bowlers 
$array_batsmen = mysql_query('SELECT id, name, ability, strength FROM wtw_players WHERE team_id = 1 ORDER BY id ASC');
$array_bowlers = mysql_query('SELECT id, name, ability, strength FROM wtw_players WHERE team_id = 2');

// Start table for data 
$data = '<table width="600px">';

// Create blank scorecard
while ($array_bat = mysql_fetch_array($array_batsmen))
{
$data .= '<tr><td>'.$array_bat['name'].'</td><td></td><td></td><td>0</td></tr>';
}

// Set up arrays for players 
$current_batsman = $current_bowler = array();

// Reset query
mysql_data_seek($array_batsmen,0);

$in_one = $in_two = $it = '';

function currentBatsman($id, $name, $ability, $strength, $out, $in, $runs)
{
global $current_batsman;


	$current_batsman = array (
										'id'		=>	$id,
										'name'		=>	$name,
										'ability'	=>	$ability,
										'strength'	=>	$strength,
										'out'		=>	$out,
										'in'		=>	$in,
										'runs'		=>	$runs
									);

	echo 'set current';
}

// Set up arrays of batsmen
while ($array = mysql_fetch_array($array_batsmen))
{	

if ($it < 3 && $in_one == '') 
{
	currentBatsman($array['id'], $array['name'], $array['ability'], $array['strength'], 0, 1, 0);

	$batsmen[$array['id']] = array (
			'id'		=>	$array['id'],
			'name'		=>	$array['name'],
			'ability'	=>	$array['ability'],
			'strength'	=>	$array['strength'],
			'out'		=>	0,
			'in'		=>	1,
			'runs'		=>	0
			);

		$in_one = $array['id'];
		$current = $array['id'];
		$it++;
}
else if ($it < 3 && $in_two == '') 
{
	$batsmen[$array['id']] = array (
			'id'		=>	$array['id'],
			'name'		=>	$array['name'],
			'ability'	=>	$array['ability'],
			'strength'	=>	$array['strength'],
			'out'		=>	0,
			'in'		=>	1,
			'runs'		=>	0
			);

		$in_two = $array['id'];
		$it++;
}
else 
{
	$batsmen[$array['id']] = array (
			'id'		=>	$array['id'],
			'name'		=>	$array['name'],
			'ability'	=>	$array['ability'],
			'strength'	=>	$array['strength'],
			'out'		=>	0,
			'in'		=>	0,
			'runs'		=>	0
			);
}

}

// Bowler Array
while ($array = mysql_fetch_array($array_bowlers))
{
$bowlers[] = array (
		'name'		=>	$array['name'],
		'ability'	=>	$array['ability'],
		'strength'	=>	$array['strength']
		);

}

// Reset both queries
mysql_data_seek($array_bowlers,0);
mysql_data_seek($array_batsmen,0);



function changeBatsman($just_out)
{
global $array_batsmen, $batsmen; 

//Update array
$batsmen[$just_out] = array (
			'in'		=>	1,
			'out'		=>  1
			);

while ($array = mysql_fetch_array($array_batsmen))
{	
	if ($just_out != $array['id'] && $batsmen[$array['id']]['out'] != 0) currentBatsman($array['id'], $array['name'], $array['ability'], $array['strength'], 0, 1, 0);
}

// Reset query
mysql_data_seek($array_batsmen,0);

echo 'change batsman';
}

function swapBatsman($other_batsman)
{
global $array_batsmen, $batsman; 

while ($array = mysql_fetch_array($array_batsmen))
{	
	if ($other_batsman != $array['id'] && $batsman[$array['id']]['out'] != 0 && $batsman[$array['id']]['in'] == 1) currentBatsman($array['id'], $array['name'], $array['ability'], $array['strength'], 0, 1, 0);
}

// Reset query
mysql_data_seek($array_batsmen,0);

echo 'swap batsman';
}

$runs = $outs = $balls = $overs = 0;

$played = array();

function selectBowler()
{
global $bowlers, $current_bowler;

// Select random bowler
$choose_bowler = array_rand($bowlers, 1);

$current_bowler = array (
		'name'		=>	$bowlers[$choose_bowler]['name'],
		'ability'	=>	$bowlers[$choose_bowler]['ability'],
		'strength'	=>	$bowlers[$choose_bowler]['strength']
		);



}

/*
function selectBatsman();
{
global $array_batsmen;

while ($array_batsmen[]['out'] != 1)
{


}*/

function bowl()
{
global $batsmen, $bowlers, $current_bowler, $current_batsman, $data, $balls, $outs, $runs;

if ($current_batsman['out'] == 0)
{
	echo 'bowling';
					// Set the initial number
					$number = rand(0, 190);

					// Ability of batsman
					if ($current_batsman['ability'] > 90) $number += 30;
					else if ($current_batsman['ability'] > 70) $number += 15;
					else if ($current_batsman['ability'] > 50) $number += 2;
					else $number = $number;

					// Strength of batsman
					if ($current_batsman['strength'] > 90) $number += 15;
					else if ($current_batsman['strength'] > 70) $number += 10;
					else if ($current_batsman['strength'] > 50) $number += 5;
					else $number = $number;

					// Depending on overs
					if ($balls > 270) $number += 30;
					else if ($balls > 120) $number -= 10;

					// Ability
					if ($current_bowler['ability'] > 90) $number -= 30;
					else if ($current_bowler['ability'] > 70) $number -= 15;
					else if ($current_bowler['ability'] > 50) $number -= 2;
					else $number = $number;

					// If batsman has made a huge total of runs, we need to knock some numbers off - more likely to get out
					if ($current_batsman['runs'] > 200) $number -= 70;
					else if ($current_batsman['runs'] > 100)	$number -= 30;

					// Finally sort out runs
					if ($number > 190) $run = 6;
					else if ($number > 170) $run = 4;
					else if ($number > 160)	$run = 3;					
					else if ($number > 100) $run = 2;
					else if ($number > 50) $run = 1;
					else if ($number > 10) $run = 0;
					else if ($balls > 120 && $number > 0) $run = 0;
					else $run = -1;

					// Increase number of balls
					$balls += 1;

					// Are they out?
					if ($run == -1)
					{
						$current_batsman['out'] = 1;

						$played[] = $current_batsman['id'];
						$find = '<tr><td>'.$current_batsman['name'].'</td><td></td><td></td><td>0</td></tr>';
						$replace = '<tr><td>'.$current_batsman['name'].'</td><td></td><td>'.$current_bowler['name'].'</td><td>'.$current_batsman['runs'].'</td></tr>';

						$data = str_replace($find, $replace, $data);


						changeBatsman($current_batsman['id']); 



						echo 'out';

					}
					else
					{
						$current_batsman['runs'] += $run;		
						$runs += $run;

						if ($run == 1 || $run == 3)
						{
							swapBatsman($current_batsman['id']);
							echo 'time to swap';
						}

						echo $run;


					}

					// Count outs
				if ($current_batsman['out'] == 1)
				$outs += 1;


}
}

function game()
{
global $main, $batsmen, $bowlers, $data, $batted, $balls, $outs, $current_batsman;

// Check if possible
while ($balls <= 295 && $outs < 10)
{

	selectBowler();

	// Actually bowl now

	bowl();


}


}


game();



echo $data;

 

Most of the mysql_data_seek()'s have been removed now. I think I know what the issue is.

 

In the bowl() function, when $run == -1, a batsman is out and so the changeBatsman() function is called. It is somewhere here where the maximum time limit is being exceeded.

 

Is there any way that I can stop that function and then restart it? .. I think it's because there is no way to exit the function at that point once the changeBatsman() function is called.

Just some advice -

 

1) Put all your function definitions either near the start of your code (before you start the main logic that makes up your page) or put them into an include file. When you are looking at the main logic in your file, that's all you should see, the main logic.

 

2) Rewrite your functions to be general purpose, so that they are passed the values they operate on as parameters when they are called and they return the results they produce, which you then assign to main program variables. For example, if your currentBatsman() function was written this way, you could have reused it in 3 - 5 different places in the code and saved a bunch of typing and made your code simpler and clearer. If your functions don't fit this model of - values in as parameters, perform some useful function, return the result produced - then the code you have wrapped in a function definition is likely part of your main program logic and does not belong in a function.

Okay, well at the moment i've just been working in one file to set everything up and then I was planning to split it all into files for the functions and then do includes etc.

 

However, my issue is it won't loop the way I want it to. The code works PERFECTLY for the first loop, but as soon as I call changeBatsman (i.e. a batsman is out and i must start the loop again) nothing happens. There is no place for the function to go. Basically, when changeBatsman() is called, I want to restart the loop with the bowl() function.

 

 

Also, never use global.  At all.  Ever.  Like PFMaBiSmAd says, functions are supposed to be general purpose black boxes, where data is passed in (via the parameter list), the data is processed (function body), and a result is returned (return statement at the end).  Global forces your function to know about the context in which it was invoked, which just kills a function's modularity, and thus makes it a pain to debug and edit (among other things).

I recommend working with the current code. By simply fixing the functions, the logic in any section of your code will become clearer and you can work on making the logic do what you want.

 

For example, I was going through your code and if your currentBatsman() function was changed to the following (renamed as well) -

 

function build_player($id, $name, $ability, $strength, $out, $in, $runs)
{
return array('id'=>$id,'name'=>$name,'ability'=>$ability,'strength'=>$strength,'out'=>$out,'in'=>$in,'runs'=>$runs);
}

 

You can use (reuse) it to set the $current_batsman, the $batsmen[] array, the $bowlers[] array (ignore the id, out, in, and runs elements), and you would also use it inside your other functions to simplify all the logic and remove countless lines of code. For example, your selectBowler() function would look like this -

 

function selectBowler($bowlers)
{
// Select random bowler
$choose_bowler = array_rand($bowlers, 1);
return build_player($bowlers[$choose_bowler]['id'],$bowlers[$choose_bowler]['name'],$bowlers[$choose_bowler]['ability'],$bowlers[$choose_bowler]['strength'],0,0,0); // id, out,in,runs not used
}

 

And you would call it like this -

$current_bowler = selectBowler($bowlers);

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.