Jump to content
MakeWebGames

Live/realtime stats bars


Recommended Posts

I would just have to ask, why? The get updated every time the user clicks a link. It will just add more strain on your server. The script will update via ajax then a use clicks and clicks and clicks. So its just double updating

 

They do NOT update on load. they update on next load.

Link to comment
Share on other sites

 

They do NOT update on load. they update on next load.

Ummm, no. That is not true at all. Your trying to say that globals.php and the header class get loaded on every other link click or page refresh?

 

plus for those who leave the browser window open (this is more a personal preferences, as yes this can cause strain unless force logout when idle).

create a file that includes globals_nonauth.php (you may be able to include globals.php and use the $nohdr = true variable under include('globals.php');) Perform some database queries of the information that you need and json_encode() the data. Then create an ajax call to that script and parse the json data and load into the html ids that you want to put it in

I did something like this for the Mccodes.com staff panel

http://pastie.org/10799955

Edited by KyleMassacre
Link to comment
Share on other sites

What that snippet will do is account for people that have another window/tab open. It will perform an Ajax request when the tab is only in focus (if I remember correctly lol). This way it's not just sitting there updating every 5 seconds when there not even playing the game. But if the tab is active and they are sitting there like typing a mail message or what have you it will refresh.

But in reality all you need to do is create a new file for the Ajax to perform a request to, include globals.php, add the $nohdr variable and set it to true, and echo out json_encode($ir);

Then you need to give your HTML elements some ids to add the data to.

Link to comment
Share on other sites

I came up with something like this:

I kept the log up so that you can see when the Ajax request is made and see that it is not being fired off when the page isn't in focus. Also in the video I didn't account for the status bar sizes but I fixed that after I recorded it :p and I even set up a little notification when they get a new mail message that uses either the default browser notification or a growl like notification

Link to comment
Share on other sites

Ok, so notifyme.php

 

<?php
include globals_nonauth.php;
global $db, $ir, $c, $userid;
$db->query("SELECT `energy`, `maxenergy`, `brave`, `maxbrave`, `will`, `maxwill`, `level`, `money`, `crystals`, `hp`, `maxhp`, `new_events`, `new_mail` FROM `users` WHERE `userid` = $userid");

 

notify.js (copy/pasted from above)

header

 

<script src="js/notify.js"></script>

 

mainmenu.php

 

<td colspan='2'>
<span class='label' id='energypercent'><b>Energy:</b> {$ir['energy']}/{$ir['maxenergy']}<br />
<img src='greenbar.png' width='$enpercbar' height='10' /><img src='redbar.png' width='$enopp' height='10' /></span><br />
<span class='label' id='bravepercent'><b>Stamina:</b> {$ir['brave']}/{$ir['maxbrave']}<br />
<img src='yellowbar.png' width='$brpercbar' height='10' /><img src='redbar.png' width='$bropp' height='10' /></span><br />
<span class='label' id='healthpercent'><b>Health:</b> {$hpperc}%<br />
<img src='greenbar.png' width='$hppercbar' height='10' /><img src='redbar.png' width='$hpopp' height='10' /></span><br />
<span class='label' id='willpercent'><b>Will:</b> {$wiperc}%<br />
<img src='bluebar.png' width='$wipercbar' height='10' /><img src='redbar.png' width='$wiopp' height='10' /></span><br />
<span class='label' id='expercent'><b>EXP:</b> {$experc}%<br />
<img src='bluebar.png' width='$expercbar' height='10' /><img src='redbar.png' width='$exopp' height='10' /></span><br />

 

(haven't done the mail/events part yet, that's another story)

But I've never really worked with json. So encode, parse..huh????

 

Link to comment
Share on other sites

To make your bars real time you need to learn the concept of asynchronous requests and of how php works at the minute for you.

Some terminology:

Client - The machine that your player(s) are using to access your site.

Server - The machine that stores your game code, runs it, processes requests.

How it works for now:

The client sends requests to the server. The server receives the request and process it.

Nine times out of ten these requests are GET requests.

The server handles the requests and sends a response to the client that sent the request.

So, when a player comes to your site and is simply clicking through the menu etc, it's sending requests to the server. The server is handling the requests and returning the appropriate repsonse.

When a player clicks the Explore link, the url in your code is /explore.php.

The client sends a request to the server to look for this file, and process the code in the file, and sends the response to the client. The browser on the client interprets the response and displays the result to the player. It loads the template and the content etc.

Now, as it stands, Mccodes is set up that when the client sends a request to the server, it loads the players energy and other stats into an array. Then it runs the queries that change the stats. But it doesn't change the values in the array. Therefore the values that get displayed after a page is loaded is one step behind.

