Posts Tagged ‘tutorials’

Learn Git in 30 Minutes

Thursday, June 2nd, 2016

learn-git-in-30-minutes

Git has exploded in popularity in recent years. The verison control system is used by huge open source projects like Linux with thousands of contributors, teams of various sizes, solo developers and even students.

Beginners are often terrified by all the cryptic commands and arguments that git requires. But you don’t need to know all of that to get started. You can begin by mastering a handful of the most often used ones, and then slowly build from there. And this is exactly what we will teach you today. Let’s begin!


basics

The basics

Git is a collection of command line utilities that track and record changes in files (most often source code, but you can track anything you wish). With it you can restore old versions of your project, compare, analyze, merge changes and more. This process is referred to as version control. There are a number of version control systems that do this job. You may have heard some of them – SVN, Marcurial, Perforce, CVS, Bitkeeper and more.

Git is decentralized, which means that it doesn’t depend on a central server to keep old versions of your files. Instead it works fully locally by storing this data as a folder on your hard drive, which we call a repository. However you can store a copy of your repository online, which makes it easy for multiple people to collaborate and work on the same code. This is what websites like GitHub and BitBucket are used for.

1. Installing Git

Installing Git on your machine is straightforward:

If you are an absolute beginner, then a graphical git client is a must. We recommend GitHub Desktop and Sourcetree, but there are many other good and free ones online. Getting to know the basic git commands is still important even if you use a GUI app, so for the remaining of this lesson, this will be our only focus.

2. Configuring Git

Now that we’ve installed git on our computer, we will need to add some quick configurations. There are a lot of options that can be fiddled with, but we are going to set up the most important ones: our username and email. Open a terminal and run these commands:

$ git config --global user.name "My Name"
$ git config --global user.email myEmail@example.com

Every action we do in Git will now have a stamp with our name and address on it. This way users always know who did what and everything is way more organized.

3. Creating a new repository – git init

As we mentioned earlier, git stores its files and history directly as a folder in your project. To set up a new repository, we need to open a terminal, navigate to our project directory and run git init. This will enable Git for this particular folder and create a hidden .git directory where the repository history and configuration will be stored.

Create a folder on your Desktop called git_exercise, open a new terminal and enter the following:

$ cd Desktop/git_exercise/
$ git init

The command line should respond with something along the lines of:

Initialized empty Git repository in /home/user/Desktop/git_exercise/.git/

This means that our repo has been successfully created but is still empty. Now create a simple text file called hello.txt and save it in the git_exercise folder.

4. Checking the status – git status

Git status is another must-know command that returns information about the current state of the repository: is everything up to date, what’s new, what’s changed, and so on. Running git status in our newly created repo should return the following:

$ git status

On branch master

Initial commit

Untracked files:
  (use "git add ..." to include in what will be committed)

	hello.txt

The returned message states that hello.txt is untracked. This means that the file is new and Git doesn’t know yet if it should keep track of the changes happening to that file or just ignore it. To acknowledge the new file, we need to stage it.

5. Staging – git add

Git has the concept of a “staging area”. You can think of this like a blank canvas, which holds the changes which you would like to commit. It starts out empty, but you can add files to it (or even single lines and parts of files) with the git add command, and finally commit everything (create a snapshot) with git commit.

In our case we have only one file so let’s add that:

$ git add hello.txt

If we want to add everything in the directory, we can use:

$ git add -A

Checking the status again should return a different response from before.

$ git status

On branch master

Initial commit

Changes to be committed:
  (use "git rm --cached ..." to unstage)

	new file:   hello.txt

Our file is ready to be commited. The status message also tells us what has changed about the files in the staging area – in this case its new file, but it can be modified or deleted, depending on what has happened to a file since the last git add.

6. Commiting – git commit

A commit represents the state of our repository at a given point in time. It’s like a snapshot, which we can go back to and see how thing were when we took it.

To create a new commit we need to have at least one change added to the staging area (we just did that with git add) and run the following:

$ git commit -m "Initial commit."

This will create a new commit with all the changes from the staging area (adding hello.txt). The -m "Initial commmit" part is a custom user-written description that summarizes the changes done in that commit. It is considered a good practice to commit often and always write meaningful commit messages.


remotes

Remote repositories

Right now our commit is local – it exist only in the .git folder. Although a local repository is useful by itself, in most cases we will want to share our work and deploy it to a server or a repository hosting service.

1. Connecting to a remote repository – git remote add

In order to upload something to a remote repo, we first have to establish a connection with it. For the sake of this tutorial our repository’s address will be https://github.com/tutorialzine/awesome-project. We advise you to go ahead and create your own empty repository at GitHub, BitBucket or any other service. The registration and setup may take a while, but all services offer good step-by-step guides to help you.

To link our local repository with the one on GitHub, we execute the following line in the terminal:

# This is only an example. Replace the URI with your own repository address.
$ git remote add origin https://github.com/tutorialzine/awesome-project.git

A project may have many remote repositories at the same time. To be able to tell them apart we give them different names. Traditionally the main remote repository in git is called origin.

2. Uploading to a server – git push

Now it’s time to transfer our local commits to the server. This process is called a push, and is done every time we want to update the remote repository.

The Git command to do this is git push and takes two parameters – the name of the remote repo (we called ours origin) and the branch to push to (master is the default branch for every repo).

$ git push origin master

Counting objects: 3, done.
Writing objects: 100% (3/3), 212 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To https://github.com/tutorialzine/awesome-project.git
 * [new branch]      master -> master

Depending on the service you’re using, you will need to authenticate yourself for the push to go through. If everything was done correctly, when you go in your web browser to the remote repository created earlier, hello.txt should be available there.

3. Cloning a repository – git clone

At this point, people can see and browse through your remote repository on Github. They can download it locally and have a fully working copy of your project with the git clone command:

$ git clone https://github.com/tutorialzine/awesome-project.git

A new local respository is automatically created, with the github version configured as a remote.

4. Getting changes from a server – git pull

If you make updates to your repository, people can download your changes with a single command – pull:

$ git pull origin master

From https://github.com/tutorialzine/awesome-project
 * branch            master     -> FETCH_HEAD
Already up-to-date.

Since nobody else has commited since we cloned, there weren’t any changes to download.


Branches

When developing a new feature, it is considered a good practice to work on a copy of the original project, called a branch. Branches have their own history and isolate their changes from one another, until you decide to merge them back together. This is done for a couple of reasons:

1. Creating new branches – git branch

The default branch of every repository is called master. To create additional branches use the git branch <name> command:

$ git branch amazing_new_feature

This just creates the new branch, which at this point is exactly the same as our master.

2. Switching branches – git checkout

Now, when we run git branch,  we will see there are two options available:

$ git branch
  amazing_new_feature
* master

Master is the current branch and is marked with an asterisk. However, we want to work on our new amazing features, so we need to switch to the other branch. This is done with the git checkout command, expecting one parameter – the branch to switch to.

$ git checkout amazing_new_feature

3. Merging branches – git merge

Our “amazing new feature” is going to be just another text file called feature.txt. We will create it, add it, and commit it.

$ git add feature.txt
$ git commit -m "New feature complete."

The new feature is complete, we can go back to the master branch.

$ git checkout master

Now, if we open our project in the file browser, we’ll notice that feature.txt has disappeared. That’s because we are back in the master branch, and here feature.txt was never created. To bring it in, we need to git merge the two branches together, applying the changes done in amazing_new_feature to the main version of the project.

git merge amazing_new_feature

The master branch is now up to date. The awesome_new_feature branch is no longer needed and can be removed.

git branch -d awesome_new_feature

 advanced

Advanced

In the last section of this tutorial, we are going to take a look at some more advanced techniques that are very likely to come in handy.

1. Checking difference between commits

