jQuery Game Development Essentials
()
About this ebook
Related to jQuery Game Development Essentials
Related ebooks
Instant HTML5 2D Platformer Rating: 0 out of 5 stars0 ratingsHTML5 for Flash Developers Rating: 5 out of 5 stars5/5Meteor Design Patterns Rating: 0 out of 5 stars0 ratingsjQuery Mobile Web Development Essentials - Third Edition Rating: 0 out of 5 stars0 ratingsLearning Behavior-driven Development with JavaScript Rating: 5 out of 5 stars5/5JavaScript Projects for Kids Rating: 0 out of 5 stars0 ratingsCRYENGINE Game Development Blueprints Rating: 0 out of 5 stars0 ratingsOpenCart Theme and Module Development Rating: 0 out of 5 stars0 ratingsGradle Dependency Management Rating: 0 out of 5 stars0 ratingsSFML Game Development By Example Rating: 0 out of 5 stars0 ratingsFlex 3 with Java Rating: 0 out of 5 stars0 ratingsCocos2D Game Development Essentials Rating: 0 out of 5 stars0 ratingsLearning AWS Lumberyard Game Development Rating: 0 out of 5 stars0 ratingsDeveloping Windows Store Apps with HTML5 and JavaScript Rating: 0 out of 5 stars0 ratingsResponsive Media in HTML5 Rating: 0 out of 5 stars0 ratingsDeveloping Turn-Based Multiplayer Games: with GameMaker Studio 2 and NodeJS Rating: 0 out of 5 stars0 ratingsGetting Started with Meteor.js JavaScript Framework - Second Edition Rating: 0 out of 5 stars0 ratingsCodeIgniter Web Application Blueprints Rating: 0 out of 5 stars0 ratingsAndroid Game Programming by Example Rating: 0 out of 5 stars0 ratingsSDL Game Development Rating: 0 out of 5 stars0 ratingsObjective-C Memory Management Essentials Rating: 0 out of 5 stars0 ratingsLearning Android Game Development Rating: 0 out of 5 stars0 ratingsSwift 2 By Example Rating: 5 out of 5 stars5/5Application Development with Swift Rating: 0 out of 5 stars0 ratingsOracle Application Express 4.0 with Ext JS Rating: 0 out of 5 stars0 ratingsMastering LibGDX Game Development Rating: 0 out of 5 stars0 ratingsNW.js Essentials Rating: 0 out of 5 stars0 ratingsLibgdx Cross-platform Game Development Cookbook Rating: 0 out of 5 stars0 ratingsCryENGINE Game Programming with C++, C#, and Lua Rating: 0 out of 5 stars0 ratingsLearning LibGDX Game Development - Second Edition Rating: 0 out of 5 stars0 ratings
Programming For You
Game Development with Unreal Engine 5: Learn the Basics of Game Development in Unreal Engine 5 (English Edition) Rating: 0 out of 5 stars0 ratingsPython Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Python Machine Learning By Example Rating: 4 out of 5 stars4/5Java for Beginners: A Crash Course to Learn Java Programming in 1 Week Rating: 5 out of 5 stars5/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5HTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsGrokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Learn JavaScript in 24 Hours Rating: 3 out of 5 stars3/5Problem Solving in C and Python: Programming Exercises and Solutions, Part 1 Rating: 5 out of 5 stars5/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5C# Programming from Zero to Proficiency (Beginner): C# from Zero to Proficiency, #2 Rating: 0 out of 5 stars0 ratingsPython Data Structures and Algorithms Rating: 5 out of 5 stars5/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Programming Arduino: Getting Started with Sketches Rating: 4 out of 5 stars4/5The Unofficial Guide to Open Broadcaster Software: OBS: The World's Most Popular Free Live-Streaming Application Rating: 0 out of 5 stars0 ratings
Reviews for jQuery Game Development Essentials
0 ratings0 reviews
Book preview
jQuery Game Development Essentials - Selim Arsever
Table of Contents
jQuery Game Development Essentials
Credits
About the Author
About the Reviewer
www.PacktPub.com
Support files, eBooks, discount offers and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. jQuery for Games
The way of jQuery
Chaining
Polymorphism
Moving things around
Chaining animations
Managing the queue
.stop()
.clearQueue()
.dequeue()
.delay()
Other usages of queues
Handling of events
.bind()
.delegate()
Removing event handlers
jQuery 1.7
Associating data with DOM elements
Manipulating the DOM
.append()
.prepend()
.html()
.remove()
.detach()
Stay curious my friend!
Summary
2. Creating Our First Game
How does this book work?
Let's get serious – the game
Learning the basics
Framework
Sprites
Implementing animations
Adding animations to our framework
Moving sprites around
Preloading
Initializing the game
Main loop
Main loop implementation
Collision detection
Summary
3. Better, Faster, but not Harder
Intervals and timeouts
One interval to rule them all
Code
Keyboard polling
Keeping track of the keys' state
HTML fragments
Avoiding reflow
Moving your sprite around using CSS Transforms
Using requestAnimationFrame instead of timeouts
Summary
4. Looking Sideways
Offline divs
Groups
Sprite transformation
CSS transform
Adding transform to the framework
Tile maps
Naive implementation
Collision detection
Colliding with tile maps
Finding the colliding tiles
Sprite versus sprite collision
Coding the game
Basic setup of the game screen
Object-oriented code for the player
Updating the player's position
Controlling the player's avatar
Player control
Parallax scrolling
Creating enemies
Summary
5. Putting Things into Perspective
Optimizing tile maps for top-down games
Finding the visible tiles
Moving the tile map
Sorting the occlusion
Sprite occlusion
Level versus sprite occlusion
Collision detection
Player versus environment collisions
Using a tile map editor
Player versus sprite collision
Talking to NPCs
Fighting enemies
The complete game
Isometric tiles
Drawing an isometric tile map
Occlusion for isometric games
Summary
6. Adding Levels to Your Games
Implementing a multi-file game
Loading tile maps
Loading sprites and their behavior
Using $.ajax
Loading a JSON file
Loading a remote script
Debugging calls to $.ajax
.done()
.fail()
Modifying our platform game
Summary
7. Making a Multiplayer Game
World of Ar'PiGi
Managing the player's account
Searching elements in the database
Creating a new player in the database
Keeping the player connected
Logging the user into the game
Keeping the players in sync
Retrieving all the other players
Updating the current player position
Client-side code
Taking care of monsters
Implementing server-side combat
Summary
8. Let's Get Social
Creating a simple leaderboard
Saving highscores
Retrieving highscores
Displaying the highscores
Making cheating harder
Server-side verification
Making your variables less readable
Obfuscating your code
Making your network protocol less readable
Encoding values
Randomly naming the variables
Adding random variables
Integrating with Twitter
Twitter for dummies
Full access to Twitter's API
Registering your game with Twitter
Server-side helper library
Authentication
Publishing high scores on Twitter
Integrating with Facebook
Authenticating with Facebook
Creating achievements
Publishing the achievements
Summary
9. Making Your Game Mobile
Making your game run well on mobile devices
Detecting mobile browsers
Client-side browser detection
Server-side detection
Should you really detect the browser?
Performance limitation – memory
Performance limitation – speed
Specifying the page's visible area
Level of details
Touch control
D-pad
Analog joystick
Event handlers
Integrating our game with the springboard
Making your game installable
Configuring the status bar
Specifying the application icon
Specifying a splash screen
Using device orientation
Using the offline application cache
Using web storage
Summary
10. Making Some Noise
Abstracting audio
Using our small library
Embedding sound
Implementation
Supported format
HTML5 Audio element
Preloading a sound
Playing and stopping sounds
Web Audio API
Basic usage
Connecting more nodes
Loading more than one sound
So many nodes, so little time
Delay node
ScriptProcessor node
Panner node
Convolver node
Analyser node
DynamicCompressor node
BiquadFilter node
WaveShaper node
Flash fallbacks
SoundManager 2
Alternatives to SoundManager
Generating sound effects
Summary
Index
jQuery Game Development Essentials
jQuery Game Development Essentials
Copyright © 2013 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: April 2013
Production Reference: 1180413
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-84969-506-0
www.packtpub.com
Cover Image by Selim Arsever (<selim.arsever@gmail.com>)
Credits
Author
Selim Arsever
Reviewers
Samuel Lee Deering
Acquisition Editors
Erol Staveley
Edward Gordon
Lead Technical Editor
Ankita Shashi
Technical Editors
Kirti Pujari
Lubna Shaikh
Copy Editors
Brandt D'Mello
Insiya Morbiwala
Alfida Paiva
Laxmi Subramanian
Project Coordinator
Anugya Khurana
Proofreader
Maria Gould
Indexer
Hemangini Bari
Graphics
Sheetal Aute
Production Coordinator
Aparna Bhagat
Cover Work
Aparna Bhagat
About the Author
Selim Arsever is a Senior Software Engineer working as a consultant in Switzerland. Over the last 4 years, he has been developing gameQuery (http://gamequeryjs.com), an open source game engine based on jQuery, as well as other JavaScript games and demos. He has been giving several talks on the subject and thinks that there is nothing more interesting than using tools beyond what they were initially intended for. You can follow him on twitter at @SelimArsever.
Thank you to my wife and my son for their patience and support, and to the entire JavaScript community for their passion and openness.
About the Reviewer
Samuel Lee Deering is a Web Developer from England who specializes in JavaScript and jQuery. Sam has built his expertise from a strong programming background, including a Bachelor's degree in Computer Science, and has worked for several high-profile companies such as Flight Centre. Sam has a very strong web presence; he develops modern web apps and has written online publications for renowned websites, such as jQuery Mobile Builder and Smashing Magazine. Sam's main focus is to help improve the Web, and he shares his knowledge with millions on his blog at http://www.jquery4u.com/.
You can find his details on the following websites:
Profile picture: http://gravatar.com/samdeering
Website: http://samdeering.com
Blog: http://jquery4u.com
Twitter: @samdeering @jquery4u
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
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.
Preface
Writing games is not only fun but also a very good way to learn a technology through and through. Even though HTML and JavaScript weren't conceived to run games, over the last few years, a series of events have occurred to make writing games in JavaScript a viable solution:
Performance of browsers' JavaScript engines has improved dramatically, with modern engines being ten times faster than the state of the art engines in 2008
jQuery and other similar libraries made working with the DOM as painless as it can be
Flash lost a lot of ground due, in part, to its absence on iOS
W3C started work on many game-oriented APIs such as canvas, WebGL, and full-screen APIs
Throughout this book, you will make three games and learn a wide array of techniques. You will not only be able to use your own games, but most importantly you will have fun doing so!
What this book covers
Chapter 1, jQuery for Games, provides an in-depth look at jQuery's functions that might be useful for game development.
Chapter 2, Creating Our First Game, implements a simple game with sprites, animation, and preloading.
Chapter 3, Better, Faster, but not Harder, optimizes the game we saw in Chapter 2, Creating Our First Game, with various techniques such as time-out inlining, keyboard polling, and HTML fragments.
Chapter 4, Looking Sideways, codes a platformer game with tile maps and collision detection.
Chapter 5, Putting Things into Perspective, creates an orthogonal RPG with tile map optimization, sprite occlusion, and better collision detection.
Chapter 6, Adding Levels to Your Games, expands the game we saw in Chapter 4, Looking Sideways, by adding multiple levels using JSON and AJAX.
Chapter 7, Making a Multiplayer Game, transforms the games we saw in Chapter 5, Putting Things into Perspective, to support multiple players on multiple machines.
Chapter 8, Let's Get Social, integrates the platform game with Facebook and Twitter as well as creating a cheat-proof leaderboard.
Chapter 9, Making Your Game Mobile, optimizes the games we saw in Chapter 5, Putting Things into Perspective, for mobile devices and touch control.
Chapter 10, Making Some Noise, adds sound effects and music to your game with the audio element, the Web Audio API, or Flash.
What you need for this book
One of the advantages of working with web technologies is that you won't need any complex or costly software to get you started. For strictly client-side games, you will only need your favorite code editor (or even a simple text editor, if you don't mind working without any syntax highlighting). If you haven't chosen any yet, there is plenty of free software around you that you could try, ranging from very old-school, such as VIM (http://www.vim.org/) and Emacs (http://www.gnu.org/software/emacs/) to more modern, such as Eclipse (http://www.eclipse.org/) and Aptana (http://www.aptana.com/), Notepad++ (http://notepad-plus-plus.org/), or Komodo Edit (http://www.activestate.com/komodo-edit). These are only some of the available editors that you can find. For JavaScript, you don't need a very advanced editor, so just use the one you're more familiar with.
If you create you own graphic, you will also need an image editing software. Here again, you will have a lot of choice. The most famous open source software being Gimp (http://www.gimp.org/) and one of my personal favorites, Pixen (http://pixenapp.com/).
For the part of the book that needs some server-side scripts, we will use PHP and MySQL. If you don't already have a server that supports them, to install these on your machine, you can use MAMP (http://www.mamp.info/), XAMPP (http://www.apachefriends.org/en/xampp.html), or EasyPHP (http://www.easyphp.org/) depending upon your OS.
Who this book is for
The primary audience for this book is a beginner web developer with some experience in JavaScript and jQuery. Since the server-side part is implemented in PHP, it will help if you have some knowledge of it too, but if you're more comfortable with another server-side language, you could use it instead of PHP without too much trouble.
You won't need any prior knowledge of game development at all to enjoy this book!
Conventions
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text are shown as follows: The .animate() function from jQuery allows you to make a property vary through time from the current value to a new one.
A block of code is set as follows:
$(#myElementId
)
.animate({top: 200})
.animate({left: 200})
.dequeue();
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
gf.keyboard = [];
// keyboard state handler
$(document).keydown(function(event){ gf.keyboard[event.keyCode] = true; });
$(document).keyup(function(event){
gf.keyboard[event.keyCode] = false;
});
Any command-line input or output is written as follows:
# cp /usr/src/asterisk-addons/configs/cdr_mysql.conf.sample
/etc/asterisk/cdr_mysql.conf
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: The following figure shows what a typical one-dimensional intersection i of two segments a and b would look like
.
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to <feedback@packtpub.com>, and mention the book title via the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <copyright@packtpub.com> with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
Questions
You can contact us at <questions@packtpub.com> if you are having a problem with any aspect of the book, and we will do our best to address it.
Chapter 1. jQuery for Games
Over the course of the last few years, jQuery has almost become the default framework for any JavaScript development. More than 55 percent of the top 10,000 most visited websites as well as an estimated total of 24 million websites on the Internet are using it (more at http://trends.builtwith.com/javascript/JQuery). And this trend doesn't show any sign of stopping.
This book expects you to have some prior experience of jQuery. If you feel that you don't meet this requirement, then you could first learn more about it in Learning jQuery, Jonathan Chaffer, Karl Swedberg, Packt Publishing.
This chapter will quickly go through the peculiarities of jQuery and will then dive deeper into its most game-oriented functions. Even if you probably have already used most of them, you may not be familiar with the full extent of their capabilities. The following is a detailed list of the topics addressed in this chapter:
The peculiarities of jQuery
The function that will help you for moving elements around
Event handling
DOM manipulation
The way of jQuery
jQuery's philosophy differs from most other JavaScript frameworks that predated it. Understanding the design patterns it uses is key to writing readable and efficient code. We'll cover these patterns in the next sections.
Chaining
Most jQuery statements are of the following form: a selection followed by one or more actions. The way those actions are combined is called chaining and is one of the most elegant aspects of jQuery. A beginner using jQuery who wants to set the width of an element to 300 pixels and its height to 100 pixels would typically write something like:
$(#myElementId
).width(300);
$(#myElementId
).height(100);
With chaining, this would be written as:
$(#myElementId
).width(300).height(100);
This has many advantages: the element is selected only once, and the resulting code is more compact and conveys the semantic meaning that what you want to achieve is really only one thing, which is to change the element size.
Functions that allow chaining don't only make it possible to group many calls on the same object, but also there are many ways to actually change on what object (or objects) the next function on the chain will operate. In these situations, it is typical to use indentation to convey the idea that you're not working on the same elements as the previous indentation level.
For example, the following chain first selects an element, then sets its background's color as red. It then changes the elements in the chain to the children of the previous element and changes their background-color attribute to yellow.
$(#myElementId
).css(background-color
, red
)
.children().css(background-color
, yellow
);
It's important that you always ask yourself how the current interactions with the previous and next element in the chain can be avoided for undesired behavior.
Polymorphism
jQuery has its own way to use polymorphism, and a given function can be