Jiangyue Zhu

Impossible is Nothing


Leave a comment

Greedy Snake Game–Using HTML5 Canvas and JavaScript

A couple weeks ago, I used HTML5 canvas and JavaScript, jQuery to implement a greedy snake game. The logic is pretty simple, compared to some complex animation game. And the all of the implementation is based on HTML5+JavaScript+CSS, without any usage of Flash.


snake

The UI is simple but the functionality is working fine, what the users need to do is to use keyboards(up-arrow, right-arrow, down-arrow, left-arrow) to control directions of the snake. The score will be recorded once the snake hit the targe and the snake’s size will be auto-increment. The game will end if the snake hit itself or the edge.

The source code can be found on GitHub: https://github.com/zhujy8833/Snake

There is another version which I put in jsFiddle: http://jsfiddle.net/zhujy_8833/bRMjV/

Click Here to view the live demo.

Advertisements


Leave a comment

Javascript OOP

It is true that javascript is very different from other programming languages, so maybe that’s why lots of people even professional programmers don’t think javascript is a good language and don’t understand it well. A year ago, I had the same feeling, but after I started my work of front-end web development and read the book “Javascript: The good parts”, I have to say I am falling in love with this beautiful and powerful language. One of the most beautiful part of javascript is its prototype property, which makes the inheritance easily.

First of all, we must know that every object in javascript has an internal prototype property(in order to distinguish it with function’s external prototype property, I would use [prototype] to denote internal ones). There are three ways that you can use to create an object:

1. var obj = {};
2. var obj = new Object;
3. var obj = Object.create(null);

All of these three ways are equivalent in creating an empty object. Once the object was created, it will have that internal [prototype] property, note that [prtotype] is still an object so it also has internal prototype prototype property of which value is the object that is inherited from Object’s external prototype. How can we access to the internal [prototype]? A standard way is to use Object.getPrototypeof(), the other way that you can use is the __proto__ property, but I think it is only built in Chrome.

Function is also a kind of object in javascript, but function has an unique property which is the external prototype.  This external prototype property is the important key for us to implement OOP in javascript. The normal way of implementation of OOP is like this:

function Person(){
    this.name = "Tom";
    this.age = 23;
}
Person.prototype.run = function(){
    console.log(this.name+" is running! ");
}
var p = new Person();   //this will create an instance of Person
p.run();

Now, let me explain the above codes:

You may ask what happened when we use the new keyword. Actually, when new keyword is used, three things happened:

1. An empty object is created, just like {}, very simple.
2. It sets the function’s prototype property’s value to the instance object’s internal [prototype], so here, we can say
      p.__proto__ = Person.prototype
3. The function’s constructor will be executed, in which the constructor is the constructor in that function’s external prototype. Then the instance will replace this in the constructor. In this example, p will have property name and age.

Oh, here is another thing I need to mention. When access to a property of an object, it will firstly detect whether the object has the property directly, if not then goes to its [prototype] ,if still not, goes to [prototype]’s [prototype]…until reaching the root and return found or not found. That’s another important concept in javascript, called prototype chain.  In the above example, it is easy to find the property ‘name’ and ‘age’ as they are directly attached to that object. But if we want to check if the object has ‘run’ property, since it is not attached to that object directly, we need to go deeper to p.__proto__ which is inherited from Person.prototype(Remind!), now we find ‘run’.

The problem here is that why we do not put ‘run’ in Person’s constructor directly? Why we attach it to prototype property of Person?

OK. if we put ‘run’ to the constructor:

function Person(){
    this.name = "Tom";
    this.age = 23;
    this.run = function(){
      console.log(this.name+" is running! ");
    }
}

It seems fine, right? Yes, it will produce the same result, but the problem is that this approach is not efficient. What I mean is that function ‘run’ will be redefined everytime when a new object is created, it does not share with other objects. But if we use prototype.run, then every object instance which inherits from Person will automatically have that function without redefinition.

Here are two links which are very good articles and a good answer from stackoveflow about ‘new’ keyword:

Two articles:

1. Learning JavaScript Design Patterns

–this is my favourite article, very good explanation about Javascript OOP and also good module pattern, helping us write good codes.

2. Object Oriented Programming in Javascript

–Good explanation about OOP, prototype, and how prototype chain works.

One good answer from Stackoverflow:

http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript/3658673#3658673

–I believe that is one of the best answer I’ve ever seen in Stackoverflow, precise and nice example


Leave a comment

Survivor Game–PHP Programming

I did a PHP program as a coding test for one technical interview. The test was to use PHP to implement a function to play the ‘Survivor’ game. The game rule is like this:

You are in a room with a circle of 100 chairs.  The chairs are numbered sequentially from 1 to 100.At some point in time, the person in chair #1 will be asked to leave.  The person in chair #2 will be skipped, and the person in chair #3 will be asked to leave. This pattern of skipping one person and asking the next to leave will keep going around the circle until there is one person left… the survivor.

 

