From the Bookmarks Bar – August 30, 2013

This week from the bookmarks bar I’ve got some interesting new developments in the world of Android development, a great new JS app for chip tune lovers and some great suggestions for front-end developers to promote code reuse.

C++ Compiler for Android

Want to start tinkering with Android applications but not that up to date on Java.  Good news!  Intel has released their own compiler for C++ that generates native Android applications.  Better yet, it is free for the time being.

Band.js: An 8-bit JavaScript Audio Library

Anyone who loves video games is no doubt a fan of the old chip tune music from the days of the NES and Game Boy.  Using a new library, you can create 8 bit chip tunes using only JavaScript and the HTML5 audio API.  Check out the link for some sample tunes from Super Mario Bros., Tetris and Zelda.

Decoupling HTML, CSS and JavaScript

Decoupling is a must with web applications; we have many design patterns that we follow and we split our applications into layers for this purpose.  However, we often think of the view as just one part of that application.  Most web applications have multiple front ends and it helps to be able to reuse HTML and CSS where possible.  Here is a good look at ways to do it.

Thanks for reading!  If you have some great bookmark suggestions please let me know in the comments!

Advertisements

Choosing a Game Development Framework

Lately I’ve had an idea for a game that I just can’t get out of my head.  Combined with the recent unveiling of the Nintendo Web Framework I’m compelled to make an attempt to get a demo of the game running on the Wii U.  At a recent presentation from Unite ’13, Nintendo touted how easy game development is for the Wii U using JavaScript and HTML5.  I’ve always wanted to explore the limitations of HD gaming within the browser so this is the perfect opportunity to test Nintendo’s claims.

Our weakness as developers is that when we have an idea we just want to code.  I don’t want to plan or design, I want to get something up and running and see the fruits of my labor as soon as possible.  As much as I love technology, some times I’m so compelled to code that I don’t even want to vet the best framework for the job.  Sometimes I’ll just grab what I’m most familiar with and start working.  With game development, that is difficult to do.

I wrote a previous post about the pitfalls of game development in JavaScript where I mentioned not reinventing the wheel.  I see so many horror stories of indie developers spending all of their time on an engine and not ever making a game.  I suggested a couple of frameworks in that post, but now that I’ve completed a more extensive vetting process I’d like to share some insight on the decisions that I made.

2D vs. 3D

If you are planning on making a 3D game, you should look no further than Unity.  You can quickly get prototypes of your game running by relying on Unity as a backbone.  There are a number of resources already available that you can take advantage of for development.  These include 3D models, plugins and tutorials for your project.

If you insist against Unity, CryEngine, Unreal Engine and the Source Engine are other options, but aren’t exactly targeted to indie developers.

I was dead set on making a 2D game; many aspects of my game rely on it.  Making a true 2D game in Unity is just not possible.  You can create a game with a fixed camera that limits movement to two dimensions but ultimately the assets and game will run 3D.  My inexperience with 3D game development had me a bit nervous going that route.

Web, Mobile or dare I say it…consoles?

I mention above that I already had some interest in the Nintendo Web Framework as a potential target, so the decision to make the game using JavaScript and HTML5 was practically made for me.  However, that wouldn’t make for a very interesting post now would it?

If I wanted to make a game for mobile platforms and perhaps PC/Mac/Linux, my previous experience would lead me to look toward cocos2d.  I have previously worked with cocos2d-iphone and found it easy to work with.  cocos2d-x is essentially the cross platform version of cocos2d, which has support for those and many other platforms.

Whittling It Down

A quick Google search turns up many JavaScript game development frameworks.  How do you decide which one to use?  I ended up filtering out options based on features that I saw as valuable to me.  This is obviously a subjective process, so your criteria may lead you to a different result than mine.

First, I needed something free and open source if possible.  I would hardly even consider myself an indie developer and I really can’t see myself financially contributing to a pet project like this.  Second, I’d prefer a framework that can work out of the box with standard tools such as Tiled for tile based map creation.

