Thursday, 27 June 2013

How to create an online visitors counter

Hello my friends, this is my first tutorial here, so I hope you enjoy it .

In this tutorial we will be creating an online visitors counter. You should have knowledge of the following:-

PHP and using sessions
MySQL

---------------------------Let's get started---------------------------
First we need a MySQL table to store our information, I'll be using a table structured of two fields, one is the session_id and the other is the time.


CREATE TABLE online_visitors(
session_id CHAR(100) NOT NULL DEFAULT '',
time INT(11) NOT NULL DEFAULT '0'
);



Now, let's get to PHP and make sure to read the comments

Note: you may use the following code as a function or you may save it in a file and include it, it's up to you. As for me, I will save it in a separate file .

Firstly, I will store my database connection information in a separate file and include it in my counter file. The database connection file is called dbc.php and in contains the following code:-

dbc.php

<?php
//connect to the database
$dbc = mysql_connect("localhost","root","") or die("Couldn't connect to the database server<br />".mysql_error());

//select the database 'test'
$dbs = mysql_select_db("test") or die("Couldn't select to the database<br />".mysql_error());
?>



counter.php

<?php
require("dbc.php"); //Require the database connection

//First we have to start the session only if it has not been started
if(!isset($_SESSION)){
session_start();
}


$session_id = session_id(); //We assign the session id to the variable $session_id

$time = time(); //We assign the current time to the variable $time

$time_limit = $time-600; //We give the session only 10 minutes if it exists

/**
*We need to check the session_id is already stored or not
*/
$num = mysql_num_rows(mysql_query("SELECT * FROM online_visitors WHERE session_id='{$session_id}' LIMIT 1"));

//if it doesn't exist, then we'll store it
//And if does exist, we will update the session's time in the DB
if($num != 1){
$sql = "INSERT INTO online_visitors VALUES('{$session_id}','{$time}')";
$query = mysql_query($sql) or die("Error<br />".mysql_error());
}else{
$sql = "UPDATE online_visitors SET time='{$time}' WHERE session_id='{$session_id}'";
$query = mysql_query($sql) or die("Error<br />".mysql_error());
}

//Now the following code is to get the count of visitors currently online
$noov = mysql_num_rows(mysql_query("SELECT * FROM online_visitors"));  //noov = number of online visitors

echo 'Visitors currently online: ',$noov;

//Now, check if the session was stored for more than 10 minutes and delete it if it is.
$delete_session = mysql_query("DELETE FROM online_visitors WHERE time<'{$time_limit}'");

//close the connection
mysql_close();
?>



Now, let's get to the explanation:-

1: We required the dbc.php which contains the database connection information

2: We are checking if the session has been already started, if it's not, then start the session

3: We assign the session id to the variable $session_id

4: We created two variables, one is the current time and the other contains the current time minus 10 minutes

5: We need to check the session_id is already stored or not, so we query the database and see if it doesn't exist, then we'll store it and if it does exist, we will update the session's time in the DB

6:We get the count of the total session in the table and print it.

7: We then check if the session has been in the database for more than 10 minutes, if it is, then we will delete it.

This is it, I hope you enjoyed this easy tutorial.

PHP: Functions

A function is just a name we give to a block of code that can be executed whenever we need it. This might not seem like that big of an idea, but believe me, when you understand and use functions you will be able to save a ton of time and write code that is much more readable!


For example, you might have a company motto that you have to display at least once on every webpage. If you don't, then you get fired! Well, being the savvy PHP programmer you are, you think to yourself, "this sounds like a situation where I might need functions."


Tip: Although functions are often thought of as an advanced topic for beginning programmers to learn, if you take it slow and stick with it, functions can be just minor speedbump in your programming career. So don't give up if functions confuse you at first!


creating your first php function

When you create a function, you first need to give it a name, like myCompanyMotto. It's with this function name that you will be able to call upon your function, so make it easy to type and understand.


