Dio bg (backgammon) beta in HTML5

bg-600-n.jpgDio bg in HTML5 is a backgammon game (called Tavli in Greek language) I was making in my free time and this is a beta version.

More »


Exporting html to pdf

You have a html page and you want to export it to pdf using an external tool only and a php file. The tool takes html data and outputs the pdf data.

More »


On javascript and AJAX

AJAX is an acronym for Asynchronous JavaScript and XML (see more) is actually a programming technique for exchanging data asynchronously between browser and server, allowing by this to create pages that have dynamic content and allowing the user to interact with the information presented.

This is done by using XMLHttpRequest object. Note: old versions of Internet Explorer (prior to 7) use the ActiveXObject object.

Here is an example:

var http = new XMLHttpRequest(), s = 'some data';
http.open("POST", "saveGames.php", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
http.onreadystatechange = httpRespSave;
http.send('data='+s);
function httpRespSave() {
if (this.readyState == 4) {
if (this.status != 200 && this.status != 304)
alert('HTTP error ' + this.status);
else
alert('Data saved successfully');
}
};

The above example sends some data to 'save.php' url. (Note that you cannot use a url from another server)

  1. creates http object
  2. declares request method as POST, url and if the request is asynchronous.
  3. set a header for content type of form
  4. set a function to be called when the ready state changes
  5. sends form data (key => value seperated with &)

the httpRespSave function only checks for readyState and request status.

Another example this time loading some data from another url:


http.open("GET", "games.json", true);
http.setRequestHeader("Cache-Control", "no-cache");
http.onreadystatechange = loadHttpResp;
http.send(null);
function loadHttpResp() {
if (this.readyState == 4) {
if (this.responseText) {
games = JSON.parse(this.responseText);
alert('Loaded '+ games.length +' games');
}
}
};

This time the request method is GET and in the response function the variable responseText has thes response.


Programming is art (?)

Sometimes like the following one it is:

So I am making another game in HTML5 (and another backgammon game) and I am using canvas for making the board's background.

Here is the process:

First we fill the following image in canvas (which is a little bigger than that):

back.jpg

Then we use canvas API to draw the borders and the game's placeholders:

canvas-pre.jpg

Sample code:

 c.fillStyle = BORDER_FILLSTYLE;
c.strokeStyle = BORDER_STROKESTYLE;
//up
c.fillRect(0,0, width, BORDER_SIZE);
// left side
c.fillRect(0,BORDER_SIZE, BORDER_SIZE, height-BORDER_SIZE*2);
c.fillRect(BORDER_SIZE, BORDER_SIZE+(6*PIONE_WIDTH), PIONE_WIDTH, 2*BORDER_SIZE);
c.fillRect(BORDER_SIZE+PIONE_WIDTH,BORDER_SIZE, BORDER_SIZE, height-BORDER_SIZE*2);
//down
c.fillRect(0,height-BORDER_SIZE, width, BORDER_SIZE);
c.fillRect(width-BORDER_SIZE,BORDER_SIZE, BORDER_SIZE, height-BORDER_SIZE*2);
...
// triangles
c.fillStyle = TRIANGLE_FILLSTYLE;
var i, x = BORDER_SIZE*2+PIONE_WIDTH, y = BORDER_SIZE, yplus = PIONE_WIDTH*5+(PIONE_WIDTH/3)*2;
for (i = 0;i < 6;i++) {
c.moveTo(x, y);
c.lineTo(x+(PIONE_WIDTH/2), y + yplus);
c.lineTo(x+PIONE_WIDTH, y);
c.lineTo(x, y);
x += PIONE_WIDTH;
}
c.fill();
...

And we have the background:

canvas.jpg

Also in order to have pawns of multiple colors we use the following textured png (easy to make it in Gimp):

pawn_back.png

And we can apply any color we want on it with some transparency. Here is the result:

final.jpg

Next thing to do is dices:)


HTML5 and gaming

HTML5 Powered with CSS3 / Styling, Device Access, Graphics, 3D & Effects, Performance & Integration, Semantics, and Offline & Storage

and specifically game development.

So initially I wanted to make a board game (backgammon) with the help of some HTML5 (with game features) library.

Here are some libraries out there with game dev features:

Finally - and after wasting some time researching / building with some libraries - I decided LimeJs would be the one.

LimeJS is a HTML5 game framework based on Closure Library by Google and extends Closure Library by adding many classes useful for game development like: Animation, audio, director (which is the base), scene (inside director), layer (inside a scene), sprite etc. For rendering DOM, canvas and WebGL are supported (latter has been added recently).

The HTML5 framework is compatible with all the major browsers and also supports touch events by touch devices. More in their site with: documentation, demos and a very good guide.

Another idea also was starting without any library - straight with Javascript language.

I also then decided to start with something simpler, as a game / test / experiment: Puzzler, a variation of jigsaw puzzle which I had made some time ago as a windows game (see Old games)

So here it is Puzzler in HTML5: Click to play

And here is the source code at GitHub.


Old games

I uploaded some old games that I had made about a decade++ ago and are still capable of running on modern Windows systems:

I suppose I really lke puzzle games :P

Issues running these games (tested on a Windows Vista system):

Agonia: Help does not work; a visit on this wikipedia greek page (game rules) solves the problem :)

Tetricom: right click on tetricom.exe file before running the game -> properties -> compatibility -> select 'Run in 256 colors'.

