post

PHP Build a Webgame Tutorial Part 5

So here the fifth part finally is!

Hello guys,
Let me introduce you what we will be doing in the fifth part of this tutorial series:

  • Add buildings to buy in the shop
  • Make money by having a money generate building
  • Give the user money every hour.

License Agreement by downloading.
——————–
You may not sell this nor making a tutorial with the same code as i do.
You may alter the code and sell a complete php game without having to pay or credit me (only if you want to ;))
This is an open source project please share your modifications with the rest of the readers.
You must have fun scripting!
By downloading the files you agree with these terms.

Live DemoCheck it!

DownloadIts free!

 

Can’t open file? Download the extractor
——————–

First things first.

Some of my readers have done some wonderful jobs for the tutorial and sended me some assets!
The logo is designed by ShinDesign.
The template is designed by ShinDesign.
Some military units are designed by Mazing Studios.
WommbLogo_footer
I have added these assets to the tutorial and are downloadable in the download files of this part of the tutorial.
Just overwrite them in your webfolder. If you got your own template already then just follow the steps!

Lets get started with part 5!
Let’s start with adding some of the new building types where we can make money with.

Go to “http://localhost/phpmyadmin/” log in and select your database.

step1

Select the table: game_buildingtypes and add a new row with the given settings in the image.

Then add a new building to the “game_buildings” table with the settings in in the image

Now that we have done that we can create a new model to insert the buildings into the database for the right user who have bought them.

Create a new model with the name “game_buildings“.
And insert the basic commands for a new model file.

game_buildings.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Game_buildings extends CI_Model {

  function __construct() {
    parent::__construct();
  }

  function getItem($id = null) {
    
  }

  function getCost($id) {
    
  }

}

?>

New models we need to define in the configs.
So open up autoload.php found in ‘application/config/autoload.php
and change this line $autoload[‘model’] = array(‘game_users’, ‘game_units’, ‘game_army’);
to this:

autoload.php

$autoload['model'] = array('game_users', 'game_units', 'game_army', 'game_buildings');

We got the basic now prepared, lets start extending it and subtract the money from the player when he buy’s units.

First thing now we need is a new database table that holds the players buildings we keep this seperate from the army table to not bloat the table with much data.
Lets create the table and name it “game_base” with the following fields as given in the image:

tut5-3
before we can get it to work we need to create a new model “game_basemodel and lets add the following standard code to it.

game_base.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Game_base extends CI_Model {

  function __construct() {
    parent::__construct();
  } 

  function getBuildings($userID) {
    
  }

  function addBuildings($userID, $buildingID, $buildingAmount) {
    
  }

  function subtractBuildings($userID, $buildingID, $buildingAmount) {

  }

}

?>

New models we need to define in the configs.
So open up autoload.php found in ‘application/config/autoload.php
and change this line $autoload[‘model’] = array(‘game_users’, ‘game_units’, ‘game_army’, ‘game_buildings’);
to this:

autoload.php

$autoload['model'] = array('game_users', 'game_units', 'game_army', 'game_buildings', 'game_base');

Now that all is loaded and the base has been made we can actually start to code now.
Open up the model “game_base.php” and change the addbuildings() function into:

game_base.php

function addBuildings($userID, $buildingID, $buildingAmount) {
  if ( $userID == null || $buildingID == null || $buildingAmount == null ) {
    return json_encode(array('msg'=>'Something went wrong, please try again later.'));
  }
  $userMoney = $this->game_users->getMoney($userID);
  $buildingCost = $this->game_buildings->getCost($buildingID);
  $buildingTotalCost = $buildingAmount * $buildingCost;
  if ( $userMoney >= $buildingTotalCost ) {
    $query = $this->db->get_where('game_base',array('user'=>$userID, 'building_id'=>$buildingID));
    if ( $query->num_rows() > 0 ) {
      //update the current amount of units for the player
      $result = $this->db->set('building_amount', 'building_amount+'.$buildingAmount, FALSE)->where(array('user'=>$userID,'building_id'=>$buildingID))->update('game_base');
    } else {
      //first time have this units, create a clean army for the player
      $result = $this->db->insert("game_base", array('user'=>$userID,'building_id'=>$buildingID,'building_amount'=>$buildingAmount));
    }
    if ( $result ) {
      $this->game_users->subtractMoney($userID,$buildingTotalCost);
      return json_encode(array('msg'=>'You have bought new buildings.'));
    } else {
      return json_encode(array('msg'=>'Something went wrong, please try again later.'));
    }
  } else {
    return json_encode(array('msg'=>'You don\'t have enough money to buy these buildings.'));
  }
}

To make this script work we need to edit the model “game_buildings”.

Since we allready made a script like the one we want we can copy it and change it a bit (see the game_units model), open the modelgame_buildings” and change these functions with this code:

game_buildings.php

function getItem($id = null) {
  if( $id === null ) {
    $this->db->order_by("buildingcost","asc");
    $query = $this->db->get("game_buildings");
    return $query->result();
  } else {
    $query = $this->db->get_where('game_buildings', array('id' => $id));
    if ( $query->num_rows() > 0 ) {
      return $query->row(); 
    }
    return null;
  }
}

function getCost($id) {
  if ( $id == null ) {
    return null;
  }
  $query = $this->db->get_where('game_buildings', array('id' => $id));
  if ( $query->num_rows() > 0 ) {
    $row = $query->row(); 
    return $row->buildingcost;
  }
  return null;
}

We can now buy buildings, lets activate it in the controller of the shop’s buy button.
We need to change some code from the index() function in the controller named “shop.php
Change the “if statement” code to this code:

shop.php

if ( $this->input->post() ) {
  $loggedUser = $this->game_users->getByUsername($this->session->userdata('game_username'));
  $userID = $loggedUser->id;
  $buying = explode("-",key($this->input->post()));
  $id = $buying[1];
  $amount = 0+intval($this->input->post(key($this->input->post())));

  if ( $buying[0] == 'game_units' ) {
    $return = json_decode($this->game_army->addArmy($userID, $id, $amount));
  } elseif ( $buying[0] == 'game_buildings' ) {
    $return = json_decode($this->game_base->addBuilding($userID, $id, $amount));
  }

  if ( $return ) {
    $this->smarty_lib->assign('loginMessage', "<div class='errorMsg'><p>{$return->msg}</p></div><br/>");
  }
}

And add this just before the $this->smarty_lib calls:

shop.php

$content .= "<h3>Shop (buildings)</h3><table cellpadding='0' cellspacing='0' style='width: 100%;'>";
$content .= "<thead><tr><th>&nbsp;</th><th>Name:</th><th>Attack:</th><th>Defense:</th><th>Health:</th><th>Price:</th><th></th></tr></thead><tbody>";
foreach ( $this->game_buildings->getItem() as $item ) {
  $content .= "<tr>";
  $content .= "<td>".$item->image."</td>";
  $content .= "<td>".$item->name."</td>";
  $content .= "<td>".$item->attackpoints."</td>";
  $content .= "<td>".$item->defensepoints."</td>";
  $content .= "<td>".$item->healthpoints."</td>";
  $content .= "<td>".$item->buildingcost."</td>";
  $content .= "<td><form method='post'><input type='text' name='game_buildings-{$item->id}' /> <input type='submit' value='Buy'></form></td>";
  $content .= "</tr>";
}
$content .= "</tbody></table>";