You are looking for real time bars. As it stands, a request is sent and response is received. And that's the end of the connection between client and server until another link is clicked.

But for real time bars you need to be constantly sending requests to the server to receive the new values to allow you to update the page.

For this you need to learn JavaScript and AJAX. jQuery can make the process easier however.

Link to comment
Share on other sites

You are on the right track. But I would like to say that your userid variable wont work with globals_nonauth.php.

Here is what I did:

Javascript File:

var ajaxLoader = function() {
   /* This is like the __construct function in php any code that is in here
    will be executed when you do new className() */
};

function notifyMe(message, type) {
   if (typeof type == 'undefined') {
       type = 'browser';
   }
   var titleImage = ''; //Put and icon in here to display with the notification
   switch (type) {
       case 'browser':
           // Let's check if the browser supports notifications
           if (!("Notification" in window)) {
               alert("This browser does not support desktop notification");
           }
           // Let's check if the user is okay to get some notification
           else if (Notification.permission === "granted") {
               // If it's okay let's create a notification
               var icon = titleImage;
               var notification = new Notification("Hello!!", {
                   body: message,
                   icon: icon
               });
           }

           // Otherwise, we need to ask the user for permission
           else if (Notification.permission !== 'denied') {
               var icon = titleImage;
               Notification.requestPermission(function(permission) {
                   // If the user is okay, let's create a notification
                   if (permission === "granted") {
                       var notification = new Notification("Hello!!", {
                           body: message,
                           icon: icon
                       });
                   }
               });
           }

           // At last, if the user already denied any notification, and you
           // want to be respectful there is no need to bother them any more.
           break;
       case 'growl':
           $.gritter.add({
               // heading of the notification
               title: 'New Notification',
               // the text inside the notification
               text: message,
               image: titleImage
           });

           break;
   }
}

ajaxLoader.prototype = {
   onLoad: true,
   prev: {
       money: $('#money').html(),
       level: $('#level').html(),
       crystals: $('#crystals').html(),
       energyBar: $('img#energyBar').attr('width'),
       willBar: $('img#willBar').attr('width'),
       braveBar: $('img#braveBar').attr('width'),
       expBar: $('img#expBar').attr('width'),
       healthBar: $('img#healthBar').attr('width'),
       mailCount: $('#mail').html(),
       redbarWill: $('img#wiRedBar').attr('width'),
       redbarEnergy: $('img#enRedBar').attr('width'),
       redbarBrave: $('img#brRedBar').attr('width'),
       redbarExp: $('img#exRedBar').attr('width'),
       redbarHp: $('img#hpRedBar').attr('width'),
       energy: $('#energy').html(),
       health: $('#health').html(),
       exp: $('#exp').html(),
       will: $('#will').html(),
       brave: $('#brave').html()

   },
   /* Make an array of previous results so we can check against this */

   callAjax: function() {
       var self = this;
       /* used so we can access "this" within other functions */
       var alert = false;
       var money;
       var level;
       var crystals;
       var energyBar;
       var willBar;
       var braveBar;
       var expBar;
       var healthBar;
       var mailCount;
       var redbarWill;
       var redbarEnergy;
       var redbarBrave;
       var redbarExp;
       var redbarHp;
       var energy;
       var health;
       var exp;
       var will;
       var brave;
       $.ajax({ // ajax call starts
           url: '../ajax_handler.php', // change this to your php file
           dataType: 'json' // Choosing a JSON datatype
       }).done(function(data) { // Variable data contains the data we get from serverside
           var obj = data;

           $('#money').html(obj.money);
           $('#level').html(obj.level);
           $('#crystals').html(obj.crystals);
           $('img#energyBar').attr({
               width: obj.enperc
           });
           $('img#willBar').attr({
               width: obj.wiperc
           });
           $('img#braveBar').attr({
               width: obj.brperc
           });
           $('img#expBar').attr({
               width: obj.experc
           });
           $('img#healthBar').attr({
               width: obj.hpperc
           });
           $('#mail').html(obj.new_mail);
           $('img#wiRedBar').attr({
               width: 100 - obj.wiperc
           });
           $('img#enRedBar').attr({
               width: 100 - obj.enperc
           });
           $('img#brRedBar').attr({
               width: 100 - obj.brperc
           });
           $('img#exRedBar').attr({
               width: 100 - obj.experc
           });
           $('img#hpRedBar').attr({
               width: 100 - obj.hpperc
           });
           $('#energy').html(obj.enperc);
           $('#will').html(obj.wiperc);
           $('#brave').html(obj.brave + '/' + obj.maxbrave);
           $('#exp').html(obj.experc);
           $('#health').html(obj.hpperc);

       }).success(function(data) {

           var obj = data;


           money = obj.money;
           level = obj.level;
           crystals = obj.crystals;
           energyBar = obj.enperc;
           willBar = obj.wiperc;
           braveBar = obj.brperc;
           expBar = obj.experc;
           healthBar = obj.hpperc;
           mailCount = obj.new_mail;
           redbarWill = 100 - obj.wiperc;
           redbarBrave = 100 - obj.brperc;
           redbarEnergy = 100 - obj.enperc;
           redbarExp = 100 - obj.experc;
           redbarHp = 100 - obj.hpperc;
           energy = obj.energy;
           health = obj.health;
           exp = obj.exp;
           will = obj.will;
           brave = obj.brave + '/' + obj.maxbrave;

           /* Moved here as if the last if statment failed but one above
            it didnt the alert would not show */
           var alert = false;

           //This needs fixin'
           if (self.prev.mailCount < mailCount) {
               alert = true;
               amount = (mailCount - $('#mail').html());
               message = (amount > 1 ? 'You have new Messages' : 'You have a new message');
               self.prev.mailCount = mailCount;
           }

           if (self.onLoad == true) {
               self.onLoad = false;
           } else {
               if (alert == true) {
                   notifyMe(message, 'growl');
               }
           }
           timeOut = setTimeout(function() {
               self.callAjax()
           }, 5000);
           $([window, document]).on('blur', function() {
               clearTimeout(timeOut);
           });
       });
       //return false; // keeps the page from not refreshing
   }
};