Every commit has it’s unique id in the form of a string of numbers and symbols. To see a list of all commits and their ids we can use git log:

$ git log

commit ba25c0ff30e1b2f0259157b42b9f8f5d174d80d7
Author: Tutorialzine
Date:   Mon May 30 17:15:28 2016 +0300

    New feature complete

commit b10cc1238e355c02a044ef9f9860811ff605c9b4
Author: Tutorialzine
Date:   Mon May 30 16:30:04 2016 +0300

    Added content to hello.txt

commit 09bd8cc171d7084e78e4d118a2346b7487dca059
Author: Tutorialzine
Date:   Sat May 28 17:52:14 2016 +0300

    Initial commit

As you can see the ids are really long, but when working with them it’s not necessary to copy the whole thing – the first several symbols are usually enough.
To see what was new in a commit we can run git show [commit]:

$ git show b10cc123

commit b10cc1238e355c02a044ef9f9860811ff605c9b4
Author: Tutorialzine
Date:   Mon May 30 16:30:04 2016 +0300

    Added content to hello.txt

diff --git a/hello.txt b/hello.txt
index e69de29..b546a21 100644
--- a/hello.txt
+++ b/hello.txt
@@ -0,0 +1 @@
+Nice weather today, isn't it?

To see the difference between any two commits we can use git diff with the [commit-from]..[commit-to] syntax:

$ git diff 09bd8cc..ba25c0ff

diff --git a/feature.txt b/feature.txt
new file mode 100644
index 0000000..e69de29
diff --git a/hello.txt b/hello.txt
index e69de29..b546a21 100644
--- a/hello.txt
+++ b/hello.txt
@@ -0,0 +1 @@
+Nice weather today, isn't it?

We’ve compared the first commit to the last one, so we see all the changes that have ever been made.

2. Fixing a commit

If you notice that you’ve made a typo in your commit message, or you’ve forgotten to add a file and you see right after you commit, you can easily fix this with git commit --amend.  This will add everything from the last commit back to the staging area, and attempt to make a new commit. This gives you a chance to fix your commit message or add more files to the staging area.

For more complex fixes that aren’t in the last commit (or if you’ve pushed your changes already), you’ve got to use git revert. This will take all the changes that a commit has introduced, reverse them, and create a new commit that is the exact opposite.

The newest commit can be accessed by the HEAD alias.

$ git revert HEAD

For other commits it’s best to use an id.

$ git revert b10cc123

When reverting older commits, keep in mind that merge conflicts are very likely to appear. This happens when a file has been altered by another more recent commit, and now Git cannot find the right lines to revert, since they aren’t there anymore.

3. Resolving Merge Conflicts

Apart from the scenario depicted in the previous point, conflicts regularly appear when merging branches or pulling someone else’s work. Sometimes conflicts are handled automatically by git, but other times the person dealing with them has to decide (and usually handpick) what code stays and what is removed.

Let’s look at an example where we’re trying to merge two branches called john_branch and tim_branch. Both John and Tim are writing in the same file a function that displays all the elements in an array.

John is using a for loop:

// Use a for loop to console.log contents.
for(var i=0; i<arr.length; i++) {
    console.log(arr[i]);
}

Tim prefers forEach:

// Use forEach to console.log contents.
arr.forEach(function(item) {
    console.log(item);
});

They both commit their code on their respective branch. Now if they try to merge the two branches they will see the following error message:

$ git merge tim_branch 

Auto-merging print_array.js
CONFLICT (content): Merge conflict in print_array.js
Automatic merge failed; fix conflicts and then commit the result.

Git wasn’t able to merge the branches automatically, so now it’s up to the devs to manually resolve the conflict. If they open the file where the conflict resides, they’ll see that Git has inserted a marker on the conflicting lines.

<<<<<<< HEAD
// Use a for loop to console.log contents.
for(var i=0; i<arr.length; i++) {
    console.log(arr[i]);
}
=======
// Use forEach to console.log contents.
arr.forEach(function(item) {
    console.log(item);
});
>>>>>>> Tim's commit.

Above the ===== we have the current HEAD commit, and below the conflicting one. This way we can clearly see the differences, and decide which is the better version, or write a new one all together. In this situation we go for the latter and rewrite the whole thing, removing the markers to let Git know we’re done.

// Not using for loop or forEach.
// Use Array.toString() to console.log contents.
console.log(arr.toString());

When everything is set, a merge commit has to be done to finish the process.

$ git add -A
$ git commit -m "Array printing conflict resolved."

As you can see this process is quite tiresome and can get extremely hard to deal with in large projects. Most developers prefer to resolve conflicts with the help of a GUI client, which makes things much easier.

4. Setting up .gitignore

In most projects there are files or entire folders that we don’t want to ever commit. We can make sure that they aren’t accidentally included in our git add -A by creating a .gitignore file:

  1. Manually create a text file called .gitignore and save it in your project’s directory.
  2. Inside, list the names of files/directories to be ignored, each on a new line.
  3. The .gitignore itself has to be added, committed and pushed, as it is just like any other file in the project.

Good examples for files to be ignored are:

A .gitignore banning all of the above will look like this:

*.log
build/
node_modules/
.idea/
my_notes.txt

The slash at the end of some of the lines signals that this is a folder and we are ignoring everything inside it recursively. The asterisk serves it’s usual function as a wild card.


Conclusion

This ends our tutorial on git! We tried our best to bring you only the most important information you need, presented as short and concise as possible.

Git is quite complex and has a lot more features and tricks to offer. If you wish to find out more, here are some learning resources we recommend:

Tags: , , , ,
Posted in PHP Tutorials | Comments Off on Learn Git in 30 Minutes

5 Practical Examples For Learning Vue.js

Tuesday, March 15th, 2016

vue1

We’ve already covered Angular.js and React in previous articles but there is a new frontend library that we think is worth your time. It’s called Vue.js and it has gathered a large community of enthusiastic developers.

The philosophy behind Vue.js is to provide the simplest possible API for creating real-time, two-way data binding between the view (HTML) and the model (a JavaScript object). As you will see in the following examples, the library holds true to that idea and working with it is effortless and enjoyable, without compromising on any functionality.

Getting Started

The easiest way to install Vue.js is to simply include it with a <script> tag at the end of your HTML’s body. The entire library is located in a single JavaScript file which you can download from the official website or import directly via CDN:

<script src="http://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js"></script>

If you want to use the library in a Node.js project, vue is available as an npm module. There is also an official CLI, which allows users to quickly setup their whole project based on premade template builds.

Below are five editors containing example apps we’ve built for you. The code has lots of comments and is separated in tabs for each file, making it really easy to follow. The editors have Vue.js built-in so don’t be afraid to experiment. Also, you can download an archive containing all the examples from the Download button near the top of this article.

1. Navigation Menu

To kick things off we’re going to build a simple navigation bar. There are a few basic components almost every Vue.js app need to have. They are:

The idea behind these fancy words is that the model and the view will always stay in sync. Changing the model will instantly update the view, and vice versa. In our first example this is shown with the active variable, representing which menu item is currently selected.

(Play with our code editor on Tutorialzine.com)

As you can see working with the library is pretty straightforward. Vue.js does a lot of the work for us and provides familiar, easy to remember syntax:

2. Inline Editor

In the previous example our model had only a couple of predefined values.  If we want to give the users the ability to set any data, we can do two-way binding and link together an input field with a model property.  When text is entered, it is automatically saved in the text_content model, which then causes the view to update.

(Play with our code editor on Tutorialzine.com)

Another thing to note in the above code is the v-if attribute . It show or hides a whole element depending on the truthfulness of a variable. You can read more about it here.

3. Order Form