Now the shop is extended with buildings! We can buy buildings but they dont appear in our overview yet.
Lets update our overview with buildings that we (or others) have bought.

Open the controller named “player.php” and add this code just before the $this->smarty_lib calls again.

player.php

$content .= '<br/>
  <strong>Buildings</strong><br/>
  <table cellpadding="0" cellspacing="0" style="width: 100%;"><thead><tr><th>&nbsp;</th><th>Name:</th><th>Amount:</th></tr></thead><tbody>'
;
$playersBase = $this->game_base->getBuildings($player->id);
if ( isset($playersBase) && !empty($playersBase) ) {
  foreach( $playersBase as $base ) {
    $baseBuilding = $this->game_buildings->getItem($base->building_id);
    $content .= "<tr>";
    $content .= "<td>".$baseBuilding->image."</td>";
    $content .= "<td>".$baseBuilding->name."</td>";
    $content .= "<td>".$base->building_amount."</td>";
    $content .= "</tr>";
  }
}
$content .= "</tbody></table>";

The overview page is working for the player.
Check if it is all still working for you (if not try to fix the error’s or leave me a post with the error you get)

 

Now that we copy, paste and edited this part for the buildings we want to generate money for the player for each ‘Oil Platform (in my example)‘ .
Let’s say that the player earn’s 100 coins each hour in a day without having any building that generates money so he can buy units / buildings when the players Oil Platforms are destroyed.
So the player can continue the game, but is less valueble for the player to attack.
And an additional 10 coins for each Oil Platform the player has.

 To make a timer that calculates like everything, there are multiple options and the best one is with a cronjob but this can only be achieved if your host support it. Also we could do it by httprequest and calculate the time diffrence but also for this option we can only do it if our host supports it.
To help everyone (i hope) with this problem about what to use, we will calculate time diffrences but not with httprequest! we will use javascript for this cause everyone can run javascript on their host.

To create something that is robust enough for this so everyone gets its money by the money buildings he owns and the default salary every hour we have to code many new things.
Grab yourself a drink and something to snack before you start with this quest.
If at the end of this tutorial you (still) have errors on your screen or things arn’t working like my example, dont be affraid to leave your problem in this post!

Ok lets do this!

Lets start by creating a new database, open your ” phpMyAdmin” and fill in the same settings as in the image:

tut5-4

We should create a fake cronjob controller we can call and with a little change could attach to a real cronjob.
Create a new file in the controller directory and call it cronjob.php.
I have commented this part so it will take lesser space in the tutorial and hopefully easier to understand.

cronjob.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Cronjob extends CI_Controller {

  function __construct() {
    parent::__construct();
  }

  function index() {
    // Only run this script when a user is logged in, minimize the request data for every guest on the site.
    if($this->session->userdata('game_username')) {
      //Only load the model when we need it and that is only in this script.
      $this->load->model("game_cronjoblog");
      // Get the last cron run record for the type 'money'
      $result = $this->game_cronjoblog->getLastCron("money");
      if( isset($result) ){
        // the time now in unix standard minus the last executed cron time is the time left for a new cron call.
        $timepast = ( strtotime(date('Y-m-d H:i:s')) - $result->executed_time );
        // if 1 hour or more has passed since last call.
        if( $timepast >= 3600 ){
          // calculate how many hours have past since the last call.
          $payoutTimes = floor($timepast/3600);
          // for every hour times the money earned is the payout a player gets without any buildings, 100 is the standard money the player gets each hour.
          $cleanPayout = $payoutTimes * 100;
          // grab all the buildings from the database that have been flagged as money generators
          $playersActive = $this->game_base->getMoneyBuildings();
          $payout = array();
          // go throught the player list of players with atleast one money building.
          foreach($playersActive as $key => $value) {
            // calculate the money a player gets and store it in an array.
            if( !isset($payout[$value->user]) ){
              $payout[$value->user] = 0+$value->earn;
            }else{
              $payout[$value->user] = ($payout[$value->user]+$value->earn);
            }
          }
          // loop through the stored array with players and their money
          foreach($payout as $user_id => $money) {
            // give every player his earned cash!
            $this->game_users->addMoney($user_id,$money);
          }

          // give every player the standard money
          $this->game_users->addMoney(null,$cleanPayout);
          // and as last we need to update the cron log as we just ran a new cronjob.
          $this->game_cronjoblog->setLastCron("money");
          echo 'You got paid!';
        }else{
          echo date("i:s",3600-$timepast);
        }
      }else{
        // if no cronjob log is found, create one as startpoint for the cronjob.
        $this->game_cronjoblog->setLastCron("money");
        echo 'Out of sync!';
      }
    } else {
      echo '';
    }
  }

}
?>

That is it for the controller, now we need to create the model to get and set the database data.
Make a new model and call it game_cronjoblog.php

game_cronjoblog.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Game_cronjoblog extends CI_Model {

  function __construct() {
    parent::__construct();
  }

  //Get the last cronjob log with the action named ...
  function getLastCron($action = null) {
    if ( $action === null ) {
      return null;
    } else {
      $query = $this->db->order_by('executed_time', 'DESC')->limit(1)->get_where('game_cronjoblog', array('action' => $action));
      if ( $query->num_rows() > 0 ) {
        return $query->row();
      }
      return null;
    }
  }

  //Set a new cronjob log with the action named ...
  function setLastCron($action = null) {
    if ( $action === null ) {
      return null;
    } else {
      $data = array(
        'executed_at' => strtotime(date('Y-m-d H:i:s')),
        'executed_time' => strtotime(date('Y-m-d H:00:00')),
        'action' => $action
      );

      $this->db->insert('game_cronjoblog', $data);
      return true;
    }
  }

}
?>

We are almost there, lets call the controller with javascript now and hopefull we will see the database get updated.

Open the template in views named “template_footer.tpl” and add the next code just before the </body> tag

template_footer.tpl

{if $this->session->userdata('game_username')}
  {literal}
    <script>
      var xhr = new XMLHttpRequest();
      xhr.open("GET","{/literal}{$smarty.const.BASE_URL}{literal}cronjob",true);
      xhr.addEventListener('load',function(){
        if(xhr.status === 200){
          jQuery("#menu p").append("<div id='timer'>Salary timer: "+xhr.response+"</div>");
          var timer = xhr.response.split(':');
          var minutes = parseInt(timer[0], 10);
          var seconds = parseInt(timer[1], 10);
          var interval = setInterval(function() {
            seconds = seconds-1;
            if(seconds <= 0 && minutes > 0){
              minutes = minutes-1;
              seconds = 59;
            }
            jQuery('#timer').html('Salary timer: '+ minutes + ':' + seconds);
            if (parseInt(minutes, 10) == 0 && parseInt(seconds, 10) == 0)
              clearInterval(interval);
          }, 1000);
        }
      },false);
      xhr.send();
    </script>
  {/literal}
{/if}

At this point we have a script that calls our cronjob code, and the cronjob code checks the database for values needed to calculate if the time has passed to update the players money.
We only need a call to the datebase and get all the buildings that gives us money. 
Lets add the function, open the model named “game_base.php” and add the next function.

game_base.php

function getMoneyBuildings() {
  $sql = "SELECT game_base.user, game_buildings.name, (game_base.building_amount * game_buildings.value) as earn FROM `game_base` left join game_buildings on game_base.building_id = game_buildings.id inner join game_buildingtypes on game_buildings.type = game_buildingtypes.id where game_buildingtypes.name = 'Money'";
  return $this->db->query($sql)->result();
}