So what the function needs to do is to find out the survivor (which chair the survivor is sitting in).

My codes are like this:

<?php
/* Function remove consists of two args. One is the integer array, the other is
 * the token to control removal: 1--remove 0--not remove
 *
 * When there is only one element left in the array, then the survivor found
 */
function survivor($array,$rmToken){

 /**
 * if only one left, return it. The survivor found!**/
 if(count($array) == 1){

 return $array;
 }
foreach($array as $key => $element){
 /**
 * token equals to 1
 * Remove current element from array
 * set token to 0, continue loop
 */
 if($rmToken){ 

 unset($array[$key]); 

 $rmToken = 0; 

 }

 /**
 * token equals to 0
 * skip this element
 * set token to 1, continue loop **/
 else { 

 $rmToken = 1; 

 }

 }// end foreach

 return survivor($array,$rmToken); //recursive 

}

// create an array containing a range of elements, from 1 to 100.
 $arr = range(1,100);
$result = survivor($arr,1); //call survivor function, return result
echo "The survivor is sitting on #".array_pop($result);
 // print_r($result);
?>


Leave a comment

Customize jQuery Plugin–Back to Top widget

How to make a more friendly widget which can enhance the user experience on the website? Imagine this scenario: when you browse a web page with long height and you almost reach the bottom of this page, how would you feel if you have to go back to the top right now? Is it too much boring to use the scroll bar which may make your finger exhausted? You may need a small widget which can make this even happen just by one click. Actually, when I browsed some websites, I noticed that some of them implemented this kind of features which I think are very user-friendly. In this blog, I want to tell how I implemented this  by using defining a customized jquery plugin.

For someone who may not be familiar with jquery plugin, please take this as reference.

Firstly, I need to write some codes for this widget using div with an id “backToTop” assigned. And I would use a small icon –up arrow for this widget. 

The code samples for this part is pretty simple:

<div id="backToTop">
   <img src="img/up.png" alt="up" width="60" height="80" />
 </div>

Now, the task would be switched to the style sheet. What I want is to move this widget to the right-bottom corner and always be there during scrolling through the page. In this way, it will not affect users’ reading behaviors. So the style sheet for this part looks like this:

div#backToTop{
	position:fixed;
	right:0em;
	bottom:0em;
	cursor:pointer;
	display:none;
	}

Some additional parts should be noted. As we prefer not to see this widget at the first time (cause we only need it when we leave the top position), we set the display attribute to none. Also, we set cursor to pointer in order to tell users they can click on it.

Then, it comes to the core part, the jquery plugin. Firstly, let’s create a new js file, naming it ‘plugin.js’. Inside it, let’s add these codes:

// JavaScript Document
(function($){

 $.fn.backToTop=function(options){
 var settings = $.extend({
 "position":200
 },options);

 var this_= this;
 var position = settings["position"];

 $(document).scroll(function(){

 var currentPos=$(window).scrollTop();

 if(currentPos >= position){
 this_.show();
 }
 else {
 this_.hide();
 }

 });

 this_.click(function(){

 $(window).scrollTop(0);

 });

 };

 })(jQuery);

Simply put, what I am doing is to define a function called ‘backToTop’ with an optional parameter called position. This position attribute is used to define when the widget should appear. I set the default value to 200. Besides, I added a scroll event to the document object and retrieve the current top offset. Using a if-else statement to control the visibility of the widget, the widget would not show up until the current top offset goes beyond the position we set. Then, don’t forget to set a click event on this widget, in the event, define a function to let set the window object scroll to the top by using scrollTop(0). And if we scroll back to top in which the current offset is smaller than the position that we set, the widget would disappear.

After we accomplished this javascript file, we need to call this function in our page. Generally, we use $(“#backToTop”).backToTop([optional parameters]) to invoke the function.

$("#backToTop").backToTop();

Now, we are set! Please visit my live project.


Leave a comment

HTML5 Box Model

As we know, the contents enclosed by <div></div> would be considered as block-level container as default. If there are some contents that we want them to be in a menu, it needs some more work to implement it.

Let’s see an much easier and more elegant way to do this by using box-model.

Now, I have a div which has an id “menu”. It would be used to display a menu with three elements:

<div id="menu">
 <div id="home">Home</div>
 <div id="contact">Contact</div>
 <div id="about">About</div>
</div>

If we did not change anything, the sub-div would be aligned vertically. What we want to do now is to align them horizontally, just like what we see in some websites.

It is easy to do this by using box-model. The codes of this part are like this:

<style type="text/css"> 
#menu{ 
 display:box;
 box-orient:horizontal;

 display:-webkit-box;
 -webkit-box-orient:horizontal;

 display:-moz-box;
 -moz-box-orient:horizontal
}
</style>

