Begining HTML5 game part 2

To continue Begining HTML5 game part 1 .

Download images for this tutorial .

https://docs.google.com/open?id=0B3wmdk4k7b_-V3Q1TTVIWW5LaWM (Save s to get zip package)

We using simple html5 game framework for develop a card game . Maybe blackjack

First, you need create Struct Folder to easy manager when your project become  complex 


In WebContent-> index.html :
Body part, add code into body of index.html file
       
<canvas id="gameCanvas" width="800"  height="550">
</canvas>

Body tag : add code into body tag :
       
           <body onload="initGame()">
       
Head-> add Script tag : define 3 methods  into <script></script> tag :
       
function draw()
function initGame()
function update()
 index.html -> draw function : add more code :
       
 update();

 requestAnimFrame(draw);
      
In js folder, create util.js file : contain some util functions and call util.js in index.htmla
       

            window.requestAnimFrame = (function(){

   return  window.requestAnimationFrame       ||

           window.webkitRequestAnimationFrame ||

           window.mozRequestAnimationFrame    ||

           window.oRequestAnimationFrame      ||

           window.msRequestAnimationFrame     ||

           function( callback ){

             window.setTimeout(callback, 1000 / 60);

           };

 })();

       

 In js folder, create card.js file : description about card object : set name , set value, draw for a card
In js folder, create dealer.js file :init for 52 cards

In index.html  : add more code in draw function
       
        var gameCanvas = document.getElementById("gameCanvas");

        var graphic =  gameCanvas.getContext('2d');

and include 2 file :  card.js and dealer.js to script tag.


To test, i'll add more code to flip card when i click on card

Add flip function to card.js
       

           this.flip=function()

       {

               if(this.status==0)

               { 

                       this.status=1;

               }

               else

               {

                       this.status=0;

               }

       }

       
Call shuffle() function of util.js in card.js to shuffle cards.

shuffle(this.cards);
 Create position and draw cards in card.js

       
for ( var i = 0; i < this.cards.length; i++) {

                     

           t=parseInt(i/15)*4;

            

           // no animation

          

           this.cards[i].x=this.x+t;

           this.cards[i].y=this.y;

           

                     

           }

    

    this.draw = function(graphic)

    {

        for ( var i = 0; i < this.cards.length; i++) 

        {

            

            this.cards[i].draw(graphic);

        }

              

    }
 
 In index.html : Add canvasClicked function to <script> tag of <head> tag to handle event

       

function canvasClicked(e)

{

    var gameCanvas = document.getElementById("gameCanvas");

    var x;

    var y;

    if (e.pageX || e.pageY) { 

      x = e.pageX;

      y = e.pageY;

    }

    else { 

      x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; 

      y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; 

    } 

    x -= gameCanvas.offsetLeft;

    y -= gameCanvas.offsetTop;

    for ( var i = 0; i < dealer.cards.length; i++) {

            
            if((dealer.cards[i].x<x) &&(dealer.cards[i].x+90>x) && (dealer.cards[i].y<y) &&(dealer.cards[i].y+135>y)  )

            {

                dealer.cards[i].flip();

            }

    }

}
       
 
and add more code in initGame function :

 // listerner event click
 var gameCanvas = document.getElementById("gameCanvas");
 gameCanvas.addEventListener("click",canvasClicked,true);
 
Declare and init value for dealer :
 QuercusScriptEngineFactory factory = new QuercusScriptEngineFactory();
 ScriptEngine engine = factory.getScriptEngine();
  engine.put("abc", "def");
   ScriptContext context = engine.getContext();
  try {
  engine.eval("<h1>hello   <?=$abc?>  </h1>");
 } catch (Exception e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }


And draw cards in draw function
dealer.draw(graphic);


Result : Drew cards and when you click to card, card will be flip.
Source code :  https://docs.google.com/open?id=0Bw97UupVaNHuVDVIZ1ZOQ21hQWc

Part 1
Part 3

Create slick effects with CSS3 box-shadow


Create slick effects with CSS3 box-shadow


Drop shadows and inner shadows are some of the effects I learned to apply using Photoshop’s Blending options. But now, since CSS3 “hit the charts”, you don’t need Adobe’s design tool to add a drop shadow or an inner shadow to a box. 


