Game elements

There were nine HTML5 elements used in this game. Each will be explained within its main category of either HTML, CSS, or JavaScript. The game itself is composed of roughly 15 elements, as depicted in the illustrations as follows:

Game elements

The main game screen, with a subtle options widget as part of it.

After a game is finished, whether or not the player wins the game, a score board is shown, where the player is given the opportunity to enter his or her name as well as start a new game.

Game elements

The preceding screenshot shows a messaging widget to indicate that the player has won or lost, as well as a leaderboard widget.

In order for us to easily identify each of the major visual game components, we'll list them as follows:

The options widget

This widget allows the player to select a preset difficulty level. Selecting a harder difficulty level will make the enemy move faster across his track towards the boat. Additionally, we could have made it so that the phrases that the player would need to type would be harder or easier based on the difficulty setting. However, we have left this implementation detail as an exercise to the reader.

The game title

This text based widget simply displays the main title of the game. Note that the type face used there is pure text (no images), using a custom web font. Its only purpose is to decorate the user interface.

Boat

This animated widget serves the purpose of strengthening the user interface by helping to tell the story of the game. The boat is a simple HTML element (div), with a background image representing the boat. The animated path that the boat follows is done strictly in CSS, and is managed completely by the browser.

Sky

This section of HTML is used to encapsulate all the elements located on the top half of the user interface, as well as to make it possible to animate the sky. As the game goes on, the color of the sky changes subtly, so as to emulate the setting and rising of the sun.

Waves

There is a section of HTML classed as ocean, which is a section that encapsulates the area where the waves are stored. Each wave (there are two in use in this case) is a div element with a width of 100 percent, and a background image that represents the wave. This background image is repeated throughout the entire width of the div element, and is animated through CSS in order to give the illusion of motion, following a pattern of waves in the ocean.

Tracks

This widget is a section of HTML that encapsulates the individual track widgets, along with the player that uses that track.

Players

Each of those icons represent the individual players in this game. To keep things as simple as possible, there are only two players in the game: you (the hero), and Mr. Snooty McSnootington (the enemy). Additionally, we could have very easily added functionality to the options widget to allow the player to choose specific icons for both, the hero and the enemy, since the code that controls what icons are used is a simple CSS class that can be added to or removed from the icon objects.

The main container

This section of HTML holds the elements that control the game, which is everything below the sky widget.

Words to write

Here is where we display the words that the user must type when the game starts. Behind the scenes, this is a simple block-level HTML element, whose only purpose is just to display a few words.

Words written

Although, this widget is identical to the words to write widget (with slightly different styling, of course), this widget is a bit more dynamic, as it will respond to user actions. When a user presses a key on the keyboard, that input will be displayed there. If the character typed matches the expected character based on whatever is shown in the Words to write widget, then the character is displayed in white. If the character is incorrect, it'll be displayed in red, with a line through it, indicating very strongly that a mistake was made. The user can use the Backspace key to delete any or all characters displayed in this widget. As each correct character is typed in, the hero will move to the right proportionally to the percentage of characters entered, relative to the total amount to be typed.

The message container

This section of HTML is displayed atop a semitransparent element to give the appearance of an overlay box. The widget is primarily meant to be a generic communication tool, through which we can inform the player of events, such as letting them know that the game is over, or that he or she won or lost the game. Additionally, we have added four other elements to it in order to make the game more engaging.

The message title

Very similar in styling and purpose to main game title widget, this element simply notifies the user of the contents of the rest of the message container widget.

The new champion form

The idea behind this form is to simulate those old-school leaderboards used in old arcade games. Once you win a game against Mr. Snooty McSnootington, you are given the opportunity to enter your name and e-mail address to be shown in the leaderboard as in the following screenshot. Of course, that information is symbolic, and only serves the purpose of illustrating how we can use HTML5's web forms. The information generated by the form is not saved anywhere, and thus, it goes away after each page refresh (or when the game is closed or navigated away from). Again, it would be a trivial task to either email the contents of that form, save it to a backend server, or even stored it locally in the browser, through any one of the many persistence or storage APIs that we'll discuss in Chapter 4, Using HTML5 to Catch a snake, later in the book.

Leaderboard

