HTML5 Games Development by Example Beginner's Guide Create six fun games using the latest HTML5, Canvas, CSS, and JavaScript techniques Makzan BIRMINGHAM - MUMBAI
HTML5 Games Development by Example Beginner's Guide Copyright 2011 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: August 2011 Production Reference: 1180811 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-849691-26-0 www.packtpub.com Cover Image by Girish Suryawanshi (girish.suryawanshi@gmail.com)
Credits Author Makzan Project Coordinator Zainab Bagasrawala Reviewers Matteo Ferretti Henk Jurriens William Malone Acquisition Editor David Barnes Development Editor Neha Mallik Technical Editors Pallavi Kachare Azharuddin Sheikh Proofreader Joanna McMahon Indexer Rekha Nair Graphics Geetanjali Sawant Production Coordinators Melwyn D'sa Adline Swetha Jesuthas Cover Work Melwyn D'sa Copy Editor Neha Shetty
About the Author Makzan is the founder of 42games Limited. He has been designing games since he was a child. He likes to see how the well-designed interactions in his games can trigger the emotions and influence the player. He believes that games should let a player share joyful times with friends. Therefore, his favorite game type is multiplayer casual games. Makzan also wrote a book named Flash Multiplayer Virtual World. It is about developing a virtual world to play with friends in real time with Adobe Flash and socket server. I would like to thank the entire team from Packt Publishing. The book would not have been possible without the help from all the editors and proofreaders. I thank all the reviewers for providing useful comments from which I have learned a lot. I thank my family for giving me support during the book writing process.
About the Reviewers Matteo Ferretti is a software engineer, an amateur comic-book artist, and an occasional graphic designer, who was drawn into software development since he played his first video game. He fell in love with JavaScript at the end of the 20th century, and he still loves it with the same passion. Currently he is working for Mozilla, after more than two years in TomTom as a Senior Software Engineer and Tech Leader. I wish to thank my love, Elisa, for her patience and understanding. I also want to thank my parents, for their continuous support throughout my whole life. Henk Jurriens is a software developer and developer evangelist, experienced with Java, Groovy and Grails, and HTML5. Henk is passionate about new technologies and loves to talk about it, and so gives different presentations about HTML5, Linked Data, and Groovy and Grails. In addition, Henk founded an HTML5 User Group to promote and share knowledge about HTML5. During the year, different meetups are organized. Together with the Google Technology User Group, he organized for example, a HTML5 Hackathon. Last year, Henk also helped with a HTML5 Game Jam and there he saw the potential of HTML5 Games and this was the reason for him to review this book. With the help of this book, great HTML5 games can be built! William Malone is a software developer specializing in dialects of ECMAScript (ActionScript and JavaScript). He has written many articles about Flash and HTML5 which are available at http://www.williammalone.com.
www.packtpub.com Support files, ebooks, discount offers and more You might want to visit www.packtpub.com for support files and downloads related to your book. Did you know that Packt offers ebook versions of every book published, with PDF and epub files available? You can upgrade to the ebook version at www.packtpub.com and as a print book customer, you are entitled to a discount on the ebook copy. Get in touch with us at service@ packtpub.com for more details. At www.packtpub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and ebooks. http://packtlib.packtpub.com Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books. Why Subscribe? Fully searchable across every book published by Packt Copy and paste, print and bookmark content On demand and accessible via web browser Free Access for Packt account holders If you have an account with Packt at www.packtpub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.
Table of Contents Preface 1 Chapter 1: Introducing HTML5 Games 7 Discovering new features in HTML5 8 Canvas 8 Audio 8 GeoLocation 8 WebGL 9 WebSocket 10 Local Storage 10 Offline application 11 Discovering new features in CSS3 11 CSS3 transition 12 CSS3 transform 13 CSS3 animation 14 Learning more detail of new HTML5 and CSS3 features 15 The benefit of creating HTML5 games 15 No third-party plugin required 16 Supporting ios devices without plugin 16 Breaking the boundary of usual browser games 16 Building HTML5 games 18 What others are playing with HTML5 18 Matching game 18 Sinuous 19 Asteroid-styled bookmarklet 19 Quake 2 20 RumpeTroll 21 Scrabb.ly 21 Aves Engine 22
Table of Contents Browsing more HTML5 games 22 What we are going to create in this book 23 Summary 24 Chapter 2: Getting Started with DOM-based Game Development 25 Preparing the development environment 26 Preparing the HTML documents for a DOM-based game 26 Time for action Installing the jquery library 27 New HTML5 doctype 28 Header and footer 29 Best practice to place the JavaScript code 29 Running our code after the page is ready 29 Setting up the Ping Pong game elements 30 Time for action Placing Ping Pong game elements in DOM 30 Introducing jquery 32 Understanding basic jquery selectors 33 Understanding the jquery CSS function 34 Benefits of using jquery 35 Manipulating game elements in DOM with jquery 35 Time for action Changing position of elements with jquery 35 Understanding the behavior of absolute position 36 Getting a keyboard input from players 37 Time for action Moving DOM objects by a keyboard input 38 Understanding a key code 39 Making constants more readable 40 Converting strings to numbers with parseint function 40 Executing JavaScript expressions directly in the Console panel 42 Checking the console window 42 Supporting multiple keyboard input from players 43 Time for action Listening to keyboard input with another approach 43 Declaring global variables in a better way 45 Creating a JavaScript timer with setinterval function 46 Understanding Game Loop 46 Moving a DOM object with JavaScript Interval 47 Time for action Moving the ball with JavaScript Interval 47 Beginning collision detection 49 Time for action Hitting the ball with the paddles 50 Showing text dynamically in HTML 53 Time for action Showing the score of both players 53 Summary 56 [ ii ]
[ iii ] Table of Contents Chapter 3: Building a Memory Matching Game in CSS3 57 Moving game objects with CSS3 transition 57 Time for action Moving a playing card around 58 2D transforms functions 61 3D transforms functions 61 Tweening the styles by using CSS3 transition 62 Creating a card-flipping effect 64 Time for action Flipping a card with CSS3 64 Toggling class with jquery toggleclass function 66 Controlling the visibility of overlapped elements by z-index 67 Introducing CSS perspective property 68 Introducing backface-visibility 69 Creating a card matching memory game 70 Downloading the sprites sheet of playing cards 70 Setting up the game environment 71 Time for action Preparing the card matching game 71 Cloning DOM elements with jquery 77 Selecting the first child of an element in jquery by using child filters 77 Vertically aligning a DOM element 77 Using CSS sprite with a background position 78 Adding game logic to the matching game 79 Time for action Adding game logic to the matching game 80 Executing code after CSS transition ended 83 Delaying code execution on flipping cards 83 Randomizing an array in JavaScript 83 Storing internal custom data with an HTML5 custom data attribute 84 Accessing custom data attribute with jquery 85 Making other playing card games 87 Embedding web fonts into our game 87 Time for action Embedding a font from Google Font Directory 88 Choosing different font delivery services 90 Summary 91 Chapter 4: Building the Untangle Game with Canvas and Drawing API 93 Introducing the HTML5 Canvas Element 94 Drawing a circle in canvas 95 Time for action Drawing color circles on canvas 95 Putting fallback content when the web browser does not support canvas 97 Drawing circles and shapes with canvas arc function 98 Converting degree to radians 98 Time for action Drawing different arcs with arc function 99 Executing the path drawing in canvas 102