Nowadays, the cool thing is that you create beautiful CSS3 shadows without actually needing Photoshop anymore. 

Browser Support



  • Internet Explorer 9/10

  • Firefox (from 3.5)

  • Safari/Chrome

  • Opera (from 10.5)


Add below Style in Header section :  
<style>
    html, body
    {
        height: 100%;
        margin: 0;
        padding: 0;
    }
 
    body
    {
        background: #b3b4b7;
        text-align: center;
    }
 
    h1
    {
      font-family: 'Allan', serif;
      text-shadow: 0 1px 0 rgba(255,255,255,.5);
      margin: 20px 0;
    }


    /* --------------------------- */
 
    body:before
    {
      content: "";
      position: fixed;
      top: -10px;
      left: 0;
      width: 100%;
      height: 10px;
      z-index: 100;
      -webkit-box-shadow: 0px 0px 10px rgba(0,0,0,.8);
      -moz-box-shadow: 0px 0px 10px rgba(0,0,0,.8);
      box-shadow: 0px 0px 10px rgba(0,0,0,.8);            
    }


    /* --------------------------- */
 
    #box
    {
      position: relative;
      width: 60%;
      background: #ddd;
      -moz-border-radius: 4px;
      border-radius: 4px;
      padding: 2em 1.5em;
      color: rgba(0,0,0, .8);
      text-shadow: 0 1px 0 #fff;
      line-height: 1.5;
      margin: 60px auto;
    }


    #box:before, #box:after
    {
      z-index: -1;
      position: absolute;
      content: "";
      bottom: 15px;
      left: 10px;
      width: 50%;
      top: 80%;
      max-width:300px;
      background: rgba(0, 0, 0, 0.7);
      -webkit-box-shadow: 0 15px 10px #000000(0,0,0, 0.7);
      -moz-box-shadow: 0 15px 10px 
      #000000 (0, 0, 0, 0.7);
      box-shadow: 0 15px 10px 
      #000000 (0, 0, 0, 0.7);
      -webkit-transform: rotate(-3deg); 
      -moz-transform: rotate(-3deg);
      -o-transform: rotate(-3deg);
      -ms-transform: rotate(-3deg);
      transform: rotate(-3deg);
    }
    #box:after
    {
      -webkit-transform: rotate(3deg);
      -moz-transform: rotate(3deg);
      -o-transform: rotate(3deg);
      -ms-transform: rotate(3deg);
      transform: rotate(3deg);
      right: 10px;
      left: auto;
    } 
</style>
 

Add below html in body section :
  

<div id="box">
<h1>Lorem ipsum dolor sit amet</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed sapien elit, pulvinar a fermentum vel,
sagittis nec dolor. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
</div> 

Begining HTML5 game part 1

OK. Let's start .

Do you know HTML ?
Create file game.html with content :
       
 <!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Insert title here</title>

</head>

<body>



</body>

</html> 

Adding some javascript as framework
       
<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Insert title here</title>

<script type="text/javascript">

    function update()

    {

        // Game UPDATE login

    }

    function draw()

    {

        // game DRAW

       

    }

    function setup()

    {

       

        setInterval(draw, 21);

        setInterval(update, 21);

    }

</script>

</head>

<body onload="setup()">

    <canvas id="gameCanvas" width="800"  height="550">



</canvas>

</body>

</html>


You can see a HTML5 Canvas tag . We will create game , and draw all thing on this canvas
function setup  some variables and create game loop .

Now we will addling some object to game . A image may be good for begin .
I will draw this image on canvas :


you can download and reset name for image is "monday.jpg" in same location of html file aaaa
       
function draw()
{

        // game DRAW

        var gameCanvas = document.getElementById("gameCanvas");

        var graphic =  gameCanvas.getContext('2d');

        var monday = new Image(); 
        // you can download and reset name for image is "monday.jpg"

            monday.src="monday.jpg";

             graphic.drawImage(monday,100, 100);

} 
               
 Open browser and you can see this image show on canvas .

