post

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
——————–

Facebook Comments