Saturday, September 22, 2012

Simple PHP-TemplateEngine

So today I started to program a simple browsergame and I found an interesting input to use an TemplateEngine.
A TemplateEngine parse a "template HTML-File" and enter the output variables into the shown file.
One of the called TemplateEngines was Smarty. It looks like it's easy to use but I was interested in how it works.
I tried by myself to create a really simple TemplateEngine by using RegEx.

One of the first template for my engine looks like this:


<html>
    <head>
        <title>
TemplateEngine</title>
    </head>
    <body>

        <table style="font-family: Arial, sans-serif; border: 3px solid #000;">
            <tbody>
                <tr>
                    <td>
Name:</td>
                    <td>
{name}</td>
                </tr>
                <tr>
                    <td>
Prename:</td>
                    <td>
{prename}</td>
                </tr>
            </tbody>
        </table>
    </body>
</html>



The template variables {name} and {prename} should be replaced with php-variables.
I think one simple way is to use RegEx.

This is the RegEx pattern to get the full variable "{name}" and the string between the brackets "name":

#\{(.*)\}#e

We need to build up a little class in PHP and we should be able to assign variables to the TemplateEngine and render a template file:

class Template
{
    private $Variables = array();

    function __construct()
    {
    }
   
    function Assign($key, $value)
    {
        //Add the $value to the $key
        $this->Variables[$key] = $value;
    }
   
    function Render($tpl)
    {
        $content = file_get_contents($tpl);
        echo $this->ReplaceVariables($content);
    }
   
    private function ReplaceVariables($content)
    {
        return @preg_replace('#\{(.*)\}#e', '$this->Variables[\'$1\']', $content);
    }
}


So, we can assign variables and render a file to replace the template-variables with assigned variables.
The most important line is the RegEx-line:

@preg_replace('#\{(.*)\}#e', '$this->Variables[\'$1\']', $content);

We replace the template-variable with the assigned variable from the array. The RegEx-Pattern returns one variable with the string between the brackets and this string is our key to find the value in the array.

To test this code i made a little test.php file:


include('framework/TemplateEngine/Template.php');

$tpl = new Template();
$s = new thesample();
$tpl->Assign('name', 'Hodler');
$tpl->Assign('prename', 'Martin');
$tpl->Render('index.tpl')
;
 


But thats not enough for me :).
I want to be able to assign objects or arrays so i worked a bit at the Assing-Function in our Template-Class:

    function Assign($key, $value)
    {
        //Check if the $value is an object
        if (is_object($value))
        {
            //Get an array of variable-values of the $value
            $vars = get_object_vars($value);
            //Get an array of the variable-names of the $value
            $keys = array_keys($vars);
            for ($i = 0; $i < count($vars); $i++)
            {
                //Create index key. For example "{$key:objectvariable}"
                $k = $key.":".$keys[$i];
                //Add the value to the key
                $this->Variables[$k] = $vars[$keys[$i]];
            }
        }
        //Check if the $value is an array
        else if(is_array($value))
        {
            //Get the keynames by default it is numeric
            $keys = array_keys($value);
            for ($i = 0; $i < count($value); $i++)
            {
                //Create index key. For example "{$key:0}"
                $k = $key.":".$keys[$i];
                //Add the value to the key
                $this->Variables[$k] = $value[$i];
            }
        }
        else
            //By default add the $value to the $key
            $this->Variables[$key] = $value;
    }


Now we can assign a class, for example an user-class with the variables 'name' and 'prename' and call them with the template-variable '{user:name}' or '{user:prename}'.

Here the final test code:

include('framework/TemplateEngine/Template.php');
class User
{
    var
$name = "Hodler";
    var $prename = "Martin";
}

$user = new User();

$tpl = new Template();
$tpl->Assign('user', $user);
$tpl->Render('index.tpl');

 
 

 
And the template file 'index.tpl':

<html>
    <head>
        <title>
TemplateEngine</title>
    </head>
    <body>
        <table
style="font-family: Arial, sans-serif; border: 3px solid #000;">
            <tbody>
                <tr>
                    <td>
Name:</td>
                    <td>
{user:name}</td>
                </tr>
                <tr>
                    <td>
Prename:</td>
                    <td>
{user:prename}</td>
                </tr>
            </tbody>
        </table>
    </body>
</html>



And the final result looks like this:




Friday, August 24, 2012

Windows 8: Confusing for many people

Windows 8 will be released at 26. october. It's the new operating system from Microsoft that should run on several device types like desktop pcs, tablets, notebooks and netbooks. The idea to use one single OS for multiple devices is good but I think many people will have a lot of problems with the new metro-style interface.
I found some funny clips:





I think older people will have more troubles with Windows 8. Things like the Start-Button is hidden and not easy to find at the first time.
But I wish you good luck with Windows 8.

Friday, December 2, 2011

ElementAt() vs. []

Beispiel: enumeration.ElementAt(i);



In ein paar Arbeiten fiel mir auf, dass ein paar Mitarbeiter die LINQ-Methode ElementAt einsetzten.
Klar war man wollte dort ein Element aus einer Enumeration herausholen. Aber warum nicht mit den eckigen Klammern "[]".