Any data entered in the new champion form (provided that the data entered is valid) is displayed here. The number next to each name simply shows the order that each name was entered. The asterisk to the right of the name indicates the difficulty level that the game was played (level 1—easy; in this particular case). For a more engaging experience, we could have kept track of how long it took the player to complete the game, how many mistakes were made, or somehow calculate an overall score and display it here. The reason we chose a full name and an email address was to show how to perform form validation in HTML5. This alone is probably the most powerful and exciting feature of HTML5 used in this game. What used to take developers hundreds of lines of code, and often lots of repeated code, now only takes a couple of HTML attributes that the browser enforces.

Game controls

Finally, the message container widget includes controls that allows the player to start a new game.

Note

In order to make the code more concise and easier to explain, we'll be aiming at less portable code, where the only requirement will be that the code runs properly in at least one browser.

Most of the APIs used are indeed very portable (meaning that the code executes the same in most major browsers), but certainly not all of it, especially any experimental CSS APIs that require vendor prefixes. For maximum compatibility with the following examples, I recommend you use the latest version of Google Chrome or Google Chromium, or at least any webkit-based browser, such as Apple Safari.

The reason for this approach, first and foremost, is to simplify the teaching process. There's no need to explain a given feature, then show code example that is 99 percent identical, but differs only in the first part of the feature name, which is the vendor name. The reasoning behind selecting webkit as the browser engine of choice is also very simple; we had to choose something, so why not webkit? Besides, Google Chrome and Apple Safari have great market penetration, as well as an incredible set of tools to help us in the development process (such as Google Chrome's Developer Tools).

Finally, the nine HTML5 elements used in the game, along with their corresponding category:

HTML

Both of the HTML features used in this game can be used in JavaScript or by the browser directly. The web form elements and attributes add great functionality to the browser out of the box, while the data attributes are more meaningful when tied to the JavaScript. In the game of our Typography Game, we have built these elements within a context that made sense, but we could certainly have used other techniques (such as storing the data represented by the data attributes strictly in code), or used the elements and attributes we did use in different ways.

The web form

The new form API added in HTML5 is one of the most visible additions to the language. With it you have access to 13 new input types, as well as countless new attributes that make form development fast, fun, and fascinating. Most of the additions will probably look familiar to you visually, since the effects that they add natively to the browser had already been done for a long time. These effects include things such as placeholder text, form validation, auto focusing fields, and so on so forth.

Two of the 13 new input types were used in the game, along with a handful of attributes for each of them, including form validation and field placeholders. Following is a brief explanation of how these elements were used in the game. An in-depth discussion of how they work and how to use them is found the the next section.

Range input

The new range input type is a slider that allows the user to select a value by moving the slider horizontally. In the game, we used the range input as a means to select a difficulty level. The range specified in this game is from 1 to 3, with 1 being the easiest difficulty level and 3 being the toughest.

Range input

The container that holds the input type range uses CSS to toggle the options menu and fade it out when not in use.

Email input

The email input type looks exactly the same as the old text input type, but with a few benefits. First, when used in a mobile device, the input type hints to the operating system what kind of information it expects, in which case the operating system can display a special keyboard to the user. For example, if the user attempts to enter data into a number input type, where only numbers are allowed, a mobile operating system can display a keyboard that only has numbers. In the case of the email type, the keyboard displayed is normally one that includes the @ symbol which makes it easier and more convenient for the user to enter the information into the web form.

The second benefit of using the email input type, which is also a benefit to desktop users, is that the browser itself can validate the data entered by the user. If the field is set to be validated and the data in the field does not match the basic format of an email address, the browser will tell the user that there is a problem and the form will not be submitted.

In the game, we use this feature whenever a player wins, by asking the user to enter his or her full name and email address. That information is used in a leaderboard, like you have probably seen in older games. While the user is not forced to enter any of the information asked for in the form, if the user does choose to input any information the data will be validated automatically by the browser.

The exciting thing about automatic form validation is that you can customize your form through the HTML attributes included, making only required fields validated, what the error message says, and so on so forth. Also, even if the user disables JavaScript functionality in the browser the form will still be validated and handled by the browser. Of course, as you well know, one of the main rules about taking input from the user is that you should never trust the user and always validate and sanitize any, and all user input in the server as well.

Email input

If no data is entered or is in the wrong format, the browser will tell you about it and keep the form from being submitted.

Data attributes

