Saturday, December 22, 2007

PHP Game Dev Forum

Still lack of time to produce some great tutorial. Also out of ideas what to write in next tutorial.

Thats why I created forum where PHP game devs can chat and help each other.
Here it is:

PHP Game Dev Forum

Thursday, November 1, 2007

Galactic Lords

Hello to all readers!

Maybe you have been wondering why I did not post for so long. Well here is the answer. I worked on my own web-based game and now it is available to play.


Galactic Lords

Choose one of seven races, each with different bonus. Build your defenses, train soldiers, invade human players, trade with others, gather your friends and found best Alliance ever.
You think you can handle it?
You think you can be the next Galactic Lord?

Galactic Lords

Friday, October 12, 2007

Basic Strategy game - simple attack script

Hello again. First of all, I like to say sorry to all readers of this blog (if any :) ). I was quite busy for last 2 weeks, but hey at least you all have time to really get into last tutorials and understand things!
So lets start. In this tutorial I will try to explain how to create simple attack script.

As always theory first:

  • user browses user list and attack user he wants to
  • soldier will have basic strength of 100
  • equipping weapon1 would double output of soldier, so 200
  • weapon2 is 400 and with weapon3 is 800
  • number of casualties on each side will depend on amount of damage dealt
Now we need some file where we will browse users, choose who to attack and see battle report. Lets create file like battle.php (don't forget to include config.php in beginning of file).
<?
//this file will be all in php
//if user did not select who to attack, we show him list of users
if (!$_GET[attack]) {
//we select id and username of everyone except us
$battleQ = mysql_query("SELECT id,username FROM users WHERE id<>'$user[id]'");
while ($battle = mysql_fetch_array($battleQ)) {
//we show all selected users as well as link to their "attack" subpage
echo "$battle[username] => <a href=\"battle.php?attack=".$battle[id]."\">attack</a> <br>";
}
}

//if user selected link to attack player
if ($_GET[attack]) {
$attack_id = $_GET[attack];
//we check if ID submited is numerical
if (!is_numeric($attack_id)) { die("Bad target ID!"); }
//we select user with that ID
$attackQ = mysql_query("SELECT * FROM users WHERE id='$user[id]' LIMIT 1");
$attackR = mysql_num_rows($attackQ);
//we check that rows are 1. if there are zero rows this means user is modifying link so we close our script!
if ($attackR <> 1) { die("Bad target ID!"); }
//all is fine, we select attacked user
$attack = mysql_fetch_array($attackQ);

//now we divide weapons to our people
if ($user[weapon3]<=$user[units]) {
//if weapon3 is more or the same of all people, then all people have it
$user_w3 = $user[units];
}else{
//only some users get weapon3
$user_w3 = $user[weapon3];
}

if ($user[weapon2]<=($user[units]-$user_w3)) {
//if weapon2 is more or the same of our people without any weapons, then they have it
$user_w2 = $user[units]-$user_w3;
}else{
//only some users get weapon3
$user_w2 = $user[weapon2];
}

if ($user[weapon1]<=($user[units]-$user_w3-$user_w2)) {
//if weapon1 is more or the same of our people without any weapons, then they have it
$user_w1 = $user[units]-$user_w3-$user_w2;
}else{
//only some users get weapon3
$user_w1 = $user[weapon1];
}

//those are our people without weapons
$user_w0 = $user[units]-$user_w3-$user_w2-$user_w1;

//now we calculate our strength
$user_strength = $user_w0*100 + $user_w1*200 + $user_w2*400 + $user_w3*800;

//We do the same thing for attacked player

//now we divide weapons to attacker
if ($attack[weapon3]<=$attack[units]) {
$target_w3 = $attack[units];
}else{
$target_w3 = $attack[weapon3];
}

if ($attack[weapon2]<=($attack[units]-$target_w3)) {
$target_w2 = $attack[units]-$target_w3;
}else{
$target_w2 = $attack[weapon2];
}

if ($attack[weapon1]<=($attack[units]-$target_w3-$target_w2)) {
$target_w1 = $attack[units]-$target_w3-$target_w2;
}else{
$target_w1 = $attack[weapon1];
}

//those are people who we attacked without weapons
$target_w0 = $attack[units]-$target_w3-$target_w2-$target_w1;

//now we calculate defender strength
$target_strength = $target_w0*100 + $target_w1*200 + $target_w2*400 + $target_w3*800;

//now to calculate casualties; we would divide strength with four (4) and then check the percentage of troops died
$att_cas = $target_strength/4;
$def_cas = $user_strength/4;

//we create formula but see that we have $target_w0 on both sides of / so we can use simple formula
//$target_w0_die = ($def_cas/$target_w0*100)*$target_w0;
$target_w0_die = ($def_cas/100);
//we cannot have more death people then we have
if ($target_w0_die >) { $target_w0_die=$target_w0; }
$target_w1_die = ($def_cas/200);
if ($target_w1_die >) { $target_w1_die=$target_w1; }
$target_w2_die = ($def_cas/400);
if ($target_w2_die >) { $target_w2_die=$target_w2; }
$target_w3_die = ($def_cas/800);
if ($target_w3_die >) { $target_w3_die=$target_w3; }
$target_killed = $target_w0_die+$target_w1_die+$target_w2_die+$target_w3_die;

//the same for our troops
$user_w0_die = ($att_cas/100);
if ($user_w0_die >) { $user_w0_die=$user_w0; }
$user_w1_die = ($att_cas/200);
if ($user_w1_die >) { $user_w1_die=$user_w1; }
$user_w2_die = ($att_cas/400);
if ($user_w2_die >) { $user_w2_die=$user_w2; }
$user_w3_die = ($att_cas/800);
if ($user_w3_die >) { $user_w3_die=$user_w3; }
$user_killed = $user_w0_die+$user_w1_die+$user_w2_die+$user_w3_die;

//we have two options
//attacker won
if ($user_strength > $target_strength) {
echo "Your troops won. You lost $user_killed units! You managed to plunder $attack[money] money.";

//we update attacker and defender, add money to attacker
mysql_query("UPDATE users SET money=money+'$attack[money]', units=units-'$user_killed' WHERE id='$user[id]'");
mysql_query("UPDATE users SET money='0', units=units-'$target_killed' WHERE id='$attack[id]'");
}

//defender won
if ($user_strength <= $target_strength) {
echo "Enemy troops were too strong. You lost $user_killed units!";

//we update attacker and defender
mysql_query("UPDATE users SET units=units-'$user_killed' WHERE id='$user[id]'");
mysql_query("UPDATE users SET units=units-'$target_killed' WHERE id='$attack[id]'");
}

}

This concludes our tutorial. I hope it was worth to wait for it!

Remember: It is not your PHP knowledge that would make game good, it is your logic and thinking! Once you have all formulas done, its easy to put them in PHP code! Read first post in this blog and you can learn basics of creating good plan of game.

What else can we do in this script:
  • formula to determine percentage of money won
  • formula to calculate loss of weapons
  • report system (so attacked user can see report of attack)
But this is up to you. I will be glad if you comment on this post, tell me about your ideas or show-off your game :)
Till next time ... enjoy.