This example illustrates multiple services and their total cost. Since our services are stored in an array, we can take advantage of the v-for directive to loop through all of the entries and display them. If a new element is added to the array or any of the old ones is changed, Vue.js will automatically update and show the new data.

(Play with our code editor on Tutorialzine.com)

To display the prices in a correct format we use one of the available filters that come built-in with Vue.js. They allow us to lazily modify the model data – in this case the currency filter is perfect, as it adds a dollar sign and proper number decimals. Just like in Angular filters are applied using the | syntax – {{ some_data | filter }}.

4. Instant Search

Here we will create an app, that exhibits some of the articles on our website. The app will also have a search field allowing us to filter which articles are displayed.  There is a filterBy filter available, but it doesn’t do exactly what we need it to, so instead we will be creating our own custom filter.

(Play with our code editor on Tutorialzine.com)

The input field is bind to the searchString model. When text is entered the model is instantly updated and passed on to the searchFor filter. This way we can create a real-time search without having to worry about rendering or setting up event listeners – Vue.js handles all that!

5. Switchable Grid

In our last example we will demonstrate a common scenario where a page has different layout modes. Just like in the previous app we will be showing a list of articles from tutorialzine.com stored in an array.

By pressing one of the buttons in the top bar you can switch between a grid layout containing large images, and a list layout with smaller images and text.

(Play with our code editor on Tutorialzine.com)

Conclusion

There is a lot more to Vue.js than what we’ve showcased in these examples. The library also offers animations, custom components and all sorts of other features. We recommend you check out the excellent official documentation which is full of information and helpful snippets.

Having troubles deciding whether Vue.js is the right library for your project? The following links will be of great help to you:

Thanks for reading!

Tags: , , , ,
Posted in PHP Tutorials | Comments Off on 5 Practical Examples For Learning Vue.js

Quick Tip: The Easiest Way To Make Responsive Headers

Thursday, February 4th, 2016

quick-tip-responsive-headers

Making pretty, responsive, headers is always a tricky process. Until now you needed to use floats or other complicated tricks and you even had to manually adjust pixel values. But not any more!

The technique we are about to show you relies on the powerful flexbox layout mode to do all the dirty work for you. It uses just a handful of CSS properties to create a header that is properly aligned and looks good on all screen sizes, while leaving the code cleaner and less hacky.

The Technique

In our demonstrative example we’ve built a header, which is separated in three sections with typical header content nested within them:

Below you can check out a simplified version of the code.

In the first tab is the HTML where we group the sections in separate div tags. This makes it easier for CSS rules to be applied and generally produces a more organised code.

In the other tab is the CSS, which is just a couple of lines, does the entire job of finding the right places for the each of the sections.

Click the Run button to open up a live demo. You can test the responsiveness by resizing the frame:

<header>
	<div class="header-left">CoolLogo</div>
	<div class="header-center">
		<ul>
			<li><a href="#">Our products</a></li>
			<li><a href="#">Pricing</a></li>
			<li><a href="#">Blog</a></li>
		</ul>
	</div>
	<div class="header-right"><button>Buy now</button></div>
</header>
header{
	/* Enable flex mode. */
	display: flex; 
	
	/* Spread out the elements inside the header. */
	justify-content: space-between;

	/* Align items vertically in the center. */
	align-items: center;
}
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Easiest Way To Make Responsive Headers</title>
<link href='https://fonts.googleapis.com/css?family=Fugaz+One' rel='stylesheet' type='text/css'>

<style>
*{
	margin: 0;
	padding: 0;
	box-sizing: border-box;
}

body{
	font: normal 16px sans-serif;
	padding: 0 10%;
	background: #eee;
}

body .container{
	max-width:1200px;
	margin:0 auto;
}

/*	Header	*/

header{
	/* Enable flex mode. */
	display: flex; 
	/* Spread out the elements inside the header. */
	justify-content: space-between;
	/* Align items vertically in the center. */
	align-items: center;

	padding: 40px 100px;
	color: #fff;
	background-color: #488EAD;
}

.header-left{
	font: normal 28px 'Fugaz One', cursive;
}

.header-left span{
	color: #EAD314;
}

.header-center ul{
	list-style: none;
}

.header-center ul li{
	display: inline-block;
	margin: 0 15px;
}

.header-center ul li a{
	text-decoration: none;
	color: #fff;
	cursor: pointer;
	font-weight: bold;
}

.header-right button{
    color: #fff;
    cursor: pointer;
    font-weight: 800;
    text-transform: uppercase;
    padding: 12px 30px;
    border: 2px solid #FFFFFF;
    border-radius: 4px;
    background-color: transparent;
}

.header-right button:hover {
    background-color: rgba(255,255,255,0.1);
}

/*	Main content	*/

.main-content{
	padding: 60px 100px;
	background-color: #fff;
    line-height: 1.5;
    color: #444;
}

.main-content h2{
	margin-bottom: 38px;
}

.main-content p{
	margin: 30px 0;
}


.main-content .placeholder{
	margin: 40px 0;
	height:380px;
	background-color: #e3e3e3;
}


/*	Media queries	*/

@media (max-width: 1200px){
	header{
		padding: 40px 60px;
	}

	.main-content{
		padding: 100px 60px;
	}

	body {
	    padding: 0 5%;
	}
}

@media (max-width: 1000px){
	header{
		/* Reverse the axis of the header, making it vertical. */
		flex-direction: column;
		/* Align items to the begining (the left) of the header. */
		align-items: flex-start;
	}

	header > div{
		margin: 12px 0;
	}

	.header-center ul li{
		margin: 0 15px 0 0;
	}

}

@media (max-width: 600px){
	body {
	    padding: 0 10px;
	}

	.header-left{
		margin-top:0;
	}

	header {
	    padding: 30px;
	}

	.main-content{
		padding:30px;
	}
}


</style>
</head>
<body>

<div class="container">
	
	<header>
		<div class="header-left"><span>Cool</span>Logo</div>
		<div class="header-center">
			<ul>
				<li><a href="#">Our products</a></li>
				<li><a href="#">Pricing</a></li>
				<li><a href="#">Blog</a></li>
			</ul>
		</div>
		<div class="header-right"><button>Buy now</button></div>
	</header>

	<section class="main-content">
		<h2>Header with three justify aligned sections</h2>
		<p>Using the power of flexbox, the logo, links, and button of our header stay in their designated places, no matter the screen size. The <strong style="white-space: nowrap;">justify-content</strong> property offers a clean approach and allows us to align the section of the header without a hassle. No need for any floats, margins or crazy width calculations.</p>
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus at congue urna, pellentesque faucibus justo. Integer a lorem a mauris suscipit congue luctus ut quam. Mauris pellentesque pellentesque mattis. In sed mi dignissim, faucibus elit at, rutrum odio. Mauris et velit magna. Maecenas iaculis eget sapien eu gravida. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vestibulum a egestas magna. Aenean tellus elit, aliquet at lacinia at, accumsan eget neque. Maecenas rutrum risus quis sem scelerisque sagittis. Quisque sit amet turpis lorem. </p>
		<div class="placeholder"></div>
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus at congue urna, pellentesque faucibus justo. Integer a lorem a mauris suscipit congue luctus ut quam. Mauris pellentesque pellentesque mattis. In sed mi dignissim, faucibus elit at, rutrum odio. Mauris et velit magna. Maecenas iaculis eget sapien eu gravida. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vestibulum a egestas magna. Aenean tellus elit, aliquet at lacinia at, accumsan eget neque. Maecenas rutrum risus quis sem scelerisque sagittis. Quisque sit amet turpis lorem. </p>
	</section>

</div>

</body>
</html>

Full responsiveness

The space-between trick will always take care of the alignment, even when the screen size changes. However, when the viewport becomes too small for a horizontal header, we can make it go vertical by changing the flex-direction property in a media query.