$(document).ready(function() {

   var ajax = new ajaxLoader();
   /* Use the ajaxLoader class */

   ajax.callAjax();

   $([window, document]).on('focus', function() {
       ajax.callAjax();
   });
});

This is the handlers php file:

<?php
include_once('globals_nonauth.php');  
$exclude = ['userpass', 'pass_salt'];  
if(!isset($_SESSION['userid']))
{    
   return;
}
$userid = isset($_SESSION['userid']) ?: null;    
$is =$db->query("SELECT `u`.*, `us`.*
   FROM `users` AS `u`
   INNER JOIN `userstats` AS `us`
   ON `u`.`userid`=`us`.`userid`
   WHERE `u`.`userid` = {$userid}
   LIMIT 1");
while($ir = $db->fetch_row($is))
{
   check_level();
   foreach($exclude as $ex)
   {
       unset($ir[$ex]);
   }    
   $ir['money'] = money_formatter($ir['money']);
   $ir['enperc'] = min((int)($ir['energy'] / $ir['maxenergy'] * 100), 100);    
   $ir['wiperc'] = min((int)($ir['will'] / $ir['maxwill'] * 100), 100);    
   $ir['experc'] = min((int)($ir['exp'] / $ir['exp_needed'] * 100), 100);    
   $ir['brperc'] = min((int)($ir['brave'] / $ir['maxbrave'] * 100), 100);    
   $ir['hpperc'] = min((int)($ir['hp'] / $ir['maxhp'] * 100), 100);    
   echo json_encode($ir);
} 

 

You will just have to rename your divs but this returns and parses everything you need. You just either rename them in your menu file or rename them here.

Forgot to mention, I added this plugin for the growl notifications: https://github.com/jboesch/Gritter

Edited by KyleMassacre
Formattting
Link to comment
Share on other sites

ok hold on slow down.

I have 4 files and 2 edits.

I have the notify.js, the notifyme.php and the header (where java goes, I think), and then the menu where the bars are displayed. lol

I did good keeping up with you guys for awhile, but slow down remember I just picked up php about 1 month ago, lol. Everything I know about php is from this forum. sooooo, slow......down.

Link to comment
Share on other sites

Mine is fully tested and functional so what you have to do is create your JavaScript file and name it whatever you wish, then include that script in your HTML markup ( I generally put it below the body closing tag), you will also need to include the jquery JavaScript library and include that (right above the last JavaScript file) . Download that gritter library I linked up for you and add the folders with the files in your document root and add the JavaScript file for it in between your jquery library and the JavaScript file I made.

Then upload that php file I made and name it what you wish but you need to find the URL for the $.ajax call and change it to whatever you named the file.

Now your done and it's uploaded and working.

Link to comment
Share on other sites

That one looks alright but as noted by Dave, it doesn't account for a window not in focus. The script I provided (which I forgot to give credit to for his help with it [MENTION=64684]Dayo[/MENTION]. He helped me a hell of a lot with this) does take into account for people not actually playing the game. Plus it adds a notification if they receive a new mail message. I realized I didn't add events in there but can easily be done.
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...