And finally open the model named “game_users.php” and add the function:

game_users.php

function addMoney($userID, $total){
  $result = $this->db->set('money', 'money+'.$total, FALSE)->where('id', $userID)->update('game_users');
  if ( $result ) {
    return true;
  } else {
    return false;
  }
}

And in the same script change the “getMoney($userID)”  function to:

game_users.php

function getMoney($userID) {
  if( $userID == null ) {
    return null;
  }
  $query = $this->db->get_where('game_users', array('id' => $userID));
  if ($query->num_rows() > 0){
    $row = $query->row();
    return $row->money;
  }
  return null;
}

Damn we just added many codes to our game. Dont forget to save all of your hard work and test if its working!


Voila! we did it again, part 5 of the tutorial added something new and cool to the game but we do not have a game yet! Next part we will focus on some new parts of the game.
Thank you for reading this part, i hope you liked it.
In the next part we finally be able to attack eachother! so stay tuned and prepare your army for the next update 😉

For those design people out there reading this and think the demo looks ugly, just send me some icons/design’s etc. to make this tutorial better to look at for everyone 😉 just like some guy’s have done already to create a nice playable community game! Also leave your comments about what u think of the game and what you would like to see changed in the future.

License Agreement by downloading.
——————–
You may not sell this nor making a tutorial with the same code as i do.
You may alter the code and sell a complete php game without having to pay or credit me (only if you want to ;))
This is an open source project please share your modifications with the rest of the readers.
You must have fun scripting!
By downloading the files you agree with these terms.

Live DemoCheck it!

DownloadIts free!

 

Can’t open file? Download the extractor
——————–

post

PHP Build a Webgame Tutorial Part 4

So here the fourth part finally is!

Hello guys,
Let me introduce you what we will be doing in the fourth part of this tutorial series:

  • Create an inventory/barracks page.
  • Create an user overview page.
  • Make the shop work.

License Agreement by downloading.
——————–
You may not sell this nor making a tutorial with the same code as i do.
You may alter the code and sell a complete php game without having to pay or credit me (only if you want to ;))
This is an open source project please share your modifications with the rest of the readers.
You must have fun scripting!
By downloading the files you agree with these terms.

Live DemoCheck it!

DownloadIts free!

 

Can’t open file? Download the extractor
——————–

First things first.

Some of my readers have done some wonderful jobs for the tutorial and sended me some assets!
We now have a logo! The logo is designed by ShinDesign go watch his website and see his awesome work.
Also ShinDesign created a nice and clean template to use for the tutorial. You can thank him by viewing his website
Also Mazing Studios has designed some units for the tutorial to give it a feel that we are playing a game! I would like to thank Mazing Studios aswel for the effort he put into this you can thank him aswel by sending him an email.
WommbLogo_footer
I have added these assets to the tutorial and are downloadable in the download files of this part of the tutorial.
Just overwrite them in your webfolder. If you got your own template already then just follow the steps!

Lets get started with part 4!
Let us create the inventory/barracks first to hold our troops.
So we can actual buy troops and later send those troops on an attack! To start with this we will need a new database table.

Go to “http://localhost/phpmyadmin/” log in and select your database.

step1

Select the table: game_army and change the field “army” to the given settings in the image.

step2

Add 1 new field to the table and name it “army_amount” with the settings in in the image

step3

step4

Now that we have done that we can create a new model to insert the units into the database for the right user who have bought them.

Create a new model with the name “game_army“.
And insert the basic commands for a new model file.

game_army.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Game_army extends CI_Model {

  function __construct() {
    parent::__construct();
  }

  function getArmy($userID) {

  }

  function addArmy($userID, $unitID, $unitAmount) {

  }

  function subtractArmy($userID, $unitID, $unitAmount) {

  }
}
?>

New models we need to define in the configs.
So open up autoload.php found in ‘application/config/autoload.php
and change this line $autoload[‘model’] = array(‘game_users’, ‘game_units’);
tothis:

autoload.php

$autoload['model'] = array('game_users', 'game_units', 'game_army');

We got the basic now prepared, lets start extending it and subtract the money from the player when he buy’s units.
Open up the “game_armymodel again and lets change the addArmy() function.

game_army.php

function addArmy($userID, $unitID, $unitAmount) {
  if ( $userID == null || $unitID == null || $unitAmount == null ) {
    return json_encode(array('msg'=>'Something went wrong, please try again later.'));
  }
  $userMoney = $this->game_users->getMoney($userID);
  $unitCost = $this->game_units->getCost($unitID);
  $unitTotalCost = $unitAmount * $unitCost;
  if ( $userMoney >= $unitTotalCost ) {
    $query = $this->db->get_where('game_army',array('user'=>$userID, 'army_id'=>$unitID));
    if ( $query->num_rows() > 0 ) {
      //update the current amount of units for the player
      $result = $this->db->set('army_amount', 'army_amount+'.$unitAmount, FALSE)->where(array('user'=>$userID,'army_id'=>$unitID))->update('game_army');
    } else {
      //first time have this units, create a clean army for the player
      $result = $this->db->insert("game_army", array('user'=>$userID,'army_id'=>$unitID,'army_amount'=>$unitAmount));
    }
    if ( $result ) {
      $this->game_users->subtractMoney($userID,$unitTotalCost);
      return json_encode(array('msg'=>'You have bought new units.'));
    } else {
      return json_encode(array('msg'=>'Something went wrong, please try again later.'));
    }
  } else {
    return json_encode(array('msg'=>"You don't have enough money to buy these units."));
  }
}

To make this script work we need to edit some models with extra functions that we will need more often like getting the players money or the cost of a specific unit.

Lets start with getting the players money first, open the modelgame_users” and add these functions after the last function:

game_users.php

function getMoney($userID) {
  if ( $userID == null ) {
    return null;
  }
  $query = $this->db->get_where('game_users', array('id' => $userID));
  if ( $query->num_rows() > 0 ) {
    $row = $query->row();
    return $row->money;
  }
  return null;
}

function subtractMoney($userID, $total) {
  //there goes the money of the player.
  $result = $this->db->set('money', 'money-'.$total, FALSE)->where('id', $userID)->update('game_users');
  if ( $results ) {
    return true;
  } else {
    return false;
  }
}

Now we can get the money from a player, which will come handy in the future.
Now for the unit cost open the modelgame_units” and add this function after the last function:

game_units.php

function getCost($unitID) {
  if ( $unitID == null ) {
    return null;
  }
  $query = $this->db->get_where('game_units', array('id' => $unitID));
  if ( $query->num_rows() > 0 ) {
    $row = $query->row();
    return $row->unitcost;
  }
  return null;
}

Voila! We can now buy units, lets activate it in the controller of the shop’s buy button.
Add the next piece of code to the top of the index() function in the controller named “shop.php

shop.php

if ( $this->input->post() ) {
  $loggedUser = $this->game_users->getByUsername($this->session->userdata('game_username'));
  $userID = $loggedUser->id;
  $buyingUnit = explode("-",key($this->input->post()));
  $unitID = $buyingUnit[1];
  $unitAmount = 0+intval($this->input->post(key($this->input->post())));
  $return = json_decode($this->game_army->addArmy($userID, $unitID, $unitAmount));
  if ( $return ) {
    $this->smarty_lib->assign('loginMessage', "<div class='errorMsg'><p>{$return->msg}</p></div><br/>");
  }
}

And change this line:

shop.php