@media (max-width: 1000px){
	header{
		/* Reverse the axis of the header, making it vertical. */
		flex-direction: column;
		
		/* Align items to the begining (the left) of the header. */
		align-items: flex-start;
	}
}

Conclusion

This sums up our quick tutorial! We hope you found it useful and will start applying it right away. Flexbox has pretty good browser support nowadays, so unless your user base is IE heavy, this technique can be applied without causing any mayhem.

To learn more about flexbox and the CSS properties that we used, check out these links:

Tags: , , , ,
Posted in PHP Tutorials | Comments Off on Quick Tip: The Easiest Way To Make Responsive Headers

Learn Sass In 15 Minutes

Tuesday, January 19th, 2016

learn-sass-in-15-minutes

If you write copious amounts of CSS, a pre-processor can greatly decrease your stress levels and save you a lot of precious time. Using tools such as SassLessStylus or PostCSS makes large and complicated stylesheets clearer to understand and easier to maintain. Thanks to features like variables, functions and mixins the code becomes more organized, allowing developers to work quicker and make less mistakes.

We’ve worked with pre-processors before as you may remember from our article about Less. This time we are going to explain Sass and show you some of it’s main features.

1. Getting Started

Sass files cannot be interpreted by the browser, so they need compiling to standard CSS before they are ready to hit the web. That’s why you need some sort of tool to help you translate .scss files into .css. Here you have a couple of options:

If you decide to go with the command line, you can install Sass in it’s original form (written in ruby) or you can try the Node.js port (our choice). There are many other wrappers as well, but since we love Node.js we are going to go with that.

Here is how you can compile .scss files using the node CLI:

node-sass input.scss output.css

Also, here is the time to mention that Sass offers two distinct syntaxes – Sass and SCSS. They both do the same things, just are written in different ways. SCSS is the newer one and is generally considered better, so we are going to go with that. If you want more information on the difference between the two, check out this great article.

2. Variables

Variables in Sass work in a similar fashion to the those in any programming language, including principals such as data types and scope. When defining a variable we store inside it a certain value, which usually is something that will often reoccur in the CSS like a palette color, a font stack or the whole specs for a cool box-shadow.

Below you can see a simple example. Switch between the tabs to see the SCSS code and it’s CSS translation.

$title-font: normal 24px/1.5 'Open Sans', sans-serif;
$cool-red: #F44336;
$box-shadow-bottom-only: 0 2px 1px 0 rgba(0, 0, 0, 0.2);

h1.title {
  font: $title-font;
  color: $cool-red;
}

div.container {
  color: $cool-red;
  background: #fff;
  width: 100%;
  box-shadow: $box-shadow-bottom-only;
}
h1.title {
  font: normal 24px/1.5 "Open Sans", sans-serif;
  color: #F44336; 
}

div.container {
  color: #F44336;
  background: #fff;
  width: 100%;
  box-shadow: 0 2px 1px 0 rgba(0, 0, 0, 0.2);
}


The idea behind all this is that we can later on reuse the same values more quickly, or if a change is needed, we can provide the new value in just one place (the definition of the variable), instead of applying it manually everywhere we’re using that property.

3. Mixins

You can think of mixins as a simplified version of constructor classes in programming languages – you can grab a whole group of CSS declarations and re-use it wherever you want to give and element a specific set of styles.

Mixins can even accept arguments with the option to set default values. In the below example we define a square mixin, and then use it to create squares of varying sizes and colors.

@mixin square($size, $color) {
  width: $size;
  height: $size;
  background-color: $color;
}

.small-blue-square {
  @include square(20px, rgb(0,0,255));
}

.big-red-square {
  @include square(300px, rgb(255,0,0));
}
.small-blue-square {
  width: 20px;
  height: 20px;
  background-color: blue; 
}

.big-red-square {
  width: 300px;
  height: 300px;
  background-color: red;
}

Another efficient way to use mixins is when a property requires prefixes to work in all browsers.

@mixin transform-tilt() {
  $tilt: rotate(15deg);

  -webkit-transform: $tilt; /* Ch <36, Saf 5.1+, iOS, An =<4.4.4 */
      -ms-transform: $tilt; /* IE 9 */
          transform: $tilt; /* IE 10, Fx 16+, Op 12.1+ */
}

.frame:hover { 
  @include transform-tilt; 
}
.frame:hover {
  -webkit-transform: rotate(15deg);  /* Ch <36, Saf 5.1+, iOS, An =<4.4.4 */
  -ms-transform: rotate(15deg);  /* IE 9 */
  transform: rotate(15deg);  /* IE 10, Fx 16+, Op 12.1+ */ 
}

4. Extend

The next feature we will look at is @extend, which allows you to inherit the CSS properties of one selector to another. This works similarly to the mixins system, but is preferred when we want to create a logical connection between the elements on a page.

Extending should be used when we need similarly styled elements, which still differ in some detail. For example, let’s make two dialog buttons – one for agreeing and one for canceling the dialog.

.dialog-button {
  box-sizing: border-box;
  color: #ffffff;
  box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.12);
  padding: 12px 40px;
  cursor: pointer;
}

.confirm {
  @extend .dialog-button;
  background-color: #87bae1;
  float: left;
}

.cancel {
  @extend .dialog-button;
  background-color: #e4749e;
  float: right;
}
.dialog-button, .confirm, .cancel {
  box-sizing: border-box;
  color: #ffffff;
  box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.12);
  padding: 12px 40px;
  cursor: pointer; 
}

.confirm {
  background-color: #87bae1;
  float: left; 
}

.cancel {
  background-color: #e4749e;
  float: right; 
}

If you check out the CSS version of the code, you will see that Sass combined the selectors instead of repeating the same declarations over and over, saving us precious memory.

5. Nesting

HTML follows a strict nesting structure whereas in CSS it’s usually total chaos. With Sass nesting you can organize your stylesheet in a way that resembles the HTML more closely, thus reducing the chance of CSS conflicts.

For a quick example, lets style a list containing a number of links:

ul {
  list-style: none;

  li {
    padding: 15px;
    display: inline-block;

    a {
      text-decoration: none;
      font-size: 16px;
      color: #444;
    }

  }

}
ul {
  list-style: none; 
}

ul li {
  padding: 15px;
  display: inline-block; 
}

ul li a {
  text-decoration: none;
  font-size: 16px;
  color: #444; 
}

Very neat and conflict proof.

6.Operations

With Sass you can do basic mathematical operation right in the stylesheet and it is as simple as applying the appropriate arithmetic symbol.

$width: 800px;

.container { 
  width: $width;
}

.column-half {
  width: $width / 2;
}

.column-fifth {
  width: $width / 5;
}
.container {
  width: 800px; 
}

.column-half {
  width: 400px; 
}

.column-fifth {
  width: 160px; 
}

Although vanilla CSS now also offers this feature in the form of calc(), the Sass alternative is quicker to write, has the modulo % operation, and can be applied to a wider range of data-types (e.g. colors and strings).

7. Functions

Sass offers a long list of built-in functions. They serve all kinds of purposes including string manipulation, color related operations, and some handy math methods such as random() and round().

To exhibit one of the more simple Sass functions, we will create a quick snippet that utilizes darken($color, $amount) to make an on-hover effect.

$awesome-blue: #2196F3;

a {
  padding: 10 15px;
  background-color: $awesome-blue;
}

a:hover {
  background-color: darken($awesome-blue,10%);
}
a {
  padding: 10 15px;
  background-color: #2196F3; 
}

a:hover {
  background-color: #0c7cd5; 
}

Except the huge list of available functions, there is also the options to define your own. Sass supports flow control as well, so if you want to, you can create quite complex behaviors.

Conclusion