I had these games on a Geocities page but now this service is history.


HTML5 demos

A couple of months ago I made 2 demos for Mozilla DemoStudio, taking also part in the monthly contests for August & September.

The context for the first contest was the History API so I created a Calendar. In this you can go to the past and the future and create events using the browser's History. So I made a time machine! why didn't they gave me the first place? :P I also created an improved version that saves events locally, using localStorage and also added mouse support for selecting a day (has some issues in Chrome though).

The second context was the GeoLocation object and I created 'Cities guide'. The demo asks for your location and loads some cities info so you can view the nearest cities, sort by population and view other useful information. You can also visit (or view) other countries cities. Again a great demo! still wondering why didn't I get the first place :P

I didn't took any of the first places in the contests, but I enjoyed writing the demos both and also I learned some useful stuff like:

  • History object in Firefox can have up to 50 items.
  • localStorage: is very easy, just like set - get a cookie.
  • JSON.stringify with a hash table just doesn't work, instead use an object.
  • Javascript has (like many programming languages) a sort function using user-defined comparison function.
  • sort function is faster in Chrome than Firefox.
  • some HTML5 elements like: section, aside, article, header, etc. (didn't really used them; Google maps had issues with section, aside)
  • India is the second country (after United States) that has more cities with 5000 or more population.

Both demos have been tested only in latest Firefox and Chrome.

Canvas is another object I'm trying to learn now, not for a contest this time but maybe a game.


Resizing / converting images in php

One great (third party) tool to resize your images if available is imagemagick's command line tool: convert,  with many options and features. Here is an example:

passthru("convert -normalize -background white -quality 95 -resize x768\> -resize 1280x\> -support 0.8 +repage -interlace plane $tmpFile $destFile");

(will convert an image with maximum width 1024 or maximum height 768)

Now how about if this tool is not available?

Php can also be used to create and manipulate image files if compiled with the GD library (read more here)
So here comes a handy function that can be used for resizing both thumbnails and normal size images:


function ResizeImage($originalImage, $toWidth, $toHeight, $filename, $thumb = false)
{
    // Get the original geometry and calculate scales
    list($width, $height) = getimagesize($originalImage);
    $xscale = $width/$toWidth;
    $yscale = $height/$toHeight;

    // Recalculate new size with default ratio
    $offsetX = 0;
    $offsetY = 0;
    if ($thumb)
    {
        $new_width = $toWidth;
        $new_height = $toHeight;

        $ratioComputed = $width / $height;
        $cropRatioComputed = (float) 1 / (float) 1;

        if ($ratioComputed < $cropRatioComputed)
        { // Image is too tall so we will crop the top and bottom
            $origHeight= $height;
            $height= $width / $cropRatioComputed;
            $offsetY= ($origHeight - $height) / 2;
        }
        else if ($ratioComputed > $cropRatioComputed)
        { // Image is too wide so we will crop off the left and right sides
            $origWidth= $width;
            $width= $height * $cropRatioComputed;
            $offsetX= ($origWidth - $width) / 2;
        }

    }
    else
    {
        if ($yscale>$xscale)
        {
            $new_width = round($width * (1/$yscale));
            $new_height = round($height * (1/$yscale));
        }
        else
        {
            $new_width = round($width * (1/$xscale));
            $new_height = round($height * (1/$xscale));
        }
    }

    // Resize the original image
    $imageResized = imagecreatetruecolor($new_width, $new_height);
    $imageTmp     = imagecreatefromjpeg ($originalImage);
    imagecopyresampled($imageResized, $imageTmp, 0, 0,  $offsetX, $offsetY, $new_width, $new_height, $width, $height);

    return (imagejpeg($imageResized, $filename));
}


PHP usort: sort an array of records using a particular sequence

With PHP's usort function you are sorting an array using a custom function you have made:

function sort_by_title($a,$b)
{

  return strcasecmp($a['title'], $b['title']);

}
$myArray[0]['id'] = 1;
$myArray[0]['title'] = 'Hello';
$myArray[1]['id'] = 5;
$myArray[1]['title'] = 'Foo';
$myArray[2]['id'] = 6;
$myArray[2]['title'] = 'Foo etc';
.... and so on

usort($myArray, 'sort_by_title');

How about sorting the same array using a particular sequence of either ids, titles or whatever field of the record (using an array)?

Here is the solution:

(this example sorts the above array by a sequence that refers to the title field)

function sort_by_seq($a,$b)
{

  $seq = array('Foo', 'Hello', 'Foo etc');
  return array_search($a['title'], $seq) - array_search($b['title'], $seq);

}
usort($myArray, 'sort_by_seq');


Check out also another (sql related) tip for sorting sql result rows:

http://programming.pblogs.gr/general-tips.html which will be updated continuity with new tips.


Firefox add-ons

Back to posts...img1.jpg


So I just made my first Firefox add-on: 'Bookmarks menu'
More on that here.


A good place to start is Mozilla developers center and also "How to develop a Firefox extension"
What you will need is some html, javascript and XUL (XML User Interface Language) knowledge in order to make a Firefox add-on, time and a lot of Firefox restarts.
Well you may avoid the last since there is a helpful add-on called "Extension Developer".


Also recently Mozilla launched Jetpack an early beta of a project that will allow any web developer to build an extension easily as building a web site