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

Even though we’ve built a combat system and a weapons system, we haven’t done anything yet to make them work together. Today, we’re going to be modifying our combat system so that it takes into account the ‘attack’ attribute of the user’s current primary weapon.

This is a quick, easy change – all we have to do is retrieve the ‘attack’ stat for the user’s primary weapon, and then add it onto their attack stat for our combat calculations. Here’s the code that retrieves a players stats, from forest.cgi:

my %player = (
	name		=>	$username,
	attack		=>	stats::getStat('atk',$userID),
	defence		=>	stats::getStat('def',$userID),
	curhp		=>	stats::getStat('curhp',$userID)

If you’ve been following along with all of the tutorials so far, you might have noticed a slight problem: we can’t retrieve weapon stats yet. Thanks to our DRY changes from earlier, it’s easy to write that code:

package weaponstats;
use DBI;
use statsDRY;
sub getWeaponStat {
	my ($statName,$userID) = @_;
	return statsDRY::getStatDRY('Weapon',$statName,$userID);

It’s even easier because we aren’t going to be allowing users to change the stats – which means we only need to write the code to retrieve them(and not update them).

With that finished, we’re going to make sure that forest.cgi includes the new code:

use weaponstats;

Because our combat formula is as simple as it is(attackdefence), all we need to do is modify the ‘attack’ value that we stored in the %player hash with the attack for their primary weapon:

my $phand = stats::getStat('phand',$userID);
$player{attack} += weaponstats::getWeaponStat('atk',$phand);

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

Extra Credit

  • Make it so that only positive attack values are added to the player’s attack.

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.

Monday, September 15th, 2008 buildingbrowsergames, code, perl
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