Some of the above features are coming to standard CSS in the future, but they are not quite here yet. In the meantime, pre-processors are a great way improve the CSS writing experience and Sass is a solid option when choosing one.

We only covered the surface here, but there is a lot more to Sass than this. If you want to get more familiar with everything it has to offer, follow these links:

Tags: , , , ,
Posted in PHP Tutorials | Comments Off on Learn Sass In 15 Minutes

Creating Your First Desktop App With HTML, JS and Electron

Wednesday, December 16th, 2015

creating-your-first-desktop-app-with-electron

Web applications become more and more powerful every year, but there is still room for desktop apps with full access to the hardware of your computer. Today you can create desktop apps using the already familiar HTML, JS and Node.js, then package it into an executable file and distribute it accordingly across Windows, OS X and Linux.

There are two popular open source projects which make this possible. These are NW.js, which we covered a few months ago, and the newer Electron, which we are going to use today (see the differences between them here). We are going to rewrite the older NW.js version to use Electron, so you can easily compare them.

Getting Started With Electron

Apps built with Electron are just web sites which are opened in an embedded Chromium web browser. In addition to the regular HTML5 APIs, these websites can use the full suite of Node.js modules and special Electron modules which give access to the operating system.

For the sake of this tutorial, we will be building a simple app that fetches the most recent Tutorialzine articles via our RSS feed and displays them in a cool looking carousel. All the files needed for the app to work are available in an archive which you can get from the Download button near the top of the page.

Extract its contents in a directory of your choice. Judging by the file structure, you would never guess this is a desktop application and not just a simple website.

Directory Structure

Directory Structure

We will take a closer look at the more interesting files and how it all works in a minute, but first, let’s take the app for a spin.

Running the App

Since an Electron app is just a fancy Node.js app, you will need to have npm installed. You can learn how to do it here, it’s pretty straightforward.

Once you’ve got that covered, open a new cmd or terminal in the directory with the extracted files and run this command:

npm install

This will create a node_modules folder containing all the Node.js dependencies required for the app to work. Everything should be good to go now, in the same terminal as before enter the following:

npm start

The app should open up in it’s own window. Notice it has a top menu bar and everything!

Electron App In Action

Electron App In Action

You’ve probably noticed that starting the app isn’t too user friendly. However, this is just the developer’s way of running an Electron app. When packaged for the public, the it will be installed like a normal program and opened like one, just by double clicking on its icon.

How it’s made

Here, we will talk about the most essential files in any electron app. Let’s start with package.json, which holds various information about the project, such as the version, npm dependencies and other important settings.

package.json

{
  "name": "electron-app",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "dependencies": {
    "pretty-bytes": "^2.0.1"
  },
  "devDependencies": {
    "electron-prebuilt": "^0.35.2"
  },
  "scripts": {
    "start": "electron main.js"
  },
  "author": "",
  "license": "ISC"
}

If you’ve worked with node.js before, you already know how this works. The most significant thing to note here is the scripts property, where we’ve defined the npm start command, allowing us to run the app like we did earlier. When we call it, we ask electron to run the main.js file. This JS file contains a short script that opens the app window, and defines some options and event handlers.

main.js

var app = require('app');  // Module to control application life.
var BrowserWindow = require('browser-window');  // Module to create native browser window.

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow = null;

// Quit when all windows are closed.
app.on('window-all-closed', function() {
    // On OS X it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform != 'darwin') {
        app.quit();
    }
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
    // Create the browser window.
    mainWindow = new BrowserWindow({width: 900, height: 600});

    // and load the index.html of the app.
    mainWindow.loadURL('file://' + __dirname + '/index.html');

    // Emitted when the window is closed.
    mainWindow.on('closed', function() {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        mainWindow = null;
    });
});

Take a look at what we do in the ‘ready’ method. First we define a browser window and set it’s initial size. Then, we load the index.html file in it, which works similarly to opening a HTML file in your browser.

As you will see, the HTML file itself is nothing special – a container for the carousel and a paragraph were CPU and RAM stats are displayed.

index.html

<!DOCTYPE html>
<html>
<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Tutorialzine Electron Experiment</title>

    <link rel="stylesheet" href="./css/jquery.flipster.min.css">
    <link rel="stylesheet" href="./css/styles.css">

</head>
<body>

<div class="flipster">
    <ul>
    </ul>
</div>

<p class="stats"></p>

<!-->In Electron, this is the correct way to include jQuery<-->
<script>window.$ = window.jQuery = require('./js/jquery.min.js');</script>
<script src="./js/jquery.flipster.min.js"></script>
<script src="./js/script.js"></script>
</body>
</html>

The HTML also links to the needed stylesheets, JS libraries and scripts. Notice that jQuery is included in a weird way. See this issue for more information about that.

Finally, here is the actual JavaScript for the app. In it we access Tutorialzine’s RSS feed, fetch recent articles and display them. If we try to do this in a browser environment, it won’t work, because the RSS feed is located on a different domain and fetching from it is forbidden. In Electron, however, this limitation doesn’t apply and we can simply get the needed information with an AJAX request.

$(function(){

    // Display some statistics about this computer, using node's os module.

    var os = require('os');
    var prettyBytes = require('pretty-bytes');

    $('.stats').append('Number of cpu cores: <span>' + os.cpus().length + '</span>');
    $('.stats').append('Free memory: <span>' + prettyBytes(os.freemem())+ '</span>');

    // Electron's UI library. We will need it for later.

    var shell = require('shell');


    // Fetch the recent posts on Tutorialzine.

    var ul = $('.flipster ul');

    // The same-origin security policy doesn't apply to electron, so we can
    // send ajax request to other sites. Let's fetch Tutorialzine's rss feed:

    $.get('http://feeds.feedburner.com/Tutorialzine', function(response){

        var rss = $(response);

        // Find all articles in the RSS feed:

        rss.find('item').each(function(){
            var item = $(this);

            var content = item.find('encoded').html().split('</a></div>')[0]+'</a></div>';
            var urlRegex = /(http|ftp|https)://[w-_]+(.[w-_]+)+([w-.,@?^=%&amp;:/~+#]*[w-@?^=%&amp;/~+#])?/g;

            // Fetch the first image of the article.
            var imageSource = content.match(urlRegex)[1];


            // Create a li item for every article, and append it to the unordered list.

            var li = $('<li><img /><a target="_blank"></a></li>');

            li.find('a')
                .attr('href', item.find('link').text())
                .text(item.find("title").text());

            li.find('img').attr('src', imageSource);

            li.appendTo(ul);

        });

        // Initialize the flipster plugin.

        $('.flipster').flipster({
            style: 'carousel'
        });

        // When an article is clicked, open the page in the system default browser.
        // Otherwise it would open it in the electron window which is not what we want.

        $('.flipster').on('click', 'a', function (e) {

            e.preventDefault();

            // Open URL with default browser.

            shell.openExternal(e.target.href);

        });

    });

});

A cool thing about the above code, is that in one file we simultaneously use:

And with this our app is ready!

Packaging and Distribution

There is one other important thing to do to make your app ready for end users. You need to package it into an executable that can be started with a double click on users’ machines. Since Electron apps can work on multiple operating systems and every OS is different, there need to be separate distributions for Windows, for OS X and for Linux. Tools such as this npm module are a good place to start – Electron Packager.

Take into consideration that the packaging takes all your assets, all the required node.js modules, plus a minified WebKit browser and places them together in a single executable file. All these things sum up and the final result is an app that is roughly 50mb in size. This is quite a lot and isn’t practical for a simple app like our example here, but this becomes irrelevant when we work with big, complex applications.

Conclusion

The only major difference with NW.js that you will see in our example is that NW.js opens an HTML page directly, whereas Electron starts up by executing a JavaScript file and you create an application window through code. Electron’s way gives you more control, as you can easily build multi-window applications and organize the communication between them.

