Building Browsergames: Integrating weapons into our combat system (PHP)

For all that we’ve built both a combat system and a weapons system, we haven’t yet done anything that allows the weapon a user has selected as their primary weapon to affect the combat system. Today, we will be integrating weapons into our combat system, so that the stats of the weapon actually affect the combat results.

This is actually a lot easier than it sounds – all we have to do is retrieve the weapon’s ‘attack’ stat, use it to modify the damage that the player does, and we’re finished! We’ll open up forest.php, to the piece of code that retrieves our player’s attack:

$player = array (
	name		=>	$_SESSION['username'],
	attack 		=>	getStat('atk',$userID),
	defence		=>	getStat('def',$userID),
	curhp		=>	getStat('curhp',$userID)

Unfortunately, we don’t yet have a weapon stats retrieval system – but thanks to our DRY changes from earlier, that’s an easy piece of code to add:

require_once 'stats-dry.php';
function getWeaponStat($statName,$weaponID) {
	return getStatDRY('Weapon',$statName,$weaponID);

Because we won’t be allowing users to modify the stats of weapons in the game, we only need to add the getWeaponStat function. Save that file as weapon-stats.php, and go back to forest.php. First off, we’ll require our weapon stats code:

require_once 'weapon-stats.php';

Because we’re using a simple combat formula, we can directly modify the player’s attack attribute in the associative array that we are using to store their stats. Here’s how we would retrieve their primary weapon, and then add it’s attack to the player’s:

$phand = getStat('phand',$userID);
$atk = getWeaponStat('atk',$phand);
$player['attack'] += $atk;

And with that small piece of code added, we’re finished! If the weapon has an attack value(even if it’s negative), it will be added to the player’s when they attack the monster.

Extra Credit

  • Make the combat system display the name of the weapon when the player attacks – e.g. “You attack <monster> with your <weapon> for 10 damage!”.

There was a small bug with the stats retrieval code found in this version of the tutorial – it has been fixed in the latest revision of the Google Code Repository. Make sure to update if you’ve been using it!

Wish there was more?

I'm considering writing an ebook - click here.


Luke is the primary editor of Building Browsergames, and has written a large portion of the articles that you read here. He generally has no idea what to say when asked to write about himself in the third person.

Friday, September 12th, 2008 buildingbrowsergames, code, php
blog comments powered by Disqus


Building Browsergames is a blog about browsergames(also known as PBBG's). It's geared towards the beginner to intermediate developer who has an interest in building their own browsergame.


Got Something to Say?

Send an e-mail to, or get in touch through Twitter at