$content .= "<td><input type='text' /> <button onclick='alert("Buying units comes later when inventory is active.")'>Buy</button></td>";

With this:

shop.php

$content .= '<td><form method="post"><input name="game_units-'.$item->id.'" type="text" /> <input type="submit" value="Buy" /></form></td>';

Now the shop works, we can buy units and they appear in our barracks… ok wait, where can we see the units we have bought now? You have a good question there! Lets start with an overview page for our player where he can view his units and create it so that we can see another player’s his overview page also. Later on we can hide the units for non-friends/non-clannees and are only visible when spy’s are sended ;-).

For this to work we need to create a new controller, let’s name it “player.php

player.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Player extends CI_Controller {

  function __construct() {
    parent::__construct();
    if ( !$this->session->userdata('game_username') ) {
      header('Location: '.BASE_URL);
    }
  }

  public function _remap($username) {
    if ( $username == "index" ) {
      $username = null;
    }
    $this->index($username);
  }

  function index($username = null) {
    $content = '<h3>Profile Overview</h3>';

    $this->smarty_lib->assign('content', $content);
    $this->smarty_lib->view("template");
  }
}

?>

The overview page is working for the player.
Lets alter the ranklist so we can click on user and view their overview page.

Open the controller named “userlist.php” and change this line:

userlist.php

$content .= "<td>".$member->username."</td>";

with this:

userlist.php

$content .= "<td><a href='".BASE_URL."player/".$member->username."/'>".$member->username."</a></td>";

As you will see you’re overview page looks rather empty at this moment.
And you cannot see how many units you have.
Lets change that… replace these lines in the controllerplayer.php“:

player.php

$content = '<h3>Profile Overview</h3>';

$this->smarty_lib->assign('content', $content);

With this piece of code:

player.php

if ( $username != null ) {
  //Show profile of user with username ...
  $player = $this->game_users->getByUsername($username);
} else {
  //Show your profile when no username is set.
  $player = $this->game_users->getByUsername($this->session->userdata('game_username'));
}
$content = '<h3>Profile Overview</h3>
  Username:<br/><strong>'
.$player->username.'</strong><br/>
  Playing since:<br/><strong>'
.date("d-m-Y",strtotime($player->created)).'</strong><br/>
  Player Value:<br/><strong>'
.$player->worth.'</strong><br/>
  <hr>
  <br/>
  <table cellpadding="0" cellspacing="0" style="width: 100%;"><thead><tr><th>&nbsp;</th><th>Name:</th><th>Amount:      </th></tr></thead><tbody>'
;
$playersArmy = $this->game_army->getArmy($player->id);
if(isset($playersArmy) && !empty($playersArmy)){
  foreach( $playersArmy as $unit ) {
    $armyUnit = $this->game_units->getItem($unit->army_id);
    $content .= "<tr>";
    $content .= "<td><img src='".IMAGE_DIR."".$armyUnit->image."' width='120px'/></td>";
    $content .= "<td>".$armyUnit->name."</td>";
    $content .= "<td>".$unit->army_amount."</td>";
    $content .= "</tr>";
  }
}
$content .= "</tbody></table>";
$this->smarty_lib->assign('content', $content, TRUE); //replace this with the current to stop caching your units.

To make this work we need to change some of the functions and add a few new.

In the model named “game_users” we need to add a new function called “getByUsername()

game_users.php

function getByUsername($username) {
  if ( $username === null ) {
    return null;
  }
  $query = $this->db->get_where("game_users", array('username' => $username));
  if ( $query->num_rows() > 0 ) {
    return $query->row();
  }
  return null;
}

And the model named “game_units” needs a little expansion in the function getItem() so we can select on a specific unit.

Change this part of the code:

game_units.php

function getItem($id = null) {
  if ( $id === null ) {
    $this->db->order_by("unitcost","asc");
    $query = $this->db->get("game_units");
    return $query->result();
  }
}

To this:

game_units.php

function getItem($id = null) {
  if ( $id === null ) {
    $this->db->order_by("unitcost","asc");
    $query = $this->db->get("game_units");
    return $query->result();
  } else {
    $query = $this->db->get_where('game_units', array('id' => $id));
    if ( $query->num_rows() > 0 ) {
      return $query->row();
    }
    return null;
  }
}

And last, we need to get the selected user his army from the database, we do want to know what a player has in his army before we attack him! 🙂

Open the model named “game_army” and fill the getArmy() function with this code

game_army.php

if ( $userID === null) {
  return null;
}
$query = $this->db->get_where("game_army", array('user' => $userID));
if ( $query->num_rows() > 0 ) {
  return $query->result();
}
return null;

Now that its all working there are 2 things left, we can buy but can’t see how much to spend. How do we get to our own overview?
These are very easy to add for the overview page we need to edit the view named “template.tpl” (only if you have updated with the latest files)!
And add this line inside the menu <ul></ul> tag

template.tpl

<li><a href="{$smarty.const.BASE_URL}player/">Overview</a></li>

And for the money we go to the view named “template_header.tpl” after the line:

template_header.tpl

Welcome {$this->session->userdata('game_username')}, <a href="{$smarty.const.BASE_URL}logout/">Logout</a>

Add this line:

template_header.tpl

Money: &euro; <strong>{$this->game_users->getByUsername($this->session->userdata('game_username'))->money}</strong>

Voila! we did it again, part 4 of the tutorial added something new and cool to the game but we do not have a game yet! Next part we will focus on some new parts of the game.
Thank you for reading this part, i hope you liked it.

For those design people out there reading this and think the demo looks ugly, just send me some icons/design’s etc. to make this tutorial better to look at for everyone 😉 just like some guy’s have done already to create a nice playable community game! Also leave your comments about what u think of the game and what you would like to see changed in the future.

License Agreement by downloading.
——————–
You may not sell this nor making a tutorial with the same code as i do.
You may alter the code and sell a complete php game without having to pay or credit me (only if you want to ;))
This is an open source project please share your modifications with the rest of the readers.
You must have fun scripting!
By downloading the files you agree with these terms.

Live DemoCheck it!

DownloadIts free!

 

Can’t open file? Download the extractor
——————–

post

PHP Build a Webgame Tutorial Part 3

So here the third part finally is!

Hello guys,

Let me introduce you what we will be doing the third part of this tutorial series:

  • Create a lost password page.
  • Create a memberlist page.
  • Create a shop page.

License Agreement by downloading.
——————–
You may not sell this nor making a tutorial with the same code as i do.
You may alter the code and sell a complete php game without having to pay or credit me (only if you want to ;))
This is an open source project please share your modifications with the rest of the readers.
You must have fun scripting!
By downloading the files you agree with these terms.

Live DemoCheck it!

DownloadIts free!

 

Can’t open file? Download the extractor
——————–

Files – What do we need to get started ?

If you haven’t done part 1 and 2 of this tutorial yet, i recommend to read those first and download the files that are needed each part.

Like i write in all tutorials, you should play with your own design cause im not making a design for your game, this is just to explain how to create a full php webgame.
If you prefer to follow my example you could download my styled website.

Lets get started with part 3!
First we need to think of what we need and want, i prefer to continue with the user pages where he/she can retreive a lost password when your user is unable to play.

Lets start creating the controller for Lost account page.
Now lets go to your directory:
C:\xampp\htdocs\{your_folder_name}\application\controllers\” and create a file named “lost.php

Open the file and start editing!