Overall Electron is an exciting way to build desktop web applications using web technologies. Here is what you should read next:

Tags: , , , ,
Posted in PHP Tutorials | Comments Off on Creating Your First Desktop App With HTML, JS and Electron

Using Flexbox to Create a Responsive Comment Section

Wednesday, November 18th, 2015

flexbox-responsive-comment-section

Flexbox is a powerful new way for building layouts that makes some of the most challenging aspects of web development trivial. Nearly all browsers that are used today support it, so it is a good time to see how it can fit in your typical day-to-day frontend work.

This is why in this quick tutorial we’re going to build a comment section using flexbox. We’ll take a look at some of the more interesting properties that the flexbox layout mode has to offer and show you how to take full advantage of it.

What We’re Going to Use

Flexbox consists of a number of CSS properties, some of which we are going to use today:

The Layout

We want our comment section to meet the following requirements:

Comment Section Layout

Comment Section Layout

All of this can be made with a few lines of CSS with flexbox. Let’s move on the the code!

The HTML

Our HTML is pretty straightforward. We’ll have a list of comments with a basic form for writing new comments at the end.

<ul class="comment-section">

    <li class="comment user-comment">
        <div class="info">
            <a href="#">Anie Silverston</a>
            <span>4 hours ago</span>
        </div>
        <a class="avatar" href="#">
            <img src="images/avatar_user_1.jpg" width="35" alt="Profile Avatar" title="Anie Silverston" />
        </a>
        <p>Suspendisse gravida sem?</p>
    </li>

    <li class="comment author-comment">
        <div class="info">
            <a href="#">Jack Smith</a>
            <span>3 hours ago</span>
        </div>
        <a class="avatar" href="#">
            <img src="images/avatar_author.jpg" width="35" alt="Profile Avatar" title="Jack Smith" />
        </a>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse gravida sem sit amet molestie portitor.</p>

    </li>

    <!-- More comments -->

    <li class="write-new">

        <form action="#" method="post">
            <textarea placeholder="Write your comment here" name="comment"></textarea>
            <div>
                <img src="images/avatar_user_2.jpg" width="35" alt="Profile of Bradley Jones" title="Bradley Jones" />
                <button type="submit">Submit</button>
            </div>
        </form>

    </li>

</ul>

If you look closely at the above code, you’ll notice that apart from having different classes, the HTML for the user comments and the author comments are practically the same. All of the stylistic and layout differences between the two, will be handled solely by CSS applied to the .user-comment and .author-comment classes.

The CSS

Here we’re going to look at flexbox-related techniques we’ve used when building the layout. If you want to examine the stylesheet in full detail, download the whole CSS file from the button near the top of the article.

First off, we are going to give all comments display: flex, which will enable us to use the flexbox properties on the comments and their child elements.

.comment{
    display: flex;
}

These flex containers span the full width of our comment section and hold the user info, avatar and message. Since we want the comments written by the author to be aligned to the right, we can use the following flex property and align everything towards the end of our container.

.comment.author-comment{
    justify-content: flex-end;
}

This will leave the comments looking like this:

justify-content: flex-end

justify-content: flex-end

Now we have the author comment aligned on the right, but we also want to have the elements inside the container in reverse order, so that the message comes first, then the avatar and the info on the far right. To do this we will take advantage of the order property.

.comment.author-comment .info{
    order: 3;
}

.comment.author-comment .avatar{
    order: 2;
}

.comment.author-comment p{
    order: 1;
}

As you can see, with the help of flexbox, the whole thing couldn’t be any easier.

Reordering Elements

Reordering Elements

Our comment section looks just like we wanted it to. The only thing left to do is make sure that it looks good on smaller devices as well. Since there won’t be as much available space on a narrower screen, we’ll have to do some rearrangements to the layout and make our content more easily readable.

We set up a media query that makes the comment paragraphs expand, taking up the whole width of the container. This will lead to the avatar and user info moving to the next line, since the comments have their flex-wrap property set to wrap.

@media (max-width: 800px){
    /* Reverse the order of elements in the user comments,
    so that the avatar and info appear after the text. */
    .comment.user-comment .info{
        order: 3;
    }

    .comment.user-comment .avatar{
        order: 2;
    }

    .comment.user-comment p{
        order: 1;
    }


    /* Make the paragraph in the comments take up the whole width,
    forcing the avatar and user info to wrap to the next line*/
    .comment p{
        width: 100%;
    }


    /* Align toward the beginning of the container (to the left)
    all the elements inside the author comments. */
    .comment.author-comment{
        justify-content: flex-start;
    }
}

The difference can be spotted right away by comparing this screen capture with the one above. You can also try opening the demo and resizing your browser to watch the comment section adapt accordingly to the size of the window.

Our comment section on smaller screens

Our comment section on smaller screens

Conclusion

This sums up our tutorial. We hope that this gave you a practical example on how to use flexbox when building real layouts. If you’re curious what else is possible, here are a few great resources that you’ll like:

Tags: , , , ,
Posted in PHP Tutorials | Comments Off on Using Flexbox to Create a Responsive Comment Section

Quick Tip: The Simplest Way To Center Elements Vertically And Horizontally

Wednesday, September 2nd, 2015

the-simple-way-to-center

Flexbox is a relatively new addition to the CSS world and we keep finding more and more excellent applications for it. We can even solve the age-old problem with centering an element both vertically and horizontally with CSS. It is easier than you can imagine – it is only three lines of code, doesn’t require you to specify the size of the centered element and is responsive-friendly!

This technique works in all modern browsers – IE10+, Chrome, Firefox and Safari (with the -webkit- prefix). See the full compatibility table here.

(Play with our code editor on Tutorialzine.com)

The HTML

The idea, of course, revolves around flexbox. First, we create a container in which we want everything to be centered:

<div class="container">
    <!--// Any content in here will be centered.-->
    <img src="fireworks.jpg" alt="fireworks">
</div>

You can place this container div anywhere you want. In the live example above we’ve made it take up the whole width and height of the page.

The CSS

As we said earlier, we will be using only three lines of code. Here they are:

.container{
    display: flex;
    justify-content: center;
    align-items: center;
}

Every flex container has two axis for positioning elements. The main axis is declared with the flex-direction property (can be row or column, see docs). By omitting this rule, we’ve left the flex direction to its default row value.

Now all that we need to do is center both axis. It couldn’t get any simpler:

  1. Make the display type flex, so that we activate flexbox mode.
  2. justify-content defines where flex items will align according to the main axis (horizontally in our case).
  3. align-items does the same with the axis perpendicular to the main one (vertically in our case).

Now that we have set the rules for the vertical and the horizontal alignment to center, any element we add inside the container will be positioned perfectly in the middle. We don’t need to know its dimensions beforehand, the browser will do all the hard work!

Conclusion

There are lots of other techniques for centering content with CSS, but flexbox makes this a whole lot simpler and more elegant. If you wish to learn more about it, check out these resources:

Tags: , , , ,
Posted in PHP Tutorials | Comments Off on Quick Tip: The Simplest Way To Center Elements Vertically And Horizontally

Top Fireworks Tutorials for Web Design

Thursday, July 30th, 2015


Even though Adobe has officially discontinued Fireworks it still remains a very popular tool for UI design. Creative Cloud includes Fireworks CS6 as part of the bundle and it should be supported for a least a couple more years. Thus learning Fireworks can be one of the best decisions you make when it comes to mockup design and wireframing. These tutorials are aimed at complete beginners who want to bring Fireworks into their typical web design workflow.

Fireworks UI

intro to fireworks ui

Wireframing

fireworks wireframing how to

Mood Boards

moodboards web design fireworks

Vectorize Elements

howto vector design fireworks