At this point I had narrowed my decision down to two options: cocos2d-html5 and melonJS.  It is going to sound odd based on my recommendation of cocos2d above, but after working with both options I eventually settled on using melonJS.  cocos2d has its applications but for lightweight, simple JavaScript game development it is my opinion that melonJS is the best framework out there.

Thanks to the great documentation, I had a simple platformer up and running using the melonJS boilerplate project within an hour of getting started.  I have yet to thoroughly stress test, but I’ve had no hiccups running the game at 720p within Chrome.

Why did I turn away from cocos2d-html5?  After some exploration it just didn’t seem like the best way to go for a lightweight JavaScript game.  Ultimately, cocos2d-html5 is meant for cross platform games between the web and iPhone, and the API reflects that.  I wanted something built for JavaScript from the ground up.

Have you been working with a framework that you really like?  Leave a comment to let me know.

Code Wars: Training in Programming Arts

As developers we have to frequently consult outside resources for information on how to complete certain tasks.  Whether it’s a book or an online tutorial, a quick refresher is always helpful to get a push in the right direction.  The problem is that we will often look for these resources when we know specifically what we need to do, rather than using them to buff up our skills.

There are many sites out there that allow you to do programming challenges to work on your proficiency with a language.  Project Euler, TopCoder or the Daily Programmer subreddit come to mind.  My newest addiction of this type of site is Code Wars.

What is Code Wars?

I like to explain Code Wars as a combination of small programming challenges and Xbox style achievements.  You complete a series of code “katas“: short snippets or bug fixes that test basic understanding of programming language concepts.  For each kata that you complete, you work your way up to higher ranks and increasingly more difficult tasks.

Code Wars Dashboard

The user dashboard in Code Wars.

Code Wars tracks the type of the katas that you complete into different types, such as bug fixes, algorithms and reference.  You can also complete katas in either JavaScript, Coffee Script or Ruby.  Since Code Wars starts with the basics, it is perfect for supplementing your learning of a new language.

Test Your Might

Code Wars provides you with a very simple code editor with syntax highlighting.  It works surprisingly well in the browser, complete with handling of indentation and other features.  You are also provided with the ability to write unit tests against your solution to test any cases that will help you complete the kata.  Then you submit your solution.  There becomes nothing more addicting than getting that green check mark every time you complete a kata.

The best feature of Code Wars comes after you complete a kata.  Once you submit your solution and it is verified, you get to see the solutions that other developers submitted as well.  Sometimes you will see solutions that are more complicated than your own, but quite often you will see solutions that are mind blowing in their simplicity.  I typically spend just as much time reviewing other’s solutions as I do coming up with my own.

Future Wars

I have no doubt that in the future Code Wars will bring support for more languages.  I’m excited at the possibility of completing code katas with Python or PHP.  I can’t help but think that Code Wars would also be an amazing tool for teaching people how to use the UNIX command line.

The beauty of Code Wars is that its katas are populated by user submissions, so it will continue to grow with new content in the as time goes on.

Want to test your skills?  Sign up by completing the example kata at http://www.codewars.com!  Thanks for reading!  If you would like, you can view my Code Wars profile here!

From the Bookmarks Bar – August 16, 2013

This week I’m excited to share a few great links From the Bookmarks Bar.  I have two great development tools and a free course that is very interesting.  Everyone loves free learning!  Take a look!

Koding: Free Virtual Machines for Developers

A new project called Koding has recently launched, with the goal to provide free virtual machines with development environments available to anyone.  The VMs run an instance of Ubuntu which you can use to develop on any language you wish.

The World’s Simplest HTML5 WYSIWYG Editor

Getting tired of the bulky, complex WYSIWYG editors?  Want something fast and easy to use?  Check out the world’s simplest editor.  With Bootstrap and around 100 lines of HTML/CSS/JS you can have a fully functioning HTML editor on your site.