Tuesday, September 25, 2007

Basic Strategy game - buy weapons

In this tutorial I will try to explain how to create system which would allow you to buy weapons for your units.

Again theory:

  • weapon1 doubles (2x) efficiency of soldier with it - costs 1000
  • weapon2 quadruples (4x) efficiency of soldier - cost 2000
  • weapon3 gives 8x bonus to soldier - cost 4000
  • by selling weapon you gain 75% of price back
Now lets create new php file like weapons.php (don't forget to include config.php in beginning of file).

//we need 2 form parts (html) - one for buying, one for selling
<form>
Weapon1: <input size="3" maxlength="4" value="0" name="buy1"> <br>
Weapon2: <input size="3" maxlength="4" value="0" name="buy2"> <br>
Weapon3: <input size="3" maxlength="4" value="0" name="buy3"> <br>
<input name="buy" type="submit" value="Buy">
</form>

<form>
Weapon1: <input size="3" maxlength="4" value="0" name="sell1"> <br>
Weapon2: <input size="3" maxlength="4" value="0" name="sell2"> <br>
Weapon3: <input size="3" maxlength="4" value="0" name="sell3"> <br>
<input name="sell" type="submit" value="Sell">
</form>

//now the PHP part
//first if buy button is pressed
if ($_POST[buy]) {
$buy1 = strip_tags(addslashes($_POST[buy1]));
$buy2 = strip_tags(addslashes($_POST[buy2]));
$buy3 = strip_tags(addslashes($_POST[buy3]));

//we check if it is numeric and positive
if (!is_numeric($buy1) OR !is_numeric($buy2) OR !is_numeric($buy3)) { die("Wrong input!"); }
if (($buy1 < 0) OR ($buy2 < 0) OR ($buy3 < 0)) { die("Wrong input!"); }

//we check if we have enough money
$buy_money = 1000*$buy1+2000*$buy2+4000*$buy3;
if ($user[money] < $buy_money) { die("Not enough money to buy so many weapons!"); }

//if script got it to this point it was all ok so we can update
mysql_query("UPDATE users SET money=money-'$buy_money', weapon1=weapon1+'$buy1', weapon2=weapon2+'$buy2', weapon3=weapon3+'$buy3' WHERE id='$user[id]'");
}

//we now make script which will run if we press Sell button
if ($_POST[sell]) {
$sell1 = strip_tags(addslashes($_POST[sell1]));
$sell2 = strip_tags(addslashes($_POST[sell2]));
$sell3 = strip_tags(addslashes($_POST[sell3]));

//we check if it is numeric and positive
if (!is_numeric($sell1) OR !is_numeric($sell2) OR !is_numeric($sell3)) { die("Wrong input!"); }
if (($sell1 < 0) OR ($sell2 < 0) OR ($sell3 < 0)) { die("Wrong input!"); }

//we check if user wants to sell more weapons he has
if (($sell1 > $user[weapon1]) OR ($sell2 > $user[weapon2]) OR ($sell3 > $user[weapon3])) { die("You cannot sell more weapons then you have!"); }

//we calculate how much money we will get (75%)
$sell_money = round((1000*$sell1+2000*$sell2+4000*$sell3)*0.75);

//if script got it to this point it was all ok so we can update
mysql_query("UPDATE users SET money=money+'$sell_money', weapon1=weapon1-'$sell1', weapon2=weapon2-'$sell2', weapon3=weapon3-'$sell3' WHERE id='$user[id]'");
}

This concludes our tutorial. You can see training units and buying weapons scripts are quite the same. Those are basics, but it is up to you and your game logic to create different, better and more complicated systems. (You can make use previous tutorials and add that user gets each hour 1 unit, which he can train to soldier).
In next tutorial we will create basic attack system, which would allow users to attack each other to gain money.

Basic Strategy game - train units

Today I will try to explain how to train and untrain units, which user will use to attack others or defend himself.

Theory is simple:

  • each unit cost 100 money
  • if you untrain unit it refunds you with 50 money
Now lets create new php file like train.php (don't forget to include config.php in beginning of file).

//we need 2 form parts (html)

<form>
Number: <input size="3" maxlength="4" value="0" name="train_s">
<input name="train" type="submit" value="Train">
</form>

<form>
Number: <input size="3" maxlength="4" value="0" name="untrain_s">
<input name="untrain" type="submit" value="Untrain">
</form>

//now for the PHP part
//first if train button is pressed
if ($_POST[train]) {
$train_s = strip_tags(addslashes($_POST[train_s])); //number of soldiers trained

//we check if it is numeric and positive
if (!is_numeric($train_s)) { die("Wrong input!"); }
if ($train_s < 0) { die("Wrong input!"); }

//we check if we have enough money
$train_money = $train_s * 100;
if ($user[money] < $train_money) { die("Not enough money to train so many units!"); }

//if script got it to this point it was all ok so we can update
mysql_query("UPDATE users SET money=money-'$train_money', units=units+'$train_s' WHERE id='$user[id]'");
}

//we now make script which will run if we press Untrain button
if ($_POST[untrain]) {
$untrain_s = strip_tags(addslashes($_POST[untrain_s])); //number of soldiers trained

//we check if it is numeric and positive
if (!is_numeric($untrain_s)) { die("Wrong input!"); }
if ($untrain_s < 0) { die("Wrong input!"); }

//we check if user has enough units to untrain
if ($user[units] < $untrain_s) { die("You cannot untrain so many units!"); }

//if script got it to this point it was all ok so we can update, but first calculate amount of gained money
$gain_money = $untrain_s * 50;
//we update, so we add money gained because of untraining units, and change number of units
mysql_query("UPDATE users SET money=money+'$gain_money', units=units-'$train_s' WHERE id='$user[id]'");
}

This is all for now. Soon we will create script that would allow us to buy weapons.
Bye - until next time ;)

Wednesday, September 19, 2007

Basic Strategy game - upgrade money gain (with bank)

Today I will try to explain how to create Bank structure, which would allow us to make more money per turn.

First theory of this addon:

  • each level of bank adds 5%
  • level 1 cost 500 money to upgrade
  • each level costs 30% more then last one
Now we create formulas that we will code later.
Each level of bank adds 5%, so our idea is to multiply basic amount with some coefficient. In our case this is 1.05 for level 1, level 2 will be 1.05*1.05, level 3 will be 1.05*1.05*1.05. So you can see where this is leading; we can create universal formula by using level and basic amount.
Cash we gain is then: 1.05^banklevel , in PHP this is used by pow() function.
Exactly the same we will use for costs of next level, but percentage is higher so coefficient would be 1.30 in this case.

Now to coding! Lets open config.php (from last post) and modify it.
After this:
//money amount to add for each round
$add_money = 1000;
Add:
//coefficient to use (5% addon = 1.05)
$k_money = 1.05;

Now find:
//calculate how much money user gained
$all_money = $nr_rounds * $add_money;
And change it to:
//calculate how much money user gained
$all_money = $nr_rounds * $add_money * pow($k_money, $user[bank]);

This "pow($k_money, $user[bank])" will work like we wanted to (1.05 ^ banklevel).

Now lets create new php file like upgrade.php (don't forget to include config.php in beginning of file).
//calculate money needed for next level of bank upgrade (php part of file)
$need_money = 500 * pow(1.30, $user[bank]);

//we must create form for upgrades (html part of file) with button.

<form>
Bank level: <? echo $user[bank]; ?> <br>
Next level: <input type="submit" value="<? echo number_format($need_money) ?> money" name="upgradebank">
</form>

//now we create another php part of this file (you could put that on top right after when you calculate $need_money), where we will tell what to do when button is pressed.
if ($_POST[upgradebank]) {

//we check if user has enough money to upgrade bank
if ($user[money] < $need_money) {
//we use die function to stop script execution and to show message what is wrong
die ("You don't have enough money to upgrade Bank!");
}

//everything is OK, we update our user table
mysql_query("UPDATE users SET money=money-'$need_money', bank=bank+'1' WHERE id='$user[id]'");

}


This concludes our tutorial, come back for more. :)
Next time we will create system which allows user to train units.

Any questions, ideas and comments are welcome.

Friday, September 14, 2007

Basic Strategy game - automated hourly money gain

Today I will try to explain how to create automated money gain (each hour)
Last time we created really basic system, so now it is time to upgrade it.

Main idea is that user gains some amount of money every hour (starting from his registration time). So theory is like this:

  • registration time (Unix timestamp - in seconds from 1970)
  • check in table when user money was last updated (row: lastupdate)
  • if this time is greater then 1 hour, then we update money
lets open our config.php file (which we will include_once in all our other documents). At bottom add:
//money amount to add for each round
$add_money = 1000;
//time now, and round time in seconds (1h=60*60seconds=3600)
$time_now = time();
$round = 3600;

//time of last update+time needed must be smaller then time now to update
if (($user[lastupdate]+$round) <= $time_now) {
//see how many rounds (hours) were there from last update
$nr_rounds = floor(($time_now-$user[lastupdate])/$round);
//calculate how much money user gained
$all_money = $nr_rounds * $add_money;
//calculate how many rounds in seconds (how many hours in seconds)
$add_time = $nr_rounds * $round;

//lets update users table
mysql_query("UPDATE users SET lastupdate=lastupdate+'$add_time', money=money+'$all_money' WHERE id = '$user[id]'") or die(mysql_error());

//here you can refresh page (so you can see progress) or select user again using login
}

You would say....oh my god it is so simple to make games! Well actually you need really good plan, then coding part is easy, although it needs time.

So in this lesson we learned how to add money to user every time he login. Script just checks for last update, and if there should be new update it does it. It adds money and it changes time of last update.
In next post I will explain how to allow users to spend their money to build and level-up economical structure (Bank), each level of Bank will add bonus of money gained each turn.

Feel free to comment and ask anything :)