OK.  For now we implement simple event mouse event .
       

          function setup()

    {

        var gameCanvas= document.getElementById("gameCanvas");

        gameCanvas.addEventListener("click", canvasClicked,true);

        //setInterval(draw, 21);

        setInterval(update, 21);

        

    }

    function canvasClicked(e)

    {

        

        var gameCanvas = document.getElementById("gameCanvas");

        var graphic =  gameCanvas.getContext('2d');

        var monday = new Image();

        monday.src="monday.jpg";

         graphic.drawImage(monday,e.clientX, e.clientY);

    }     
 

Function draw is not loop (commented //setInterval function call), to you can see when click to canvas , new Image is drawn.

As you see HTML5 not so hard as you think , it very simple .

Result : when you click mouse, you could see  monday.jpg draw :D
Full source
<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Insert title here</title>

<script type="text/javascript">

    function update()

    {

        // Game UPDATE login

    }

    function draw()

    {

        // game DRAW

        var gameCanvas = document.getElementById("gameCanvas");

        var graphic =  gameCanvas.getContext('2d');

        var monday = new Image();

        monday.src="monday.jpg";

         graphic.drawImage(monday,100, 100);

        

    }

    function setup()

    {

        var gameCanvas= document.getElementById("gameCanvas");

        gameCanvas.addEventListener("click", canvasClicked,true);

        //setInterval(draw, 21);

        setInterval(update, 21);

        

    }

    function canvasClicked(e)

    {
        var gameCanvas = document.getElementById("gameCanvas");

        var graphic =  gameCanvas.getContext('2d');

        var monday = new Image();

        monday.src="monday.jpg";

         graphic.drawImage(monday,e.clientX, e.clientY);

        

    }

</script>

</head><body onload="setup()">
    <canvas id="gameCanvas" width="800"  height="550">



</canvas>

</body>

</html>


part 2 is for next post .
Part 3

Using Java UDP broadcast to detect Server IP address on LAN

I develop a game server on LAN.
My game server is TCP based (java socket)
But when the game client starts, it needs to know what is server IP address. How to client detect Server's IP address?
I using UDP broadcast to detect server IP.

Firstly :
In Server I create a UDP server, it broadcast in a schedule :

       
       DatagramSocket ss = new DatagramSocket();
       ss.setBroadcast(true);
       byte[] b = new byte[100];
       DatagramPacket p = new DatagramPacket(b, b.length);
       p.setAddress(InetAddress.getByAddress(new byte[] { (byte) 255,
               (byte) 255, (byte) 255, (byte) 255 }));
       p.setPort(PORT);

This code will send a null package(100 bytes) to 255.255.255.255 , and this package will send all IP on LAN.
Of course, we need a loop to send in a schedule.

       

DatagramSocket ss = new DatagramSocket();
       ss.setBroadcast(true);
       byte[] b = new byte[100];
       DatagramPacket p = new DatagramPacket(b, b.length);
       p.setAddress(InetAddress.getByAddress(new byte[] { (byte) 255,
               (byte) 255, (byte) 255, (byte) 255 }));
       p.setPort(PORT);
                 int i = 0;
       while (true) {
           String s = new Integer(i++).toString();
                             b = s.getBytes();
           p.setData(b);
           ss.send(p);
           try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
       }

Secondly.
When client starts, it will retrieve UDP package sent by a server and of course, it know Server's IP address.

       

 byte[] receiveData = new byte[100];
DatagramSocket clientSocket = new DatagramSocket(1234);
DatagramPacket receivePacket =
        new DatagramPacket(receiveData,
                     receiveData.length);
     clientSocket.receive(receivePacket);
     System.out.println(receivePacket.getAddress());

Finally. I use detected IP to create a socket connection with the game server and everything works great.

[How to] Install resin webserver on centos


Resin is very strong webserver/servlet container  . It really fast and strong ,  it may be keep ~10k  concurrent connection  . This tutorial will help you install Resin as service on Centos

1. Install jdk (best is  jdk7 , skip this step if you already have JDK [5,6,7])

http://download.oracle.com/otn-pub/java/jdk/7u2-b13/jdk-7u2-linux-x64.rpm

    wget http://download.oracle.com/otn-pub/java/jdk/7u2-b13/jdk-7u2-linux-x64.rpm

    rpm -i jdk-7u2-linux-x64.rpm

2.Install resin (current version is 4.0)

    wget http://www.caucho.com/download/resin-4.0.24.tar.gz

    tar xzf resin-4.0.24.tar.gz

    cd resin-4.0.24

    ./configure

    make

    make install

In this step  script configure maybe not work because in .configure :

    tmpname=”/tmp/java$$.out”

    $JAVA_EXE -version 2> $tmpname

    grep “1\.[678]” $tmpname 1> /dev/null
    if test “$?” != “0″; then
    echo “no”
    java_version=`cat $tmpname`
    as_fn_error $? “Java 1.6 required. ${JAVA_EXE} returned: ${java_version}” “$L
    NENO” 5

   This script will check current  java version is  1.6[7,8] or not . But in centos java version is 1.6.0_23 or 1.7.0

To make it work edit  “1\.[678]”  to  grep “1\.[678]\.[0-9]\”

continue make and make install

Check resin service ready work

    service resin restart

Check by open http://yourip:8080

Done .

But some task may be you need :
- config port change to 80 instead of 8080
- config admin username/password
- config virtual host
- config memory/heap






Hello world WebSocketServer with Netty

I've done to write hello world of WebSocketServer (for html5 websocket) with Netty (a network framework  by jboss) . It's really simple to create. You start with 7 step to create WebSocketServer :
  • S1 : Create new project with "HelloNetty" name
  • S2 : Download documentation in : http://netty.io/docs/ and  lib of Netty : http://netty.io/downloads/
  • S3 : Create "lib" folder and paste 2 packages : "netty-3.4.4.Final-sources.jar" and  "netty-3.4.4.Final.jar" to "lib"


  • S4 : Add lib and source preference :


    • S4.1 : Add lib : Click right mouse to HelloWorld ->Build Path -> Configure Build Path Choose "Libraries" tab -> Add JARs -> lib -> "netty-3.4.4.Final-source.jar"
    • S4.2 : Add Source : choose lib package -> Source attachment -> Edit button -> Workspace -> choose source(netty-3.4.4.Final-source.jar) -> Ok button
  • S5 : Create "src" folder" and paste 4 files : "WebSocketServer.java", "WebSocketServerHandler.java", "WebSocketServerIndexPage.java", "WebSocketServerPipelineFactory.java" in there
  • S6 : In Src, have 2 files that you need to care to edit : "WebSocketServerHandler.java" and "WebSocketServerIndexPage.java"


    • S6.1 : In "WebSocketServerHandler.java" : we care to "handleWebSocketFrame()" method. This's method that u can do. Cause it's simple helloworld project, so, u can edit directly in this. But if your project has big, you should write others methods to clear seeing and easy manager, then, call those methods in this method.
    • S6.2 : In "WebSocketServerIndexPage.java" : it's client. But to easy, you can create new html in others folder to edit. Example, i create "test.html" file to test.
  • S7 : Run and Test Server, Client
    • S7.1 : Run Server : go to "WebSocketServer.java" file, and run.
    • S7.2 : Run Client : go to "test.html" file, copy location of "test" file, and paste to browser to run
Source code in herehttp://www.mediafire.com/?c434vlhd46cdc2y
Hope to helping ^^

Cake Bake - Cake Console


Some quick tip to use cake bake
In normal, you will type : 
$cake bake
After that, you will answer each question of cake bake as what do you generate (D/M/V/C/P/Q ...) ... how to gen.
We have a quickly statement to do that : 
  1. Want to direct generate models
    $cake bake model
    
  2. Want to direct generate controller
    $cake bake controller
    
  3. Want to direct generate view
    $cake bake view
    
  4. Want to direct generate models with name
    $cake bake model model_name
    
  5. Want to direct generate controller with name
    $cake bake controller controller_name
    
  6. Want to direct generate view with view name
    $cake bake view controller_name view_name
    
  7. Want to direct generate view with template name
    view name and template name in : /cake/console/libs/templates/views and can add or override in : /app/vendors/shells/templates/views

     $cake bake view controller_name template_name view_name
    
  8. Want to generate controller like result of scaffold
    $cake bake controller Users scaffold
    
  9. Want to generate controller add more actions for admin
    $cake bake controller Users scaffold admin
    
  10. Want to gen controller only have actions for admin
    $cake bake controller Users null admin
    
  11. Gen help
    $cake bake model help
    
  12. List of model
    $cake bake all
    
  13. model -> controller -> views
    $cake bake all Model_name