lost.php

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Lost extends CI_Controller {

  function __construct() {
    parent::__construct();
  }

  function index() {
  $error = '';
  $content = $error.'Lost your login data?<br/>
  <form method="post">
    <table>
      <tbody>
        <tr>
          <td>Registered email:</td>
          <td><input name="email" type="text" /></td>
        </tr><tr>
          <td>&nbsp;</td>
          <td><input type="submit" value="Get my data!" /></td>
        </tr>
      </tbody>
    </table>
  </form>'
;

  $this->smarty_lib->assign('content', $content);
  $this->smarty_lib->view("template");
  }

}
?>

Like part 2 this is the base to view a page, go check it out to see what it looks like.
This won’t be enought to retreive our lost password, for that we need to define some actions.
Lets create the validation and response.

Add these lines under “$error = ”;

lost.php

if ( $this->input->post() ) {
  $this->form_validation->set_rules('email', 'email', 'trim|required|valid_email');
  if ( $this->form_validation->run() == FALSE ) {
    $error = validation_errors();
  }else{
    $error = "<strong>An email with instructions has been sent to you.</strong>";
  }
}

This piece of code will check if the input from the user is a valid email, else it will show an error.


If you have noticed the message will say that an email has been sent, hope you haven’t checked your mail for 30 minutes or longer… this email won’t be there! so stop looking and start creating the real mail.

replace this line with new code: ‘$error=”An email with instructions has been sent to you.
“;

lost.php

$to = $this->input->post('email');
$subject = "Password recovery for ".BASE_URL;
$headers = 'From: recovery@yourmail.nl' . "\r\n" .
  'Reply-To: no-reply@yourmail.nl' . "\r\n" .
  'X-Mailer: PHP/' . phpversion();
$recoveryLink = md5(date('d-m-Y H:i:s').'-'.$this->config->item('encryption_key'));
$message = "You or someone else has requested a password reset, if it isn't you do nothing else go to this link: ".BASE_URL."lost/reset/".$recoveryLink;
if ( mail($to, $subject, $message, $headers) ) {
  $error = "<strong>An email with instructions has been sent to you.</strong>";
} else {
  $error = "<strong>Sending the mail failed, try again later.</strong>";
}

We just added some basic variables for the email like subject, to address and the content with a link. And finally mail those variables to ourself.
You could try the page again to see if its working. (If you try this on localhost it won’t work unless you have set up a mail server on your computer try it online for direct results).

If you’re able to test this then you will see the mail arrives in you inbox, the only thing that didn’t worked was the link provided by the email! Lets fix this right away!

Add the this code under the index() function

lost.php

function reset() {
  if ( $this->input->post() ) {
    if ( $this->game_users->resetPassword() ) {
      $content = 'Password succesfully reset, login with your new password.';
    } else {
      $content = '<div class='errorMsg'>Password not reset, wrong information given!</div>';
    }
  } else {
  $content = 'Reset your password<br/>
    <form method="post">
      <table>
        <tbody>
          <tr>
            <td>Registered email:</td>
            <td><input name="email" type="text" /></td>
          </tr><tr>
            <td>New password:</td>
            <td><input name="password" type="password" /><input name="indentification" type="hidden" value="'
.$this->uri->segment(3).'" /></td>
          </tr><tr>
            <td>&nbsp;</td>
            <td><input type="submit" value="reset password" /></td>
          </tr>
        </tbody>
      </table>
    </form>'
;

  }
  $this->smarty_lib->assign('content', $content);
  $this->smarty_lib->view("template");
}

Add the next code under the line: if(mail($to, $subject, $message, $headers)) {

lost.php

$this->db->where('email', $to);
$this->db->update('game_users', array("lostpassword" => $recoveryLink));

And finally create a new function in the model named game_users.php

game_users.php

function resetPassword() {
  $data = array(
    'email' => $this->input->post('email'),
    'lostpassword' => $this->input->post('indentification')
  );
  $query = $this->db->get_where("game_users", $data, 1);

  if ( $query->num_rows() == 1 ) {
    $this->db->where($data);
    $this->db->update('game_users', array("lostpassword" => null, "password" => md5($this->input->post('password'))));
    return true;
  }else{
    return false;
  }
}

Try to test if you can reset your password this time. Works ? great! now that this part is done we can create a list of members when we are logged in that we could attack.

To do this we need to create a new controller and call this file ‘userlist.php‘ insert the following code:

userlist.php

< ?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Userlist extends CI_Controller {

  function __construct() {
    parent::__construct();
    if ( !$this->session->userdata('game_username') ) {
      header('Location: '.BASE_URL);
    }
  }

  function index() {
    $content = 'Member list.';
    $this->smarty_lib->assign('content', $content);
    $this->smarty_lib->view("template");
  }

}

?>

Now we can reach the page we should add it to the menu first, to see if we can only reach it when we are logged in!

Open the View named template_header.tpl (application/views/template_header.tpl)
And add the following line just above the the line: <a href='{$smarty.const.BASE_URL}logout/’>Logout</a>

template_header.tpl

<a href="{$smarty.const.BASE_URL}userlist/">Rankinglist</a><br/>

Save your work and test if it works.
If it’s all OK then we can grab some coffee or walk the dog to let our brains and vingers rest for a minute.

Back already? Ok lets continue with the member list.
Open the userlist controller and edit the index() function.
Overwrite “$content = ‘Member list.’;” with the following code.

userlist.php

$content = "Memberlist:";
$content .= "<table cellpadding='0' cellspacing='0' style='width: 100%;'>";
$content .= "<thead><tr><th></th><th>Username:</th><th>Protected?</th><th>Land worth:</th><th>Playing since:</th><th></th></tr></thead><tbody>";

foreach( $this->game_users->getUser() as $member ) {
  $content .= "<tr>";
  $content .= "<td></td>";
  $content .= "<td>".$member->username."</td>";
  $content .= "<td>".(($member->protected == 1) ? "Yes" : "No")."</td>";
  $content .= "<td>".$member->worth."</td>";
  $content .= "<td>".$member->created."</td>";
  $content .= "<td><a>attack!</td></a>";
  $content .= "</tr>";
}
$content .= "</tbody></table>";

Now we have created only the view for the list but haven’t got anything that is selecting all the players yet to display.
To do that we need to add a new model function to the user database.
So lets open the model named ‘game_users.php‘ and add the next function at the bottom:

game_users.php

function getUser($id = null) {
  if ( $id === null ) {
    $this->db->order_by("worth","desc");
    $query = $this->db->get("game_users");
    return $query->result();
  }
}

When all is saved and inserted into the code you could test your website.
Lets see if you can see the member list and the registered members.
And do not attack them yet 😉 we arn’t that far yet!

Only one page left this tutorial the shop page!
Creating pages is very similar to eachother so lets repeat the steps for the memberslist only with the shop this time.

First create a new controller named ‘shop.php‘ and add the following code to it:

shop.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Shop extends CI_Controller {

  function __construct() {
    parent::__construct();
    if ( !$this->session->userdata('game_username') ) {
      header('Location: '.BASE_URL);
    }
  }

  function index() {
    $content = 'Welcome to the shop.';
    $this->smarty_lib->assign('content', $content);
    $this->smarty_lib->view("template");
  }

}

?>

Now we can reach the page we should add it to the menu first, to see if we can only reach it when we are logged in!

Open the View named template_header.tpl (application/views/template_header.tpl)
And add the following line just above the the line: <a href='{$smarty.const.BASE_URL}userlist/’>Rankinglist</a>

template_header.tpl

<a href="{$smarty.const.BASE_URL}shop/">Shop</a><br/>

Save your work and test if it works.
If its all OK then we continue creating a new model, name it ‘game_units.php‘.
Insert the following code to get items from the database:

game_units.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Game_units extends CI_Model {
  function __construct() {
    parent::__construct();
  }

  function getItem($id = null) {
    if ( $id === null ) {
      $this->db->order_by("unitcost","asc");
      $query = $this->db->get("game_units");
      return $query->result();
    }
  }
}
?>

The only thing with new models is, that we need to define them in the configs.
So open up autoload.php found in ‘application/config/autoload.php
and add the new model to this line $autoload[‘model’] = array(‘game_users’);
like this:

autoload.php

$autoload['model'] = array('game_users', 'game_units');

Now in the shop controller we only need to load the data through the model to the view!
So change the next line ‘$content = ‘Welcome to the shop’;‘ in the controller named ‘shop.php‘ to the following code:

shop.php

$content = "Shop:";
$content .= "<table cellpadding='0' cellspacing='0' style='width: 100%;'>";

foreach( $this->game_units->getItem() as $item ) {
  $content .= "<tr>";
  $content .= "<td>".$item->image."</td>";
  $content .= "<td>".$item->name."</td>";
  $content .= "<td>".$item->attackpoints."</td>";
  $content .= "<td>".$item->defensepoints."</td>";
  $content .= "<td>".$item->healthpoints."</td>";
  $content .= "<td>".$item->unitcost."</td>";
  $content .= "<td><input type='text' /><button>Buy</button></td>";
  $content .= "</tr>";
}
$content .= "</tbody></table>";

Now you can see the shop has some units for sell.
You cannot buy them yet, but soon you will!

This was part 3 of the tutorial.
In the next tutorial we will create some more pages and most likely an inventory to store your units in.
Thank you for reading this part, i hope you liked it.

For those design people out there reading this and think the demo looks ugly, just send me some icons/design’s etc. to make this tutorial better to look at for everyone ;-).