The actual syntax for creating a function is pretty self-explanatory, but you can be the judge of that. First, you must tell PHP that you want to create a function. You do this by typing the keyword function followed by your function name and some other stuff (which we'll talk about later).


Here is how you would make a function called myCompanyMotto. Note: We still have to fill in the code for myCompanyMotto.


PHP Code:

<?php

function myCompanyMotto(){

}

?>


Note: Your function name can start with a letter or underscore "_", but not a number!

Wednesday, 26 June 2013

Animation with HTML5 Canvas

Introduction

In this article, we're going to look at some of the techniques used to produce animation on a canvas, like a player moving position in a game. We'll also take a look at adding keyboard control to the box.
Before I start, I would like to advise you to read the earlier articles Beginner's Guide to HTML5 Canvas and More Beginner HTML5 Canvas as we're going to be making use of a lot of the techniques mentioned.
How does animation work?
Animation works by changing the properties of the element, or layer, in such small increments, that it looks smooth to the user. If you slow down animation, and make these increments larger, you'll actually be able to see the element jumping between the different increments. The Code
So with that, let's get into it. The first step is, obviously, to create the canvas.
?
1
<canvas width='200' height='200' id='canvas'>Your browser does not support canvas - go get Chrome!</canvas>
We're also going to draw a square in the middle of the canvas.
?
1
2
3
4
5
6
7
8
9
10
var canvas = document.getElementById('canvas');
 
if (canvas.getContext) {
  var context = canvas.getContext('2d');
 
  context.beginPath();
  context.rect(50, 50, 100, 100);
  context.fillStyle = '#000000';
  context.fill();
}
View Demo ?
That's great, but as it is, this would be horrible for animation, so we need to put it in a function that can be reused much more easily. We'll start by first defining the function, we'll name it render. We'll also put out current render code in there too.
?
1
2
3
4
5
6
7
8
var render = function() {
    context.beginPath();
    context.rect(50, 50, 100, 100);
    content.fillStyle = '#000000';
    content.fill();
};
 
render();
View Demo ?
We'll also want to make sure we're clearing the canvas before drawing to it, as it will make it easier to change our drawing later on. We'll do this by using the function clearRect(). This is used exactly the same way that rect() is, but instead of drawing to the canvas, it clears it. We'll be wanting to clear the full canvas, so we can use canvas.width and canvas.height for the width and height parameters.
?
1
2
3
4
5
6
7
var render = function() {
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.beginPath();
    context.rect(50, 50, 100, 100);
    context.fillStyle = '#000000';
    context.fill();
};
View Demo ?
The next step is to make an object to store various parameters of our square, and alter the render function to use this object. This will make updating the square later on much easier:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var square = {
    'x': 50,
    'y': 50,
    'width': 100,
    'height': 100,
    'fill': '#000000'
};
 
var render = function() {
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.beginPath();
    context.rect(square.x, square.y, square.width, square.height);
    context.fillStyle = square.fill;
    context.fill();
};
View Demo ?
In order to produce animation, we must use a technique aptly named redrawing, which is where we repeatedly draw something, in this case the element, to the screen as often as possible. In the past, this was done using standard delay functions, such as setTimeout and setInterval, but now we can use a function called requestAnimationFrame. However, because this is still not fully supported, we must accommodate for various browser implementations, and replicate it if it doesn't exist at all.
That's quite easy to do with the below block of code. This might look complex, but actually all it's doing is attempting each variation of requestAnimationFrame for each browser, before falling back to our own function. This works because if you ask an object (in this case window) for a property, that doesn't exist, it will return undefined. Ultimately we're saying if this property is undefined, try the next property, if that's undefined, try the next one, etc... until we eventually just define it ourselves:
?
1
2
3
4
5
6
7
8
9
var requestAnimationFrame = 
        window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        function(callback) {
          return setTimeout(callback, 1);
        };
We can now make the render function redraw the square using the above function
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var render = function() {
    // Clear the canvas
    context.clearRect(0, 0, canvas.width, canvas.height);
 
    // Draw the square
    context.beginPath();
    context.rect(square.x, square.y, square.width, square.height);
    context.fillStyle = square.fill;
    context.fill();
 
    // Redraw
    requestAnimationFrame(render);
};
 
// Start the redrawing process
render();
Because we have the render function drawing the square based on the object of properties, all we have to do now is to update the square's properties, and the render function will redraw with them.
Next, we must write the function that will actually animate the square. This function will take the property to update (out of x, y, width or height), the value to update it to, and the duration of the animation.
?
1
2
3
var animate = function(prop, val, duration) {
 
};
Inside of this function, we need to do a couple of calculations, that will help us determine the progress of the animation. We'll reference the property they want to animate using square[prop], which is the same as saying square['x'] or square.x when prop equals 'x'. First we calculate the time that the animation started, and then when it should end, then finally work out the distance remaining of the animation.
?
1
2
3
4
var start = new Date().getTime();
var end = start + duration;
var current = square[prop];
var distance = val - current;
Because we need to increment the property in steps, we need a step function. This is also where you would do the calculations required for easing, though that is outside the scope of this tutorial.
?
1
2
3
4
5
var step = function() {
 
};
 
return step();
Inside the so-called step function, we need to calculate the current progress of the function, so we can work out what to set the property to. There is a little maths behind this, but it's quite simple. Where timestamp is the current timestamp in the step.
?
1
(duration - (end - timestamp))) / duration
However, we can never allow this number to be more than 1, otherwise the square will go further than intended, so we'll use the Math.min function. This function returns the smallest number out of the two arguments. So if the equation did return a number more than one, the function would still only return 1:
?
1
var min = Math.min(1, 2); // min = 1
Using this progress variable, we can calculate the value of the property for this stage of the animation. Lastly, we need to repeat the step function if the animation hasn't ended yet.
?
1
2
3
var timestamp = new Date().getTime();
var progress = Math.min((duration - (end - timestamp)) / duration, 1);
if (progress < 1) requestAnimationFrame(step);
With that, your animation should be working. For clarity, I'm going to give you the full animate function.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var animate = function(prop, val, duration) {
  // The calculations required for the step function
  var start = new Date().getTime();
  var end = start + duration;
  var current = square[prop];
  var distance = val - current;
 
  var step = function() {
    // Get our current progres
    var timestamp = new Date().getTime();
    var progress = Math.min((duration - (end - timestamp)) / duration, 1);
 
    // Update the square's property
    square[prop] = current + (distance * progress);
 
    // If the animation hasn't finished, repeat the step.
    if (progress < 1) requestAnimationFrame(step);
  };
 
  // Start the animation
  return step();
};
 