Somit suchte ich mir die Lösung zusammen:
ElementAt kann benutzt werden falls die Enumeration keinen Indexer enthält, somit könnte die Enumeration nicht über den Indexer (eckige Klammer) abgefragt werden. Ausserdem soll die Methode auch nützlich sein falls man nicht weis wie viele Objekte in der Enumeration vorhanden sind.
Was aber ein wichtiger bestandteil diese Methode ist, ist das kontrollieren des Objekttypes. Bei ElementAt wird somit das Element an der gegebenen Position mit dem detektiertem, order vorgegebenen Typ herausgeholt.

Ich kontrollierte darauf ob diese Enumeration einen Index besitzt: Ganz einfach, ich testete es und schaute ob ein Fehler dabei raus kommt was aber nicht der Fall war.
Somit kontrollierte ich mit dem Performance Profiler von RedGate, "ANTS Performance Profiler 6.3", ob ich an dieser Stelle einen Zeitverlust zu verzeichnen habe. Der Test bestätigte meine Vermutung: Zeitverlust.
Diesen kann man somit mit den eckigen Klammern beheben falls die Enumeration einen Index enthält.


Um das ganze zeitlich zu testen, schrieb ich eine kleine Test-Applikation:





Code:


        private void BracketTest()
        {
            int tempVariable;

            //Speed test loop
            for (int i = 0; i < m_Array.Count; i++)
            {
                tempVariable = m_Array[i];
            }
        }

        private void ElementAtTest()
        {
            int tempVariable;

            //Speed test loop
            for (int i = 0; i < m_Array.Count; i++)
            {
                tempVariable = m_Array.ElementAt<int>(i);
            }
        }

Wer den Test selbst durchführen möchte kann dies gerne machen:
SpeedTest.exe*

Hier noch den ganzen Source Code:
SpeedTest.zip*


* Die Links führen auf meinen Öffentlichen Dropbox-Ordner. Die Software ist oder enthält kein Virus oder andere Schadensprogramme.

XNA


XNA - Logo


XNA was ausgeschrieben "XNA ist keine Abkürzung" (engl. "XNA's Not Acronymed") bedeutet ist eine von Microsoft entwickelte Technologie um für Microsoft Windows, Xbox 360, Zune wie auch Window Phone 7 Spiele basierend auf C# zu entwickeln.

XNA verbindet zudem verschiedene Schnittstellen wie Direct3D aus DirectX (2D und 3D Darstellung) wie auch XACT (Audio) und XInput (Peripherie) in einem einzigen Framework.



Kompatibel ist das Framework ab Visual Studio 2005 wobei aber nur die Version 2.0 dafür geeignet ist. Wer aber auch die möglichkeit haben möchte Windows Phone 7 - Spiele zu machen sollte sich mindestens die Express Version von Visual Studio 2010 herunterladen (gratis) und das XNA Framework 4.0. XNA kann als eine grundlegende Game-Engine betrachtet werden jedoch ist wirklich nur eine Basis vorhanden. Wobei zum Beispiel das laden und darstellen von Texturen, Sprites, 3D-Modellen usw. schon implementiert ist und nur noch mit einer Methode aus einer Klasse aufgerufen werden kann.

XNA - 3D Windows Phone 7 Game (Quelle: www.engadget.com)

In Visual Studio ist nach der installation von XNA ein neurer Projekttyp für Windows, Xbox, oder Windows Phone 7 Spiele verfügbar. In einem neuen Projekt sind in der Game-Klasse Methoden wie: LoadContent, UnloadContent, Update und Draw bereits vorhanden.


InitializeDort sollten die Instanzen erstellt werden.
LoadContentDient zum Laden der Texturen, Sprites, Models, Sounds, Musik usw.
UnloadContent   Dient zum freigeben von Speicher nach dem Laden.
UpdateWird mehreremale pro Sekunde aufgerufen und dient zum ausführen der Spiellogik.
DrawIst die Methode in der die Objekte auf den Bildschirm gezeichnet werden. Diese wird auch mehreremale pro Sekunde aufgerufen.

Trotz häufigen Aufrufen dier beiden letzten Methoden läut das Spiel sehr schnell und flüssig. Natürlich ist dies später auch von der Programmierung des Spiels abhängig. Nach Bewertungen und Erfahrungen von anderen Personen soll C# mit XNA bei effizientem Code ziemlich gut mit C++ mithalten können. Falls Interesse besteht: Microsoft bietet auf ihrer Seite ein Tutorial für das Entwickeln von 2D-Games an, jedoch ist dieses nicht in Deutsch verfügbar. Das Tutorial und die Ressourcen findet ihr unter folgendem Link (Englisch):
http://create.msdn.com/en-US/education/tutorial/2dgame/getting_started




Meine Erfahrungen
XNA ist ein sehr praktisches Framework um Spiele zu entwickeln. Momentan studiere ich das Entwickeln von 3D Spielen mit XNA wobei einer der grössten Aufwände das Modellieren der Objekte beansprucht. 2D Spiele waren natürlich leichter zu entwickeln, aber ich arbeite gerne mit XNA da einem vieles vereinfacht wird und vieles schon vorhanden ist. Jedenfalls würde ich XNA jedem weiter empfehlen der gerne Spiele programmieren will und grundlegend mit der Programmiersprache C# vertraut ist.