License Agreement by downloading.
——————–
You may not sell this nor making a tutorial with the same code as i do.
You may alter the code and sell a complete php game without having to pay or credit me (only if you want to ;))
This is an open source project please share your modifications with the rest of the readers.
You must have fun scripting!
By downloading the files you agree with these terms.

Live DemoCheck it!

DownloadIts free!

 

Can’t open file? Download the extractor
——————–

post

PHP Build a Webgame Tutorial Part 2

So here the second part finally is!

Hello guys,

Let me introduce you what we will be doing the second part of this tutorial:

  • Create a working login page.
  • Create a working register page.
  • Create a working password lost page.
  • Create a working profile page.

License Agreement by downloading.
——————–
You may not sell this nor making a tutorial with the same code as i do.
You may alter the code and sell a complete php game without having to pay or credit me (only if you want to ;))
This is an open source project please share your modifications with the rest of the readers.
You must have fun scripting!
By downloading the files you agree with these terms.

Live DemoCheck it!

DownloadIts free!

 

Can’t open file? Download the extractor
——————–

Files – What do we need to get started ?

If you haven’t done part 1 of this tutorial yet, i recommend to read it first and download the files that are needed from there.

Like i wrote in last tutorial, you should play with your own design cause im not making a design for your game, this is just to explain how to create a full php webgame.
If you prefer to follow my example you could download my styled website.

At this moment there arn’t many members that downloaded it yet so i dont know if this topic is populair or not but i hope that new viewers will register to follow this tutorial and give some feedback or questions 🙂

While doing the whole tutorial we will be start programming in PHP in OOP (Object Orientated Programming) / MVC (Model View Controller)!

Lets get started with part 2!
First we need to think of what we need and want, i prefer to start with the user part where he/she can register and login to view their account.
If i got this, i can easy check without manual inserting rows in the Database, and let my friends test it to see if it all works.
*People other then yourself will find bugs much faster as they don’t know the system like you do.*
After i got the user part i can focus on the rest, how i see it now i will break it apart in parts of:

  1. User Login / Registration / Profile
  2. Unit setup / Market
  3. Building setup / Market
  4. Currency (with Cronjobs or by Date calculation)
  5. Attack / Defend others
  6. Leftovers like HighScore / Page content / Protection / etc.
  7. Backend to let the admin control everything.
  8. Finishing touch.

Lets start creating the controllers for Register Account, Login, Profile and Lost account.
Now lets go to your directory:
C:\xampp\htdocs\{your_folder_name}\application\controllers\” and open the file named “index.php

Here we will put all the handling and variables for the Login and Profile.
The Controllers will send everything to the Views so we keep the HTML code and PHP code clean, as you will see in this tutorial.
The Controllers will call the Models for database connection so we try to keep everything related to the database as well away from the PHP code.
This will give you a nice overview where everything is and easy to expand your code later with new things, or modify it without searching where you wrote the code.

If you downloaded the files of this tutorial, your “index.php” will look like this, it may differ a bit but don’t worry.

index.php

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Index extends CI_Controller {

  function __construct() {
    parent::__construct();
  }

  function index() {
    $this->smarty_lib->assign('content', "Welcome to WommBattle!<br/><br/>You need an account to enter the combat<br/>So why dont you create one now?");
    $this->smarty_lib->view("template");
  }

}
?>

The index() function is always the one that will be called if you call the controller (unless defined else in the __construct).
So we check if a form post is send to the page and then parse the data to the index (if we set the form action to this controller).
Type this inside your “function index()” just above the 2 rows that are already there:

$error = "";
if( $this->input->post() ) {
  $this->form_validation->set_rules('username', 'username', 'trim|required|min_length[5]|max_length[25]');
  $this->form_validation->set_rules('password', 'password', 'trim|required');
  if ( $this->form_validation->run() == FALSE ) {
    $error = "<div class='errorMsg'>   ".validation_errors()."</div>";
  } else {
     //We could be logged in, if username and password matches!
  }
}

$this->smarty_lib->assign('loginMessage', $error);


At this point we can allmost log into our website, but before that we need to create an account first, so lets start with the register function so we can actual register and test the login form with a created account.

Create a new controller in “C:\xampp\htdocs\{your_folder_name}\application\controllers\” and name it “register.php

We start with the basic controller code so CodeIgniter can read it, and we can open this page.

register.php

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Register extends CI_Controller {

  function __construct() {
    parent::__construct();
  }

  function index() {
   $this->smarty_lib->assign('content', 'The register form will go here.');
   $this->smarty_lib->view("template");
  }

}

?>

Save your script and lets try to reach it, open up your browser and go to: “http://localhost/{your_folder_name}/register/“.
You will notice that the content is changed to: “The register form will go here.

Register created

This is a good start! We will now create the real form.
Lets expand the code in “register.php“:

register.php

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Register extends CI_Controller {

  function __construct() {
    parent::__construct();
  }

  function index() {
    $error = '';
    if( $this->input->post() ) {
      $this->form_validation->set_rules('username', 'username', 'trim|required|min_length[5]|max_length[25]|is_unique[game_users.username]');
      $this->form_validation->set_rules('password', 'password', 'trim|required');
      $this->form_validation->set_rules('email', 'email', 'trim|required|valid_email|is_unique[game_users.email]');

      if ( $this->form_validation->run() == FALSE ) {
        $error = " ".validation_errors()." ";
      } else {
        $error = "<div class='successMsg'>Account created with success!</div>";
      }
    }

    $content = $error.'Register your account and start the battle!<br />
    <br />

    <form method="post">
      <table>
        <tbody>
         <tr>
           <td>Username:</td>
           <td><input name="username" type="text" /></td>
         </tr><tr>
           <td>Email:</td>
           <td><input name="email" type="text" /></td>
         </tr><tr>
           <td>Password:</td>
           <td><input name="password" type="password" /></td>
         </tr><tr>
           <td>&nbsp;</td>
           <td><input type="submit" value="Register!" /></td>
         </tr>
       </tbody>
     </table>
   </form>'
;

    $this->smarty_lib->assign('content', $content);
    $this->smarty_lib->view("template");
  }

}

?>

Save your work and try it out.
You will see that it will give messages to you when the form fails and says it is created with success when it passes the validation.

Register form created

The validation will check on different things now:

  1. Username is required and need minimal 5 characters and maximal 25 characters also the username must be unique in our database user table.
  2. Password is only required with no further restrictions
  3. Email is required it will check if it is a valid email address and if the email address is unique in our database user table.

Now before we actually add the data to the database we will be making a model first to process it.

Create a new model in “C:\xampp\htdocs\{your_folder_name}\application\models\” and name it “game_users.php” just like how we called our table in the database.

And add this code to it:
game_users.php

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Game_users extends CI_Model {

  function __construct() {
    parent::__construct();
  }
}
?>

This is the start of all models you will be creating, just like the controllers.
Now lets add the piece of code that will add the new registered user to the database with the given values!

game_users.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Game_users extends CI_Model {

  function __construct() {
    parent::__construct();
  }

  function registerUser($_POST) {
    $date = date('Y-m-d H:i:s');
    $ip = "xx.xx.xx.xx";

    //Check valid user IP on diffrent ways
    if ( !empty($_SERVER['HTTP_CLIENT_IP']) ) {
      $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif ( !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
      $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }else{
      $ip = $_SERVER['REMOTE_ADDR'];
    }
    //End IP check

    $data = array(
      'username' => $this->input->post('username'),
      'password' => md5($this->input->post('password')),
      'email' => $this->input->post('email'),
      'started' => '1970-01-01',
      'created' => $date,
      'ip' => $ip
    );

    $query = $this->db->insert("game_users", $data);

    if( $query ) {
      return true;
    }else{
      return false;
    }
  }

}
?>

You can see that i created a new function in the model the function will insert the user given data into the database.
If you do not understand what the function does please read it a few times over or check the CodeIgniter manual on the CodeIgniter website.

Now it is almost working the last thing to do is including the model in the autoload of CodeIgniter!
Go to “C:\xampp\htdocs\{your_folder_name}\application\config\autoload.php” and scroll all the way down to line number 112.

You will see:

$autoload['model'] = array();

Change it to:

$autoload['model'] = array('game_users');

Lets try it out by calling the model in our register form!
Open the controller “C:\xampp\htdocs\{your_folder_name}\application\controllers\register.php” and add the following line:


register.php

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Register extends CI_Controller {

  function __construct() {
    parent::__construct();
  }

  function index() {
    $error = '';
    if( $this->input->post() ) {
      $this->form_validation->set_rules('username', 'username', 'trim|required|min_length[5]|max_length[25]|is_unique[game_users.username]');
      $this->form_validation->set_rules('password', 'password', 'trim|required');
      $this->form_validation->set_rules('email', 'email', 'trim|required|valid_email|is_unique[game_users.email]');

      if ($this->form_validation->run() == FALSE){
        $error = " ".validation_errors()." ";
      }else{
        $error = "<div class='successMsg'>Account created with success!</div>";
        $this->game_users->registerUser($this->input->post());
      }
    }
    $content = $error.'Register your account and start the battle!<br/>
    <br/>
    <form method="post">
      <table>
        <tbody>
          <tr>
            <td>Username:</td>
            <td><input name="username" type="text" /></td>
          </tr><tr>
            <td>Email:</td>
            <td><input name="email" type="text" /></td>
          </tr><tr>
            <td>Password:</td>
            <td><input name="password" type="password" /></td>
          </tr><tr>
            <td>&nbsp;</td>
            <td><input type="submit" value="Register!" /></td>
          </tr>
        </tbody>
      </table>
    </form>'
;
    $this->smarty_lib->assign('content', $content);
    $this->smarty_lib->view("template");
  }

}

?>

That should do the trick! Now try to create your first account.
*Note: you could try to create another one with either the same username or email and you will see it an error message back.*

Using register to fill the database

Ok now we registered our account but we can’t log in!
Let’s finish the login form as well!

We need to expand our “game_users” model to handle the login part.
So open: “C:\xampp\htdocs\{your_folder_name}\application\models\game_users.php” again and add this function.

game_users.php

function loginUser() {
  $data = array(
    'username' => $this->input->post('username'),
    'password' => md5($this->input->post('password'))
  );
  $query = $this->db->get_where("game_users", $data, 1);
  if( $query->num_rows() == 1 ) {
    return true;
  } else {
    return false;
  }
}

This function will tell our controller if the username and password match and return true, or do not match and return false.
Like i just said, it will tell us the match outcome to the controller, so lets open our controller:

C:\xampp\htdocs\{your_folder_name}\application\controllers\index.php

The line:

//We could be logged in!

And replace it with:

if( $this->game_users->loginUser() ) {
  $this->session->set_userdata('game_username', $this->input->post('username'));
}

Now we only need to change our view when we are logged in, i’ve decided to do this in the template_header view.
Later on we will create a library for this, but because we did already pretty much we will try to avoid more files we do not really need yet.

So lets open and change some lines: “C:\xampp\htdocs\{your_folder_name}\application\views\template_header.tpl

{* Menu if logged in *}
{if $this->session->userdata('game_username')}
  Welcome, {$this->session->userdata('game_username')}<br/>
  Lets create some chaos!<br/><br/>
  <a href="{$smarty.const.BASE_URL}logout/">Logout</a>
{else}
  {* Menu if logged out *}
  Are you allready part of the war?<br/>
  Login now!<br/><br/>
  <form action="{$smarty.const.BASE_URL}" method="post">
    username:<br/><input name="username" type="text" /><br/>
    password:<br/><input name="password" type="password" /><br/>
    <input type="reset" value="reset" /> <input name="loginBtn" type="submit" value="login" />
  </form>
  <br/>
  <a href="{$smarty.const.BASE_URL}lost/">lost password</a> | <a href="{$smarty.const.BASE_URL}register/">register</a>
{/if}

As you can see we added a new link called “logout”, because i like to safely close my profile so no one else can play with my game data.

Now save your file and try to login.

Succesfully logged in!

To log out we need a need controller to handle the logout process.
Go to and create: “C:\xampp\htdocs\{your_folder_name}\application\controllers\logout.php


logout.php

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Logoutextends CI_Controller {

  function __construct() {
    parent::__construct();
  }

  function index() {
    $this->session->sess_destroy();
    $this->load->helper('url');

    redirect(base_url());
  }

}

?>

And we can now even logout!

At this point i will stop with part 2, now it is time for you guy’s to play with your website (mockup) create something nice for the game you’ve got in your mind and try to add more register fields and validation checks!
The next tutorial we will be creating many things for the website like the menu, the contents, and more! so be sure to check back often for updates!

Leave a message or some screenshots please, i would like to see how you guys are doing it or if you are stuck at a point i could help you with.

Good luck and have fun with programming!

 

License Agreement by downloading.
——————–
You may not sell this nor making a tutorial with the same code as i do.
You may alter the code and sell a complete php game without having to pay or credit me (only if you want to ;))
This is an open source project please share your modifications with the rest of the readers.
You must have fun scripting!
By downloading the files you agree with these terms.