Design Tools

video design tools fireworks

Fireworks for Web Design

basics of fireworks webdesign tutorial

jQuery Mobile in FW

fireworks for jquery mobile ui

Fireworks Design Workflow

fireworks workflow for web design

Brushed Metal Effect

brushed metal icloud icon fireworks

3D Text

3d text effect fireworks

Complex Vector Shapes

complex vector shapes fireworks

SVG with Fireworks

svg graphics in fireworks

Interactive Prototypes

interactive prototypes fireworks

Rocketship Icon

rocket ship icon fireworks

Fireworks Style Guide

fireworks howto design style guide

Advertisements:
ioDeck, a self-hosted and awesome PHP form generator.
Professional XHTML Admin Template ($15 Discount With The Code: WRD.)
SSLmatic – Cheap SSL Certificates (from $19.99/year)

The post Top Fireworks Tutorials for Web Design appeared first on Web Resources Depot.

Tags: ,
Posted in Uncategorized | Comments Off on Top Fireworks Tutorials for Web Design

Tutorials for Learning Google Material Design

Wednesday, July 29th, 2015


Android Lollipop has become the standard method of design for smartphones powered by Google’s OS. This design follows the popular flat techniques to a T with slight drop shadows, but almost no gradients or bevels. It’s an easy technique to master but difficult to gain momentum.

These tutorials can teach even a complete novice how to design Android interfaces in Photoshop, Sketch, and Illustrator.

Tuts+ Material Intro

google material design introduction

Getting Started

getting started android material

Android Toolbar

material design toolbar

Floating Button

floating button ui design

Flat Tabs

flat android tabs tutorial

Sliding Nav

sliding drawer nav ui

Materialize CSS Framework

css materialize framework

Polymer Chat App

material polymer chat app

Lollipop Resources

free material lollipop resources

Free Swatches & Palettes

free swatches color palettes material design

Material Shadows

material design shadows tutorial

Material Design in Sketch

material design sketch tutorial

Sketch Android App Design

android apps in sketch howto

PS & AI Material Design

photoshop illustrator material design

Advertisements:
ioDeck, a self-hosted and awesome PHP form generator.
Professional XHTML Admin Template ($15 Discount With The Code: WRD.)
SSLmatic – Cheap SSL Certificates (from $19.99/year)

The post Tutorials for Learning Google Material Design appeared first on Web Resources Depot.

Tags: ,
Posted in Uncategorized | Comments Off on Tutorials for Learning Google Material Design

Making Your First HTML5 Game With Phaser

Tuesday, June 16th, 2015

html5-game-phaser

Everybody loves classic games. How many of you remember the retro snake game from old Nokia phones? We sure do. This is why for this lesson we decided to recreate it using HTML5. There is a great open source game development framework called Phaser that we will use.

You will learn about sprites, game states and how to use the preload, create and update methods. Here’s what the final version of the game we’re building looks like:

Finished Game

Setup

Download a zip archive with the file structure of the game here. It contains all the image assets needed for the game but no code. We will be writing this next.

Now open index.html, add a title for your page and create links to all the JS files. Later, to play the game, just open this file in your browser.

<!doctype html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>Snake</title>
    <script src="assets/js/phaser.min.js"></script>
    <script src="assets/js/menu.js"></script>
    <script src="assets/js/game.js"></script>
    <script src="assets/js/game_over.js"></script>
    <script src="assets/js/main.js"></script>
</head>
<body>

</body>
</html>

Your directory should look like this:

Directory Tree

Directory Tree

How the game is organized

Phaser games are organized around states. Think of states in Phaser as the different parts of a game. Here are the states of our game:

main.js is our main JavaScript file. This is the place where we will create a new game instance and add a menu state.

1. Loading an image

Right now, our game doesn’t do anything. Let’s code the Menu state, and make it display the title screen.

During the setup we included the Phaser library in our HTML file. This gives us a global object called Phaser. Through it, we can access the library’s methods and functions for building games.

Now we will use the global Phaser object, and create a new game instance. This is an object which represents our entire game. We will add the states to it.

main.js

var game;

// Create a new game instance 600px wide and 450px tall:
game = new Phaser.Game(600, 450, Phaser.AUTO, '');

// First parameter is how our state will be called.
// Second parameter is an object containing the needed methods for state functionality
game.state.add('Menu', Menu);

game.state.start('Menu');

Now we need to initialize our Menu state object. In menu.js define a new object and add the functions below. When the state is started, the preload function will be called first, loading all the needed assets for our game. Once preloading finishes, create gets called, initializing the playing field and everything we want on it:

menu.js

var Menu = {

    preload : function() {
        // Loading images is required so that later on we can create sprites based on the them.
        // The first argument is how our image will be refered to, 
        // the second one is the path to our file.
        game.load.image('menu', './assets/images/menu.png');
    },

    create: function () {
        // Add a sprite to your game, here the sprite will be the game's logo
        // Parameters are : X , Y , image name (see above) 
        this.add.sprite(0, 0, 'menu');
    }

};

Because of browser security restrictions, to start the game you’ll need a locally running web server. This page from the Phaser guidelines has plenty of options for all operating systems – here. In other words, it won’t work if you simply double click your index.html.

If everything has been done right, a page with the the start screen should appear in your browser.

Rendering an image

2. Drawing the snake

As we mentioned earlier, the Game state is where the actual game play happens. This is also the place where we will draw the snake. Like we did with the Menu state, we need to register the Game state with the global game object in main.js. Here is how your code should look like:

main.js

var game;

game = new Phaser.Game(600, 450, Phaser.AUTO, '');

game.state.add('Menu', Menu);

// Adding the Game state.
game.state.add('Game', Game);

game.state.start('Menu');

We’ll also want to add some code in menu.js to let us start the Game state when it is clicked. For this purpose, we will replace the sprite with a button. Adding a button is basically the same as adding a sprite, you only need to provide a function to be called when it is clicked. Here is the final menu.js code:

menu.js

var Menu = {

    preload : function() {
        // Load all the needed resources for the menu.
        game.load.image('menu', './assets/images/menu.png');
    },

    create: function () {

        // Add menu screen.
        // It will act as a button to start the game.
        this.add.button(0, 0, 'menu', this.startGame, this);

    },

    startGame: function () {

        // Change the state to the actual game.
        this.state.start('Game');

    }

};

We can now proceed with coding the Game state and drawing the snake. The structure is similar to the one of the Menu state.

game.js

var snake, apple, squareSize, score, speed,
    updateDelay, direction, new_direction,
    addNew, cursors, scoreTextValue, speedTextValue, 
    textStyle_Key, textStyle_Value;