As part of the effort, for more semantic document structure, HTML5 allows us to create our own, custom element attributes. Before HTML5, most browsers simply ignored element attributes that it did not understand (for example, a custom attribute made specially for one's application) but the downsides to this practice included the fact that the document could not be validated, the behavior was somewhat unpredictable, and there was a chance that a new release of the language introduced attributes of the same name, thus making your old custom attributes invalid. Now, we can safely create custom attributes for elements and none of the downsides just mentioned would apply.

In our game, we used data attributes to do two things, namely to specify the minimum speed that a player can move across the track and to specify that a generic button should trigger a new game (so that any button with that data attribute did not need any extra logic within JavaScript in order to act like a special button).

CSS

Since this game was intended to show off the more visual aspects of HTML5, we focused most of our efforts in making the interface of the game a real eye-candy. Since CSS is all about that visual presentation, most of the featured employed fall under this category.

Web fonts

Prior to HTML5's ability to handle custom fonts, web designers and developers were limited to a handful of type faces that could be used in a website or web application. Over time, there were a few solutions developed to solve this problem, but none were particularly impressive and most (if not all) broke some of the browser's functionality. For example, one common technique to display custom text involved the use of JavaScript to dynamically replace each character in a string with an actual image of that character using the custom font. The problems with this approach included the fact that one needed to create and manage all of those images. The user had to download all of those images, and worst of all, the resulting text could not be selected, copied, resized, and the color could not be changed.

Now we can simply specify the name of a font, along with the actual font file, which the browser can download if the user's operating system doesn't have that font installed and use just as any other font.

In the game, we use three different custom fonts to create just the right visual effect and make the texts in the game match the desired visual theme. The three fonts used are open source fonts, which can be downloaded from the internet and used for free. The fonts used were Lemon, Mystery Quest, and Fredericka the Great. Amazing names, don't you agree?

Web fonts

Prior to looking for some fonts for the game, I had no idea that these fonts existed. Best of all, it only took me a couple of minutes to go through a large collection of open source fonts (from Google's Web Fonts tool) and find just what I wanted.

Since a font file is an external asset just like anything else that is downloaded from the server, there is a period of time between the time the browser starts downloading a font file and the time when the page is ready to be rendered. Different browsers handle this situation differently. For example, webkit hides the text until the font asset is ready. Other browsers may render the text with a fallback or default font until the web font file is ready, then swap the fonts and re-render the text.

Transitions

A CSS transition attribute tells the browser what attributes it applies to and how long the transition should last. Once those properties change, the browser will interpolate the beginning and end states and generate a very smooth transition for the duration specified. Of course, this can only be applied to attributes represented by some numerical value, such as font size, background color (represented by either an RGB or HSL value, or a hexadecimal number, all of which can be converted to percentages), element position, and so on. Values that do not get smoothly interpolated in CSS transitions include font-family, background images, or any other attribute that don't have in-between values, such as display block and display none.

In the game, the only uses of transition were with the options menu, the message container, and in moving the players across the tracks. The options menu is set to be pushed off the left side of the screen and the main icon that represents it is 75 percent transparency. Once the user hovers the mouse over that icon, it transitions to zero percent transparency (fully visible) and the rest of the menu transitions onto its left side to move to the right until its left edge snaps to the left edge of the browser.

The message container uses a similar effect, and that it is always positioned at the top of the screen, its width being 100 percent the window viewport and its height is set to zero by default (when the container is closed). When we want to display a message to the user, add the CSS class open to the container widget which sets the container's height to 100 percent, thus triggering a smooth transition that simulates a slide-in effect.

Finally, we used transitions to move the players from right to left within the tracks to which they are each bound. This was a very easy task to accomplish, even though the hero and the enemy are controlled slightly different. The way the enemy moves is simple: at every tick of the game timer we increment the enemy's horizontal position (by changing its left style attribute) by whatever value is set in its data-speed data attribute. The smooth transition between the two points is handled by the browser. The way the hero moves is similar, with the exception that the data-speed is always set to zero (otherwise it'd be moving automatically without the user having to type anything) and at each key press we check whether the character typed in was what was expected, in which case we advance the hero a percentage of the way to the end of the track, which is relative to the percentage of characters typed in properly and relative to the total amount of characters. For example, if the user correctly typed in the tenth character of a phrase that has 100 characters, then we move the hero 10 percent of the way across its track. Both, the hero and the enemy, have checks in place so that they can't be moved beyond the width of their respective tracks.

Animations

Probably the most powerful feature of CSS3, the animation attribute, allows for named keyframe animation very similar to the formerly popular Adobe Flash. The way it works is incredibly simple: you create an animation sequence, give it a name, and specify one or more CSS attributes to be applied at each keyframe. Each keyframe represents a moment in time when those attributes should be added to whatever element you associate with that animation sequence. Then, every moment in time between two keyframes are smoothly interpolated by the browser and the illusion of animation is achieved.

In the game, we use animations to give life to the ocean waves, to move the boat in its path, and to make the sky fade darker and lighter with the passing of time, thus simulating the rising and setting of the sun. Although this may seem like a complicated task, animating elements is so easy that the main limitation you're likely to run into may be creativity. If you're somewhat familiar with CSS and how to use it to apply various styles to elements, then learning and using the animation API should be a natural next step.

Animations

Each animated object was nothing more than a div element with a background image set to it. The waves' background image was set to repeat about the x axis, whereas the boat's background image was set to no-repeat. The boat's width and height was set to match the image it represented, whereas the waves had a different height set for each of them (the wave positioned behind everything was a bit taller so that it could be seen behind the other wave), but with a width of 100 percent, so that it always fills the width of the monitor viewing the app, no matter how wide that monitor is. At the end of this animation cycle, the objects follow that same path, but in reverse, making the animation seem continuous and always smooth.

The easiest element to animate was the sky, since it only had two keyframes. At the first keyframe, the div element that represented the sky was set to have a light blue color for its background. The last keyframe changed that background color to a slightly darker blue. For a more dramatic effect, we could have had this last keyframe define a very dark color for the background. For an even more drastic effect representing this night fall, we could also have added another div on top of this sky element, with its background image being a transparent image with white dots scattered about it. Each dot would represent a star. Then, at the same pace that the sky gets darker, we set the opacity of this element to become more visible (less transparent), so that it animates from fully transparent to fully opaque. The final effect would be that as the sky gets darker, then stars would appear.

The boat was animated with three keyframes: the first placed it at some position slightly above the waves, the second moved it to the right and up, and the third keyframe moved it significantly higher, and a bit to the left. The trick to making the animation between these points seem somewhat natural, and more like something would move on the ocean in real life, is to make the distance the object moves between two different keyframes different. For example, the horizontal distance the boat moves between the first and second keyframe is different than the horizontal displacement used between the second and third keyframes. The vertical displacement between those keyframes are even more drastic. If the distances were all the same, our eye would get used to the same familiar pattern of motion, and the animation would soon appear too repetitive and uninteresting.

Animating the waves was equally easy. Although there were two sets of waves, they both use the same animation set. The only difference is that the set of waves positioned behind the other (the back wave) was set to move slower, so that it looked like it was farther away, and the animations didn't seem to be the same.

All that was animated in these wave elements (remember, a wave element is just a div with a repeating background image) was the position of the background image. The div elements themselves were always static and absolutely positioned atop each other. Since the elements were transparent wherever their background images were transparent, we were able to apply a background color to the element holding all three of these elements (both waves and the boat), which we set to be the sky element, which animated the background color.

Although the final result looks fun and slightly complex, the work required to put this sort of thing together is really no more complicated or difficult than setting up any other design using plain CSS, especially because this is nothing more than plain old CSS.

Note

At the time of this writing, there were a handful of tools aimed at helping developers create and manage keyframe animations. While many of these tools were free and many are completely cloud-based (written using HTML5 technologies), if you're looking for an enterprise level tool to help you build professional animations truly similar to what we're used to seeing with Adobe Flash, you'll need to invest in some cash in more advanced and fine tuned tools. Although some of these tools may not be the best option for a developer on a budget (or one with no budget at all), their quality and power are normally orders of magnitude beyond whatever any of the free tools can provide.

If you're only developing for fun, or for the learning experience, the plethora of free tools available online should be more than enough to get you going with CSS3 keyframe animations. However, if your goal is to build high-end applications and you need the high precision and control over the animations, then a professional tool might be well worth your investment.

One particularly popular free web-based CSS animation generator can be found at http://www.css3maker.com/. On the other hand, Adobe makes a terrific product called Adobe Edge Animate, which can be purchased at http://html.adobe.com/edge/animate/.

The text shadows

This new text attribute in CSS allows you to simulate a shadow effect around text. Behind the scenes, what the browser really does is create a copy of the text that the shadow is being applied to, then displace it behind the original text based on the values you specify as the vertical and horizontal offset. You can also tell the browser how much to blur this "shadow" version of the text by specifying a values between zero and whatever integer value you desire. After a point, depending on the size of the original text, the blur is so high that the text is virtually invisible, so supplying very large numbers can be counter productive.

The only instance in the game where text shadow is used is in the message container's title. Since the rest of the user interface for the game used pretty flat graphics with very subtle or no gradients at all, I thought I'd use text shadows to add a solid, lighter shadow to give continuation to the theme of flat, single dimensional graphics.

The text shadows

The CSS3 text shadow API allows you to specify an arbitrary number of displaced and blurred copies of a text string.

The box shadows

Similar to text shadows, box shadows place one or more boxes behind a particular element, with a vertical and horizontal offset specified as parameters, with a third parameter being the amount of blur to be applied to the shadow. You can specify solid colors or use the optional alpha channel in order to add varying levels of opacity to it. Alternatively, the shadow can be applied to the inside of the container to which it is bound. Note that any box shadow applied to elements, if they're placed behind the box, are placed outside the border, if one is available, ignoring any margin the element may have. Shadows placed inside an element are placed just inside the border, if one is present, ignoring any padding added to the element.

In the game, there are two instances of a CSS box shadow. One shows off the traditional shadow behind an element, and is applied to the message container. The other instance of box shadow in the game is applied to the tracks that hold each player. In this case, the shadow is intended to convey the effect that the tracks are pressed in into the page, which is done by using the attribute that places the shadow inside the box. If the shadow is placed outside the box, the effect given is that of the box being stacked over the page.

The box shadows

The white line on the bottom of each track is just a bottom border, but the same effect could have been accomplished by adding a second box shadow.

The border radius

Before the border radius property was available, the same effect it provides could be achieved by positioning images of rounded corners to the corners of elements. This was a tedious task to do and the final effect was rarely as impressive as intended. With the CSS3 border radius property, we can apply an arbitrary amount of roundness to one or more corners of a container element.

Note

Keep in mind that, although it is possible to make a container element look completely round by specifying a border radius value to all four corners large enough proportional to each side's length, the element is still a rectangle to the browser. In other words, if you float two or more elements that have been made to look round through CSS, they will behave like rectangles and not circles.

The flow of elements and text in HTML5 is still rectangular based, although there are experimental APIs that allow us to specify arbitrary shapes through which text flows. For more information about these particular CSS APIs (called regions and exclusions), see Chapter 6, Adding Features to Your Games.

There was only one use of CSS border radius in the game, which was on the right side of the navigation options widget. The API allows us to specify which specific side to apply a border radius to, and to demonstrate this feature, only two of the four sides of the container were rounded.

The player icons could have been more HTML5-ish instead of just being a transparent image applied to the background of the element. One possibility could be to have each icon be a rectangular image, which we could apply to the background of the container representing each player, then we could have used border radius to make the element look completely circular. An optional box shadow could also have been added to create the same shadow effect achieved by the photo editing software used to create the images. One benefit of using this technique would be that the native effects would scale much better, meaning that if you zoom the page in or out, the image will eventually look distorted and pixelated, whereas any border radius, box shadow, or borders added to the element would always look smooth and fresh.

JavaScript

Although the logic that drives this game is fairly simple, and quite a bit limited, there is still a decent amount of JavaScript code in order to make the game work. Since we're trying to focus on HTML5 features, we'll only look at one particular API used in the code that can more or less be considered HTML5. This is the selectors API , which was first drafted by the W3C back on May of 2006.

Query selectors

If you have been doing any web development at all in the last several years, you've certainly heard or, used, and have fallen in love with the popular JavaScript library jQuery. Among its many powerful features, one of jQuery's most useful tools is its amazing DOM selector API, which allows you to retrieve the DOM elements by simply using CSS selectors and pseudo selectors, as opposed to using the limited document.getElementById(), document.getElementsByClassName(), and document.getElementsByName() methods, among other equally limited ones.

The good news is that this powerful nodes selector API is now all native to modern browsers. Since the feature is native to the browser, it is much faster and more stable. Furthermore, since the feature is native to the browser, there is no need to import a library to handle the task.

This game, as well as all the others described in this book, uses the new selectors API level 1. Since there are no visual elements that can be seen form query selectors, we'll deepen the discussion about its usage in the next section, where we'll also take a look at some code examples.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.83.199