Create Your Own Programming Language

Ever wondered what goes into developing a new programming language?  Here is a great introductory level course that goes over the basics of everything from parsing to compiling.

Thanks for reading!  Do you have some links you would like to see in the bookmarks bar?  Leave a comment or let me know on Twitter!

How to Write a jQuery Plugin – Part 2: Options and Collections

In part one of my series on creating a jQuery plugin, I showed an example on how to structure a new custom plugin.  In this post, I’ll show you how to provide options for developers using your plugin and how to allow your plugin to handle multiple elements in the DOM.

User Options

You will remember in part one that we added an options parameter to our plugin’s main function.  It looked like this:

$.fn.highlight = function (options) {

This parameter is an object that will contain values for all of the options that the user will specify.  There is nothing special about this object.  It can hold any kind of data that you need to use as a setting for your plugin.  The problem with using this object directly is that we don’t want to require the user to set any options at all, if we don’t need them to.  However, we also don’t want to have to check to see if each value exists to specify a default.

jQuery’s built in extend function simplifies this down to a small piece of code.  See the example below:

var settings = $.extend({
     cssClass: 'highlight-yellow'
}, options);

In this snippet we are creating a variable in our plugin to hold our user settings.  To do this, we pass two things into jQuery’s extend function.  The first is an object that contains all of the default values that we wish for our plugin to use if the user does not specify their own value.  The second parameter is, you guessed it, the options variable containing the user’s specified values.  jQuery extend takes those two objects and merges them together, replacing our default values with the values in the options variable, if they exist.

In this case, I’ve added a very simple setting that will control the class that gets added to the content to highlight it in a specific color.  I will demonstrate how to use that in the next section.

Handling Loops and Collections

You may not realize it, but any time you are using a jQuery selector you are being returned a collection of elements.  This is the case whether or not there is or an only be one matching element on the page or not.  Selecting an element by class?  You get a collection of the elements that match that class.  Selecting an element by ID?  You still get a collection, but it contains only a single element.

This is important to understand because you will need to code your plugin to handle a collection of elements, rather than just one.  You can do this easily using jQuery’s each function.

return this.each(function () {
     // Adds the highlighter class to the element
     // Note the use of our settings object.
     $(this).addClass(settings.cssClass)
});

Inside of the each function is where we write the code for the core functionality of our plugin.  In this case, we want to add a class to every element that has been selected by the user. This will be how we add the highlight to each block of content.

Notice the use of the settings variable.  That object will contain either the default value or the user specified option value.  No extra work is required.

At this point, if we combine all of our code into a single file, we have a very simplified, but working plugin.  In the final part of the series, I will show you how to create your plugin file and complete all of the necessary steps to use it in an HTML page.

Until then, thanks for reading!

How to Write a jQuery Plugin – Part 1: Structure

One of the most beloved features of jQuery is that it is easily extensible. It requires little overhead to get a basic plugin started and it allows you to build reusable components on top of the power of jQuery. jQuery is already in use on many sites around the web. Creating a plugin allows you or other developers to easily drop your code into a site and start using it quickly.

Over the following three weeks, I will show you how to structure a basic plugin, provide a base set of features and how to package up and use your plugin on a page. Let’s get started this week with the basics of plugin structure.

Basic Structure

(function ( $ ) {
	$.fn.highlight = function (options) {
          // Our plugin code goes here.
	};
}( jQuery ));

The code snippet above outlines the basic structure of a jQuery plugin.  This may look out of the ordinary to you if depending on how you have worked with JavaScript in the past.  Let’s break it down.

Attaching to jQuery

Our plugin begins on line 1 with some strange syntax for declaring a function inside of parentheses.  At the end of the function’s brackets we have the “jQuery” variable in parentheses.  What’s up with that?

This takes advantage of a behavior in JavaScript called Immediately Invoked Function Expressions.  (I won’t go into detail about all that can be done with IIFE, but you can find more information here.)  The purpose of this code is to make sure that your plugin will work side-by-side with other libraries.  There are many libraries that use the $ character to provide an alias or shortcut (jQuery and ASP.NET AJAX are just two of many).

The last line of our plugin immediately passes the jQuery function into our IIFE, allowing us to use the $ alias within the scope of our plugin whether it is in use by another library outside of the plugin or not.

Plugin Declaration

On line 2 of the code above, we declare the $.fn.highlight function.  This is the main entry point of our jQuery plugin.  The function declaration also includes a parameter called “options”, which we will deal with in later parts of the series.

By attaching our function to $.fn, this makes it available anywhere in your application that jQuery is in scope.  You will likely recognize the syntax below that we can now use to call our plugin.

$(function () {
	$('p').highlight();
});

On page load, this will call the highlight function in our plugin for every paragraph tag on the page.  Feel free to try it out.  To run the code properly, you will need to include the plugin code in a file and include jQuery in your HTML file as well.

At this point, we have no code in our main function, so nothing will execute when our plugin is called.  However, in later installments we will add our plugin functionality and work with user defined options.

Thanks for reading!  Feel free to leave a comment or share this post.  Please come back next week for part two!

Getting Started with the Stripes Framework

Stripes is an up-and-coming alternative to Apache Struts for developing web applications using Java. Stripes is very well documented, but leaves something to be desired in their sample projects and jump start information.  I’ve also noticed that while some of the features of Stripes are very extensible, it can be hard to understand what is needed and what isn’t.  I’ve included a quick briefing on some of the common pitfalls below.

ActionResolver

ActionResolver is a component of Stripes that discovers your ActionBeans and maps them to URLs for you to use in your views. One common mistake that occurs when setting up a new Stripes project is not having the ActionResolver properly mapped to the package containing your ActionBeans. This is done in the web.xml configuration file for your project.

<filter>
	<display-name>Stripes Filter</display-name>
	<filter-name>StripesFilter</filter-name>
	<filter-class>net.sourceforge.stripes.controller.StripesFilter</filter-class>
	<init-param>
		<param-name>ActionResolver.Packages</param-name>
		<param-value>{Your ActionBean package name goes here.}</param-value>
	</init-param>
</filter>

If this is not configured properly, you may see errors such as this: “Could not locate an ActionBean that was bound to the URL. Commons reasons for this include mis-matched URLs and forgetting to implement ActionBean in your class.” This can be misleading because the actual cause is related to neither of those reasons.

UrlBinding

One particular difficulty that I had when I started working with Stripes was the usage of UrlBinding annotations. The reason for this is that if your ActionBeans are named properly, then you may never need to use them.

For example, let’s say you have an ActionBean class named LoginActionBean. By default, the ActionResolver will automatically bind this to the Login.action URL without any manual configuration required from you. The only time you ever need to use a UrlBinding is if your URL needs to differ from the automatically generated URL.

This is important to know, because at times the error messages returned by Stripes when it is not configured properly, such as the ones above, can lead you to using a UrlBinding even when you don’t need it.

Using HTML5/Custom Attributes

If you try to use custom attributes with one of the Stripes jump start projects, you will find that using HTML5 or other custom attributes will cause an exception to occur in Stripes.

For example, if you want to add an HTML5 placeholder attribute to a text input that is generated by Stripes, you will not be able to do it with the standard Stripes tag library.  This is also the case with JavaScript event attributes such as “onclick” or “onchange”, and custom attributes prefixed with “data-“.

I found the solution difficult to track down, but all you need to do is use the dynamic tag library provided with Stripes.  To use the Stripes dynamic tag library in your project, just add this taglib reference to the top of your JSP file:

<%@ taglib prefix="stripes" uri="http://stripes.sourceforge.net/stripes-dynattr.tld" %>

You can use the standard Stripes tag library and the dynamic tag library together on the same page.  You just need to set the prefix value in the code above to something different than the prefix value you are using for the standard tag library.  This is actually the recommended usage of the dynamic tags, yet it is not used in any of the current Stripes samples.

Never fear

Stripes is a lightweight framework that is great for developing Java web applications. Not many people are using it, and unfortunately that means that there are not many resources available outside of the documentation. However, the documentation is very detailed and technical. The process of getting up to speed may take longer than usual, but having an alternative framework to available is great for the future of Java on the web.

More information, including samples and comparisons to Struts can be found at http://www.stripesframework.org.

From the Bookmarks Bar – July 12, 2013

I’m going to give something new a shot here.  From the Bookmarks Bar is a weekly round-up of interesting software development related links from around the web.  In general, it’s just a collection of things that I think you may find interesting.  Without further ado, here some favorites From the Bookmarks Bar for this week:

New Programming Jargon

We’ve all run into these issues from time to time.  This article reads like a book of the best programming related jokes.  Smurf Naming Convention is my favorite.

Raspberry Pi Powered Microwave

Disappointed by the lack of features on your microwave?  Why not overhaul it by integrating a Raspberry Pi?

The Visitor Pattern Explained

Many developers have only a brief understanding of the visitor pattern even after using it.  This is a detailed and practical example of the usage and practices of the visitor pattern.

How to Modify Bootstrap Simply and Effectively

Here is a collection of some great Bootstrap mods as well as some tools to easily modify Bootstrap to your tastes.  Want to make your Bootstrap based site look like Facebook or Metro in Windows?  An add-on can make it happen.

Super Mario Bros. 3 Match Game in Javascript

This is a fun one.  A developer has built a slick recreation of the match game from Super Mario Bros. 3, written entirely in JavaScript.  The project is well segmented and structured and is a good example for those looking to learn modern JS.  Source code is available here:  https://github.com/callmehiphop/mario-cards

That’s it for this week.  I’ll be experimenting with From the Bookmarks Bar over the next couple of weeks.  Feel free to leave a comment and let me know what you think.  Thanks for reading!

Using jQuery 2.0 and supporting IE 8?

jQuery 2 has been released and the most talked about addition is actually the removal of a feature.  Notably, support for Internet Explorer versions 6, 7 and 8.  The jQuery blog notes that Android 2.x browsers are the next on the chopping block.  You may think that the new features in jQuery 2.0 would have to be substantial to encourage developers to use it and leave IE 8 behind, but at this point the APIs of jQuery 1.9 and 2.0 are identical.  In other words, they provide the exact same set of features, they just support different browsers.  In addition, both the 1.x and 2.x versions of jQuery will continue to be supported side-by-side for the foreseeable future.  jQuery 1.10 is will be released in the coming months with bug fixes from the 2.0 cycle.

The only noted benefit of the change to jQuery 2.0 is a decrease in size of the JavaScript file from 93kb to 83kb.  Some developers may see this change as negligible and continue to use jQuery 1.9, where those who support systems with much higher traffic may see a benefit in the reduced file size.  Why choose when you can serve the larger file to the browsers that need it and save the bandwidth for those that do not?

How To

Through the use of conditional comments, a site can use jQuery 1.9 to support just the IE 8 and lower users, and use jQuery 2.0 for all others, taking full advantage of the bandwidth savings when possible.  Conditional comments are commonly used to create IE-only stylesheets for those pesky quirks that only seem to occur in Internet Explorer.  However, there is nothing preventing them from being used for JavaScript as well.  See the following code example:

<!--[if lt IE 9]><!-->
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<!--<![endif]-->
<!--[if gte IE 9]><!-->
<script src="http://code.jquery.com/jquery-2.0.0.min.js"></script>
<!--<![endif]-->

The first line checks to see if the requesting browser is lower than IE 9.  If it is, then we load jQuery 1.9.  The second line checks if it is greater than or equal to IE 9.  If it is, then we load jQuery 2.0.  Since the 1.9 and 2.0 APIs are identical, the rest of the calls to jQuery on the page will work properly with no additional changes required.  Take note that there are some additional comment tags included to make these checks visible to non-IE browsers such as Chrome or Firefox.

Conclusion

Many developers considered jQuery’s support for a wide range of browsers to be a significant benefit for choosing it over other alternatives.  Often a project’s targeted audience or the client themselves will determine what browsers need to be supported, leaving the developer out of the decision entirely.  With the newest version shifting from that support, the door may be left open for a competitor product to gain usage in the developer community.  At this point, there is no cause for alarm since the jQuery 1.x line will continue to be supported in the future.  However, if jQuery 2.0 begins to add features that are not available in 1, developers may demand a version of jQuery 2 with support for older browsers, or just move on to something new.  Only time will tell.

Pitfalls of JavaScript Game Development with HTML5

A few months back I completed development on a promotional game for a client that I wrote entirely in JavaScript using the HTML5 canvas. The game was similar in nature to Breakout but instead of deflecting the ball with the pad at the bottom of the screen, the player needed to catch objects falling at random from the top of the screen. The requirements were that it needed to run smoothly in all modern browsers and on touch based devices such as phones and tablets. The iPad was specified as a target device, so using Flash was out of the question.  With that known I set my sights on an HTML5 canvas based game.

The game play was very simple, so I wrote the game engine from scratch. The core game was easy to implement, but reinventing the wheel by not using an existing JavaScript game engine presented some issues with cross-browser compatibility.  Here are some of the issues I ran into and how I either got around them, or didn’t:

Graphics and Presentation

The client was keen on supporting Internet Explorer 7, if possible, but deemed supporting the iPad to be more important.  I looked around and stumbled upon a plugin called explorercanvas, which allowed the usage of the canvas element within older versions of IE.  To my surprise, I dropped the script in and everything worked properly.

Controls

After some trial and error, I ended up relying on jQuery to attach the events for player control.  Each of the browsers handle events differently and expose different values for mouse coordinates.  jQuery exposes the same values no matter which browser you are running, so that you can be sure of whether will be receiving an x and y value in reference to the entire window or just the canvas’ bounds.  Capturing key presses are also slightly different among browsers, so jQuery can help with that as well.

Touch controls are an entirely different monster.  At the moment, jQuery does not support binding to touch events.  Luckily, at this point most mobile browsers support the same spec for adding event listeners to touch events for touchstart, touchend, touchmove and touchcancel.

Audio

Sound effects and music are a piece of cake to implement with HTML5 audio.  Preloading and playing sounds on cue from script takes only a single function call.  Unfortunately, this is where older browsers like Internet Explorer 7 fall short.  The only way to play sound without using Flash in these browsers is to append an embed tag on the page using JavaScript when the sound needs to be played.  This presents two potential problems.  First, the embed tag plays the sound using the codecs that the user has installed.  If they have no codec to play sounds in your format of choice, you’re out of luck.  Second, the sound must load the first time it is played, so it is out of sync.  I occasionally ran into issues with syncing sound even once it had loaded.

Conclusion

This particular project was simple, so it didn’t suffer from being written from scratch, but if I had to do it over, I would choose one of the JavaScript frameworks already available.  The best choices right now seem to be LimeJS and ImpactJS.  Though ImpactJS provides additional tools for profiling and level editing, it’ll cost you, where LimeJS is free.  The popular iOS game development framework Cocos2D now has a flavor available for JavaScript and HTML5 as well.

As a developer who is against reinventing the wheel whenever possible, these frameworks provide simple solutions for all of the common problems with developing games using HTML5 canvas and JavaScript.  They can help separate your game from a small game to a full fledged experience that user forgets they are playing in their browser.