var Game = {

    preload : function() {
        // Here we load all the needed resources for the level.
        // In our case, that's just two squares - one for the snake body and one for the apple.
        game.load.image('snake', './assets/images/snake.png');
        game.load.image('apple', './assets/images/apple.png');
    },

    create : function() {

        // By setting up global variables in the create function, we initialise them on game start.
        // We need them to be globally available so that the update function can alter them.

        snake = [];                     // This will work as a stack, containing the parts of our snake
        apple = {};                     // An object for the apple;
        squareSize = 15;                // The length of a side of the squares. Our image is 15x15 pixels.
        score = 0;                      // Game score.
        speed = 0;                      // Game speed.
        updateDelay = 0;                // A variable for control over update rates.
        direction = 'right';            // The direction of our snake.
        new_direction = null;           // A buffer to store the new direction into.
        addNew = false;                 // A variable used when an apple has been eaten.

        // Set up a Phaser controller for keyboard input.
        cursors = game.input.keyboard.createCursorKeys();

        game.stage.backgroundColor = '#061f27';

        // Generate the initial snake stack. Our snake will be 10 elements long.
        // Beginning at X=150 Y=150 and increasing the X on every iteration.
        for(var i = 0; i < 10; i++){
            snake[i] = game.add.sprite(150+i*squareSize, 150, 'snake');  // Parameters are (X coordinate, Y coordinate, image)
        }


        // Genereate the first apple.
        this.generateApple();


        // Add Text to top of game.
        textStyle_Key = { font: "bold 14px sans-serif", fill: "#46c0f9", align: "center" };
        textStyle_Value = { font: "bold 18px sans-serif", fill: "#fff", align: "center" };

        // Score.
        game.add.text(30, 20, "SCORE", textStyle_Key);
        scoreTextValue = game.add.text(90, 18, score.toString(), textStyle_Value);
        // Speed.
        game.add.text(500, 20, "SPEED", textStyle_Key);
        speedTextValue = game.add.text(558, 18, speed.toString(), textStyle_Value);

    },



    update: function() {
        // The update function is called constantly at a high rate (somewhere around 60fps),
        // updating the game field every time.
        // We are going to leave that one empty for now.
    },


    generateApple: function(){

        // Chose a random place on the grid.
        // X is between 0 and 585 (39*15)
        // Y is between 0 and 435 (29*15)

        var randomX = Math.floor(Math.random() * 40 ) * squareSize,
            randomY = Math.floor(Math.random() * 30 ) * squareSize;

        // Add a new apple.
        apple = game.add.sprite(randomX, randomY, 'apple');
    }

};

Here is how the snake and apple should look like:

Drawing the snake

3. Movement and control

To make the snake move we’ll be working in the update function of game.js.

First of all, we create event listeners for controlling the direction of the snake with the arrow keys.

The actual movement is a bit complex, since update is triggered at a very quick rate, and if we move the snake every time it’s called we would end up with one uncontrollably speedy reptile. To change this, we’ve set up an if statement that checks weather this is the 10th consecutive call of update() using a counter variable called updateDelay. 

If it really is the 10th call, we remove the last square of our snake (first element in the stack), give it new coordinates according to the current direction and place it in front of the head of the snake (top of the stack). Here’s how the code looks like:

update: function() {

    // Handle arrow key presses, while not allowing illegal direction changes that will kill the player.

    if (cursors.right.isDown && direction!='left')
    {
        new_direction = 'right';
    }
    else if (cursors.left.isDown && direction!='right')
    {
        new_direction = 'left';
    }
    else if (cursors.up.isDown && direction!='down')
    {
        new_direction = 'up';
    }
    else if (cursors.down.isDown && direction!='up')
    {
        new_direction = 'down';
    }


    // A formula to calculate game speed based on the score.
    // The higher the score, the higher the game speed, with a maximum of 10;
    speed = Math.min(10, Math.floor(score/5));
    // Update speed value on game screen.
    speedTextValue.text = '' + speed;

    // Since the update function of Phaser has an update rate of around 60 FPS,
    // we need to slow that down make the game playable.

    // Increase a counter on every update call.
    updateDelay++;

    // Do game stuff only if the counter is aliquot to (10 - the game speed).
    // The higher the speed, the more frequently this is fulfilled,
    // making the snake move faster.
    if (updateDelay % (10 - speed) == 0) {


        // Snake movement

        var firstCell = snake[snake.length - 1],
            lastCell = snake.shift(),
            oldLastCellx = lastCell.x,
            oldLastCelly = lastCell.y;

        // If a new direction has been chosen from the keyboard, make it the direction of the snake now.
        if(new_direction){
            direction = new_direction;
            new_direction = null;
        }


        // Change the last cell's coordinates relative to the head of the snake, according to the direction.

        if(direction == 'right'){

            lastCell.x = firstCell.x + 15;
            lastCell.y = firstCell.y;
        }
        else if(direction == 'left'){
            lastCell.x = firstCell.x - 15;
            lastCell.y = firstCell.y;
        }
        else if(direction == 'up'){
            lastCell.x = firstCell.x;
            lastCell.y = firstCell.y - 15;
        }
        else if(direction == 'down'){
            lastCell.x = firstCell.x;
            lastCell.y = firstCell.y + 15;
        }


        // Place the last cell in the front of the stack.
        // Mark it the first cell.

        snake.push(lastCell);
        firstCell = lastCell;

    }
    
}

Try and control the snake via the arrow keys on your keyboard.

Movement and control

 4. Collision detection

A game in which the snake is roaming freely in the playing field is not much fun. We need to detect when the snake comes in contact with a wall, an apple or itself. This is called collision detection.

This is usually done by using a physics engine, of which the Phaser framework supports a few. But they are too complex for a simple game like this. We will instead do our own collision detection by comparing coordinates.

In the update function, after the code for moving the snake, we call a number of methods. They will compare coordinates to tell us if a collision has occurred.

update: function() {

        // Snake movement
        // ...
        // End of snake movement

        // Increase length of snake if an apple had been eaten.
        // Create a block in the back of the snake with the old position of the previous last block
        // (it has moved now along with the rest of the snake).

        if(addNew){
            snake.unshift(game.add.sprite(oldLastCellx, oldLastCelly, 'snake'));
            addNew = false;
        }

        // Check for apple collision.
        this.appleCollision();

        // Check for collision with self. Parameter is the head of the snake.
        this.selfCollision(firstCell);

        // Check with collision with wall. Parameter is the head of the snake.
        this.wallCollision(firstCell);
    }


},

appleCollision: function() {

    // Check if any part of the snake is overlapping the apple.
    // This is needed if the apple spawns inside of the snake.
    for(var i = 0; i < snake.length; i++){
        if(snake[i].x == apple.x && snake[i].y == apple.y){

            // Next time the snake moves, a new block will be added to its length.
            addNew = true;

            // Destroy the old apple.
            apple.destroy();

            // Make a new one.
            this.generateApple();

            // Increase score.
            score++;

            // Refresh scoreboard.
            scoreTextValue.text = score.toString();

        }
    }

},

selfCollision: function(head) {

    // Check if the head of the snake overlaps with any part of the snake.
    for(var i = 0; i < snake.length - 1; i++){
        if(head.x == snake[i].x && head.y == snake[i].y){

            // If so, go to game over screen.
            game.state.start('Game_Over');
        }
    }

},

wallCollision: function(head) {

    // Check if the head of the snake is in the boundaries of the game field.

    if(head.x >= 600 || head.x < 0 || head.y >= 450 || head.y < 0){


        // If it's not in, we've hit a wall. Go to game over screen.
        game.state.start('Game_Over');
    }

}

When the snake collides with the apple we increase the score and the length of the snake. But when a collision with the wall or the snake body occurs, we should end the game. To do this, we need to make the Game_Over state. Again, we need to register it with main.js. Add this line near the bottom of that file:

main.js

game.state.add('Game_Over', Game_Over);

And the state itself:

game_over.js

var Game_Over = {

    preload : function() {
        // Load the needed image for this game screen.
        game.load.image('gameover', './assets/images/gameover.png');
    },

    create : function() {

        // Create button to start game like in Menu.
        this.add.button(0, 0, 'gameover', this.startGame, this);

        // Add text with information about the score from last game.
        game.add.text(235, 350, "LAST SCORE", { font: "bold 16px sans-serif", fill: "#46c0f9", align: "center"});
        game.add.text(350, 348, score.toString(), { font: "bold 20px sans-serif", fill: "#fff", align: "center" });

    },

    startGame: function () {

        // Change the state back to Game.
        this.state.start('Game');

    }

};

Collision detection

That’s it! Our game is ready!

Further reading

We hope that you liked our simple game and learned a lot while following our tutorial. There is much more to learn about Phaser:

Tags: , , , ,
Posted in PHP Tutorials | Comments Off on Making Your First HTML5 Game With Phaser