Live DemoCheck it!

DownloadIts free!

 

Can’t open file? Download the extractor
——————–

post

PHP Build a Webgame Tutorial Part 1

Finally the first part has arrived!

Hello guys,

Let me introduce you what we will be doing the first part of this tutorial:

  • Download all the stuff we need.
  • Install it and set up the project.
  • First look at what we are working with.
  • Make a template in our own style with basic HTML & CSS code.
  • Explaining what we have done and what you can do before the next part.

License Agreement by downloading.
——————–
You may not sell this nor making a tutorial with the same code as i do.
You may alter the code and sell a complete php game without having to pay or credit me (only if you want to ;))
This is an open source project please share your modifications with the rest of the readers.
You must have fun scripting!
By downloading the files you agree with these terms.

Live DemoCheck it!

DownloadIts free!

 

Can’t open file? Download the extractor
——————–

Files – What do we need to get started ?

First of all we need something to compile the PHP code on our local machine.
PHP is a server side script that needs to be compiled by the server and then sended to the viewing user in propper HTML.
HTML code is a browser/client script that can be viewed with it need to be compiled by a server first.

For this we dont really need a compiler for the PHP as we won’t be using PHP in now but we will be using it in the next part!

While doing the whole tutorial we will be using a few library’s:

1. CodeIgniter (an Application Development Framework, for clean scripting in MVC)

2. Smarty (a Template Engine for PHP this will be used as the (V)iew in CodeIgniter)

3. jQuery (a JavaScript library for some nice and easy to code effects)

4. And HTML and CSS.


If you like to customize your website other then the tutorial, you should read the documents here to know what you can with it. Also if i forget to explain something they got a full documentation on their sites where you can check it out.

Lets get started!
First we need Xampp go to www.apachefriends.org/en/xampp.html and download the version you need (Windows / Linux etc.) install the program by following the instructions given.

After you have installed it with success you should have a directory like “C:\xampp\htdocs\
this is the directory where you should put your projects in to access them with your browser.
For more information about Xampp please read it on the website.

Now lets go to your directory “C:\xampp\htdocs\” and create a new folder.
Name this foldermygame” (or whatever you like to call it, but do not use spacebar, numbers or uppercase characters)

I created a basic template for you with all the connections and Database we will be using during this tutorial.
Download it and place the files in the folder you just created.

After you have placed this in “C:\xampp\htdocs\{your_folder_name}\” we will need to adjust some config files to get it working propper.

  • Open C:\xampp\htdocs\{your_folder_name}\.htaccess, change line 3 “tutorial” with {your_folder_name}
  • Open C:\xampp\htdocs\{your_folder_name}\application\config\constants.php, change line 40 “tutorial” with {your_folder_name}
  • Open C:\xampp\htdocs\{your_folder_name}\application\config\database.php, change the variables with your database setup, also on line 47 change “tutorial” to the database name you like to use (We will set the database after this).


Now lets go to your database.

Open your browser and go to “http://localhost/phpmyadmin/” this should open the database screen for you.

Create a database with the name you earlier picked in the database.php file.
Go to import and select the database file i created for you. “C:\xampp\htdocs\{your_folder_name}\database\complete.sql

At this point we have done all we need for now.
Lets try to open the website: “http://localhost/{your_folder_name}/” if you did it all right, then you should see: “This will be you template file.” on your screen.

You can grab a cup of coffee now or some food cause you completed the first part,

Lets go further with the real thing now!

Lets go to the template file and start designing our webgame!
Open “c:/xampp/htdocs{your_folder_name}/application/views/template.tpl“.

You will see the next lines in it:

Here we will begin with creating our style.
If you don’t have any knowledge with basic HTML i like to reffer you to my other tutorials i have some basic HTML tutorials there.

Click here for the first HTML tutorial
Click here for the second HTML tutorial
Click here for the third HTML tutorial
Click here for the fourth HTML tutorial

Lets create the frame for the website first, we will need the page to be centered and have a menu at the top and when a player logged in we want a menu at the left aswell.
We will create a page with this setup.

Logo and menu
Menu
if
logged
in
Here all the information will go.
Your copyright etc.

Lets start with writing a wrapper to keep it all together and in the center.

template.tpl

{* Header will be inserted at the very beginning of every page as it will always be the same. *}
{include file='template_header.tpl'}

{* Content will be diffrent and keep every page that is called *}
<div id="wrapper">
  <div id="weblayout">
    <div id="header">Logo and menu</div>
    <div>
      <div id="menu">Menu if logged in</div>
      <div id="content">Here all the information will go.{$content}</div>
    </div>
    <div id="footer">Your copyright etc.</div>
  </div>
</div>
{* Footer will be inserted at the end of every page as it is always the same. *}

{include file='template_footer.tpl'}

What we have done here is created some blocks with text in it, it will look like some simple text rules now if you open your website but we will fix this!
We gave every div an unique name so we can reconize what it will be (aswell as the code will reconize this).

Lets give the website some color!
Open “c:/xampp/htdocs/{your_folder_name}/public/css/default_style.css“.

You will see 4 things in there:

  1. body{}
  2. a{}
  3. a:link{}
  4. a:hover{}

Lets put our just created blocks in it and give them some color  (If you give an element the Tag id=”” you can call them with # in your css file)

default_style.css

body {
  background-color: #000000;
  color: #000000;
  font-family: arial;
  font-size: 12px;
  margin: 0px;
  padding: 0px;
}

a {

}

a:link {

}

a:hover {

}

#wrapper {
  /* we need the full screen so we can center easly in the browser */
  width:100%;
}

#weblayout {
  width: 950px; /* width of our website */
  border: 1px solid #FFFFFF;
  margin: 0px auto;
}

#header{
  height:225px;
  width: 100%;
  background-color: #FF0000;
}

#menu {
  float:left;
  width:225px;
  min-height: 300px;
  background-color: #00FF00;
}

#content {
  float:right;
  width:725px;
  min-height: 300px;
  background-color: #FFFF00;
}

#footer {
  clear: both;
  height:30px;
  width: 100%;
  background-color: #0000FF;
}

If you save our work and try to open you website again you will see a big difference with the last time you visited.
We gave the blocks some style and created the first part of our mockup.
Do you want to know more about css? Try my tutorial or visit w3schools for more information about what you can do with it.

At this point i will stop with part 1, now it is time for you guy’s to play with your website (mockup) create something nice for the game you got on your mind!
The next tutorial we will be creating many things for the website like the menu, the contents, and more! so be sure to check often for updates!

Leave a message or screenshots please, i would like to see how other’s are doing or if you are stuck at a point i could help you out with it.

Good luck and have fun!

License Agreement by downloading.
——————–
You may not sell this nor making a tutorial with the same code as i do.
You may alter the code and sell a complete php game without having to pay or credit me (only if you want to ;))
This is an open source project please share your modifications with the rest of the readers.
You must have fun scripting!
By downloading the files you agree with these terms.

Live DemoCheck it!

DownloadIts free!

 

Can’t open file? Download the extractor
——————–