animate('x', 0, 1000);
View Demo ?

Examples

The most basic example is moving the square around, which can be done quite easily.
To move the square horizontally across the canvas, we can use the below code that will alter the x value over 1 second:
?
1
animate('x', 0, 1000);
To move the square vertically up the canvas, we can use the below code that will alter the y value over 1 second:
?
1
animate('y', 0, 1000);
To move the square diagonally we can alter both the x and y simultaneously:
?
1
2
animate('x', 50, 1000);
animate('y', 50, 1000);
View Demo ?

Extending It

What if you wanted to add keyboard controls to the box? This is slightly more complex, but shouldn't take too long to get your head around.
The idea is to start an animation for the square to move when the key is pressed down, but stop it when the key is no longer being pressed. We'll be attaching keydown and keyup events in order to listen for these keys being pressed.
?
1
2
3
4
5
6
7
document.body.addEventListener('keydown', function(e) {
 
});
 
document.body.addEventListener('keyup', function(e) {
 
});
We can use the event variable to generate information about the movement such as the property to animate and by how far. However, we'll be needing this in both the keydown and keyup events, so we'll put this in a separate function.
?
1
2
3
var meta = function(e) {
 
};
In this meta function, we need to decide which direction the square is going, and by how far. This is actually relatively easy, once you know which key codes correlate to which direction. You can find a full reference for these key codes here, but to save time, I'll give you the relevant ones here.
?
1
2
3
4
Left: 37
Right: 39
Up: 38
Down: 40
So now all we need to do is to check against the key code (contained in e.which) and then we'll have all the information we need. This function checks the event variable to see if we're going up, down, left, or right. We use a 'multiplier' variable, to make our distance negative if we're going left or up. We'll also use a prop variable to change the property we're animating if we're going up, or down.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var meta = function(e) {
    // Set some initial variables
    var distance = 100;
    var prop = 'x';
    var mult = 1;
 
    // Just return false if the key isn't an arrow key
    if (e.which < 37 || e.which > 40) {
        return false;
    }
 
    // If we're going left or up, we want to set the multiplier to -1
    if (e.which === 37 || e.which === 38) {
        mult = -1;
    }
 
    // If we're going up or down, we want to change the property we will be animating.
    if (e.which === 38 || e.which === 40) {
        prop = 'y';
    }
 
    return [prop, mult * distance];
}
Inside the keydown event, we can grab the meta information using the meta function, and then animate the square based on that information. In the key up event, we'll stop the animation.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
document.body.addEventListener('keydown', function(e) {
    var info = meta(e);
    if (info) {
        e.preventDefault();
        animate(info[0], square[info[0]] + info[1], 1000);
    };
});
 
document.body.addEventListener('keyup', function(e) {
    var info = meta(e);
 
    if (info) {
        e.preventDefault();
        animate(info[0], square[info[0]], 1000);
    };
});
View Demo ?
After adding the meta function, and the two event listeners, you should be able to move the square around the canvas using the arrow keys.

Conclusion

This should be all you need to kickstart your shiny new HTML 5 game. If you would like to see all the techniques discussed here, you can go check out this JSFiddle that I wrote during the writing of this article.