Thursday, September 13, 2007

Starting Basic Strategy game

I have chosen to pick Action/Strategy as genre for our next game.
So basic ideas:

  • player has money (he gains it every hour - from his registration time)
  • he can train units (1 different type), and this unit can be equipped with weapon (1 out of 3)
  • he can build defensive or economical structures (to get more defense or gain more money)
  • he can attack others and steal their money
How to start?
We need database with 1 table. Structure will be like this:
ID / username / password (protect it, if nothing else then md5) / email
also we must add other things, so it would look like that:
ID / username / password / email / lastupdate / money / units / weapon1 / weapon2 / weapon3 / wall / bank

Do not forget to optimize table and set money, units, weapon1-3, wall, bank to 0 as default!
Lets say this table is called 'users' so we connect to it using config.php and selecting user that is logged in (SELECT * FROM users WHERE password='$password' AND username='$username'). We use php function to fetch this row:
$user = mysql_fetch_array($selection);
to use any thing from our logged user we can use $user[X], where X is thing we like to use. For example if we want to see how much money does logged user has, we use:
echo "Logged user has: ".$user[money]." money".
Also you must create login and registration system* (in registration when adding new user do not forget to add $time_now ($time_now = time();) variable to lastupdate column!

So lets create main page (main.php), where we will show user information:
<?
echo "Username: $user[username]<br>
E-mail: $user[email]<br>
Money: $user[money]<br>
Units: $user[units]<br>
Number of Weapon 1: $user[weapon1]<br>
Number of Weapon 2: $user[weapon2]<br>
Number of Weapon 3: $user[weapon3]<br>
Wall level: $user[wall]<br>
Bank level: $user[level]<br>";
?>

This is all we need to start our basic game.
In next post I will explain how to make that money updates automatically every hour.

*You can find tutorials on login/register system on several tutorial sites.

Start is Hard

Starting is always hard.
Not enough ideas, not good plan, voices in your head (like: why am I doing it?!)... but hey let's just start!

Warning!
This blog is not going to be like all blogs which like to be only theoretical about PHP games.
But this post is :)

Browser based games can be divided in next genres:

  1. Strategy
  2. Action
  3. RPG
  4. Sports
  5. Business
So when you have decided about genre you need to make GOOD plan for your game. Coding is easy with good plan and good economy. But how to achieve that?
  1. Try to write down everything about your future game (in short form)
  2. Create Game Design Document (where you explain all mechanism of your game)
  3. USE Excel (MS or Open ones...it does not matter), to produce your starting economy (will explain this more later)
This is all you need BEFORE you even start coding ... if you want to produce decent game.
So more about economy; it depends on what game are you making, but basically it goes like this:
  • try to write all prices down and all items (if any)
  • make and test formulas you would use, and compare different versions
  • use graphs to see your work
  • try to make everything connected (so if you change one price, then everything connected to this value changes - so you do not need to fix several things)
Now we have prepared all we need and coding can start.