Actually, we need to set the display attribute of menu div section to box. In the codes, there are two additional attributes which has prefixes: -webkit and -moz which aims to solve the cross-browser compatibility. -webkit is to support several browsers such as Opera, Chrome, and Safari, while -moz supports Mozilla Firefox. We note that the box orient attribute is also being set to horizontal.

Are we set now? Not yet. Why? The reason is that the sub-div elements will not inflate into the whole menu div, even though all these three sub-div elements are aligned horizontally. For example, if we set the width of the menu div to 500px, then the current result would be something like this:

That’s definitely not what we expect. Now, the next step is to add some codes for controlling those menu sub-div elements. The codes are like this:

#menu > div{
 text-align:center;
 border:#999999 solid;
 border-radius: 5px;
 box-flex:1;
 -webkit-box-flex:1;
 -moz-box-flex:1;
}

The important part is the attribute box-flex. Simply put, if we set the box-flex value of all the sub-div elements to 1, it means that those three elements would occupy the whole menu div with equal width. That’s what we want! So, after adding these codes, the result looks exactly what we expect:

Here is a live result, click here. It has more than what I introduced above because it has some additional attributes which can allow the div stretch when the mouse is hover on it. Also, it has some features such as the shadow or border radius.


					
		
	


Leave a comment

Configure Virtual Hosts–Use XAMPP

By default, I can access to my localhost in http://localhost:8080/(my port sets to 8080) and the projects are deployed under htdocs folder.

But, how to change that? I read some posts online and find a way to do it for XAMPP.

Firstly, copy the following lines to C:\xampp\apache\conf\extra\httpd-vhosts:

<VirtualHost *:8080>
 DocumentRoot "C:/xampp/htdocs/zend/public"
 ServerName zend
 SetEnv APPLICATION_ENV development
<Directory "C:/xampp/htdocs/zend/public">
 Options Indexes MultiViews FollowSymLinks
 AllowOverride All
 Order allow,deny
 Allow from all
 </Directory>
</VirtualHost>

The port number is 8080. And the root directory is : “C:/xampp/htdocs/zend/public, which is my zend framework project application folder.

Also, I customize my host name as ‘zend’. So in this way. I can use http://zend:8080/ instead of http://localhost:8080/

But before open the browser, there is still one more thing to do:

Go to ‘C:\Windows\System32\drivers\etc’, and find open ‘hosts’.

Here, I edit another host by using the following contents:

127.0.0.1       localhost zend

After this configuration, don’t forget to restart the apache server.

Then it is the time to open the browser to try the new url:  http://zend:8080

and it will access the public/ directory.


1 Comment

Learn How to set up Zend Framework

After considering several days, I planned to learn Zend Framework. Actually, I had generated this idea since I graduate in last December. But I was confused about the process of setup. It seems that Zend Framework is powerful, but at the same time, you need to tolerate the complicate installation procedure.

Recently, I came across some tutorials on the web, and I finally, finally got it set up. I tried it on NetBeans 7.0 and Zend Studio.

It would be much easier when you use Zend Studio which would automatically help you set up the architecture if you choose ‘File’->’New’->’Zend Framework Project’.

The project structure looks like this

The files under public/ directory are the web pages for this application. Also, it should be noted that the project contains ‘models’,’views’, and ‘controllers’ folders.

Previously, when I tried this,  I got error when I launched the browser with url access to index.php under application/public/ directory. I found out that it was the reason that the project missed the Zend library, which can be downloaded here. I downloaded the zip file and extract the contents under library/ directory to the project library/ directory. Then it works!

The index page would like this:

I accessed to this result by this url: http://localhost:8080/zend/public/, where zend is my project name.

Also, the url:  http://localhost:8080/zend/public/index would have the same result because index under public/ directory is the a default action within a controller called Index.

For NetBeans IDE, the process is a little bit complicated. It is easy to find the way to create a new PHP application. After setting some necessary parameters such as project name, php version…, you have the option to select one framework. But it would invoke a alert which says that a zend script is required. Use the ‘Browse’ option and go to the folder of zend framework which was downloaded before and select ‘zf.bat’ and at the same time, you need to make sure that the Zend library is in your ‘\php\PEAR’ directory. In my case, I copy the ‘library/’ contents to ‘C:\xampp\php\PEAR’

After this, don’t forget to click the ‘Register Provider’ button just below the zend script line.

And, All the stuffs are set!!

The project structure is the same as Zend Studio one. And also, the result of launching the project is also the same.

Now, I would spend some time to study Zend Framework MVC. I want to share a good tutorial which is in PDF format. I t can be downloaded in http://akrabat.com/wp-content/uploads/Getting-Started-with-Zend-Framework.pdf

Also, the author provides some resources such as the sample codes for this tutorial: http://akrabat.com/zend-framework-tutorial/