{"id":13513188,"url":"https://github.com/kittykatattack/ga","last_synced_at":"2025-04-04T16:17:06.562Z","repository":{"id":18539999,"uuid":"21740919","full_name":"kittykatattack/ga","owner":"kittykatattack","description":"The world's tiniest, cutest and funnest game engine","archived":false,"fork":false,"pushed_at":"2024-07-09T19:46:11.000Z","size":30479,"stargazers_count":455,"open_issues_count":28,"forks_count":81,"subscribers_count":22,"default_branch":"master","last_synced_at":"2025-03-28T15:09:26.213Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kittykatattack.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2014-07-11T15:17:00.000Z","updated_at":"2025-03-27T22:20:22.000Z","dependencies_parsed_at":"2024-11-17T00:39:16.849Z","dependency_job_id":null,"html_url":"https://github.com/kittykatattack/ga","commit_stats":{"total_commits":149,"total_committers":9,"mean_commits":"16.555555555555557","dds":"0.17449664429530198","last_synced_commit":"28e76ee9c727c71237da9e5deea5f2dc15a51fad"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kittykatattack%2Fga","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kittykatattack%2Fga/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kittykatattack%2Fga/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kittykatattack%2Fga/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kittykatattack","download_url":"https://codeload.github.com/kittykatattack/ga/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247208190,"owners_count":20901570,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-01T04:00:43.383Z","updated_at":"2025-04-04T16:17:06.530Z","avatar_url":"https://github.com/kittykatattack.png","language":"JavaScript","funding_links":[],"categories":["Uncategorized"],"sub_categories":["Uncategorized"],"readme":"![Ga](/tutorials/screenshots/logoAndIllustration.png)\n\nGa\n===\n\n*\"Ga!\"*\n*- A baby's exclamation of surprise.*\n\n*Ga* is a tiny, cute and friendly system for making HTML5 games or any other\nkind interactive media. You can use it to make any kind of 2D action\ngame you can imagine, with unbelievably tiny file sizes (under 6.5k!)\n\nTake a look at the feature list and the `examples` folder to get\nstarted. Keep scrolling, and you'll find a complete beginner's\ntutorial ahead. If you've never made a game before, the tutorials are\nthe best place to start.\n\nGa is \"finsihed\" software. It's perfect and bug-free, which is why there have been so few recent updates. Go ahead and use it - forever! \n\n[中文文档](./README_zh_CN.md)\n\n### Table of contents:\n\n1. [Features](#features)\n2. [The Plugins](#plugins)\n3. [Coming soon...](#comingsoon)\n4. [Ga's philosophy and technical constraints](#philosophy)\n5. [Minifying, crushing and compressing](#minifying)\n6. [Contributions and Licencing](#contibutions)\n7. [Hexi](#hexi)\n8. [Tutorials](#tutorials)\n  1. [Treasure Hunter](#treasure)\n    1. [Setting up the HTML container page](#settingup)\n    2. [Initializing the Ga engine](#initializing)\n    3. [Define your \"global\" variables](#defineglobals)\n    4. [Initialize your game with a setup function](#setupfunction)\n      1. [Customizing the canvas](#customizing)\n      2. [Creating the `chimes` sound object](#creatingsound)\n      3. [Creating game scenes](#gamescenes)\n      4. [Making sprites](#makingsprites)\n      5. [Positioning sprites](#positioningsprites)\n      6. [Assigning dynamic properties](#dynamicproperties)\n      7. [Creating the enemy sprites](#enemysprites)\n      8. [The health bar](#healthbar)\n      9. [The game over scene](#gameoverscene)\n      10. [Keyboard interactivity](#keyboard)\n      11. [Setting the game state](#gamestate)\n    5. [Game logic with the play function loop](#gamelogic)\n      1. [Moving the player sprite](#movingplayer)\n      2. [Containing sprites inside the screen boundaries](#boundries)\n      3. [Collision with the enemies](#collisionenemy)\n        1. [Collision with the treasure](#collisiontreasure)\n      4. [Ending the game](#endinggame1)\n    6. [Using images](#usingimages)\n      1. [Individual images](#individualimages)\n        1. [Loading image files](#loadingimagefile)\n        2. [Making sprites with images](#makingsprites)\n        3. [Fine-tuning the containment area](#finetuning)\n    7. [Using a texture atlas](#textureatlas)\n      1. [Preparing the images](#preparingimages)\n      2. [loading the texture atlas](#loadingatlas)\n  2. [Alien Armada](#alienarmada)\n    1. [Load and use a custom font](#customfonts)\n    2. [Scale and center the game in the browser](#scalebrowser)\n    3. [A loading progress bar](#progressbar)\n    4. [Shooting bullets](#shootingbullets)\n    5. [Sprite states](#spritestates)\n    6. [Generating random aliens](#randomaliens)\n      1. [Timing the aliens](#timingaliens)\n      2. [The aliens' random start positions](#randomposition)\n    7. [Moving the aliens](#movingaliens)\n    8. [Making the aliens explode](#explodealiens)\n    9. [Displaying the score](#displayingscore)\n    10. [Ending and resetting the game](#endinggame2)\n  3. [Flappy Fairy!](#flappyfairy)\n    1. [Launch a game in fullscreen mode](#launchagameinfullscreenmode)\n    2. [Make a button](#makeabutton)\n    3. [Making the fairy fly](#makingthefairyfly)\n    4. [Make a scrolling background](#makeascrollingbackground)\n    5. [The fairy dust explosions](#thefairydustexplosions)\n    6. [Use a particle emitter](#useaparticleemitter)\n    7. [Creating and moving the pillars](#creatingandmovingthepillars)\n9. [A Guide to the examples](#aguidetotheexamples)\n\n\u003ca id='features'\u003e\u003c/a\u003e\nFeatures\n--------\n\nHere's Ga's core feature list:\n\n- All the most important sprites you need: rectangles, circles, lines,\n  text, image sprites and animated \"MovieClip\" style sprites. You can make any of these\n  sprites with one only line of code. You can also create your own custom sprite\n  types.\n- A complete scene graph with nested child-parent hierarchies (including\n  a `stage`, and `addChild`/`removeChild` methods), local and global\n  coordinates, depth layers, and rotation pivots.\n- `group` sprites together to make game scenes. \n- A game loop with a user-definable `fps` and fully customizable and\n  drop-dead-simple game state manager. `pause` and `resume` the game\n  loop at any time.\n- Tileset (spritesheet) support using `frame` and `filmstrip` methods to make\n  sprites using tileset frames.\n- Built-in texture atlas support for the popular Texture Packer\n  format. Use a sprite's `setTexture` method if you want to change a sprite's image source while the game is running \n- A keyframe animation and state manager for sprites. Use `show` to\n  display a sprite's image state. Use `play` or `playSequence` to play\n  a sequence of frames (in a `loop` if you want to). Use\n  `show` to display a specific frame number. Use `fps` to set the\n  frame rate for sprite animations which is independent from the game's\n  frame rate.\n- Interactive `button` sprites with `up`, `over` and `down` states.\n- Any sprite can be set as `interactive` to receive mouse and touch\n  actions.\n  Intuitive `press`, `release`, `over`, `out` and `tap` methods for buttons and interactive\n  sprites.\n- Easy-to-use keyboard key bindings. The arrow and space keys are\n  built-in, and you can easily define your own with the `keyboard`\n  method.\n- A built-in universal `pointer` that works with both the mouse and\n  touch. Assign your own custom `press`, `release` and `tap` methods\n  or use any of the pointer's built-in properties: `isUp`, `isDown`,\n  `tapped`, `x` and `y`. Define as many pointers as you need for multi-touch.\n- Conveniently position sprites relative to other sprites using\n  `putTop`, `putRight`, `putBottom`, `putLeft` and `putCenter`.\n- A universal asset loader to pre-load images, fonts, sounds and JSON\n  data files. All popular file formats are supported. You can load new assets into the game at\n  any time.\n- An optional `load` state that lets you run actions while assets are\n  loading. You can use the `load` state to add a loading progress bar.\n- A fast and focused canvas-based rendering engine.\n- A sophisticated game loop using a fixed timestep with variable rendering\n  and sprite interpolation. That means you get butter-smooth sprite animations\n  at any framerate.\n- A `plugins.js` file full of extra tools. \n- A compact and powerful \"Haiku\" style API that's centered on shallow,\n  composable components. Get more done writing less code.\n- Ga is totally hackable. Overwrite any of its default methods or objects\n  with your own at compile or run time.\n- Yes, Ga is mobile friendly!\n- Yes, the core `ga.js` engine is less than 6.5k minified and zipped!\n  That makes Ga the world's smallest, most light-weight full featured game engine.\n  It's all you need to start making any any 2D action, puzzle or\n  strategy game. \n\nAnd the coolest part? If you were alone on a desert island with only\na solar powered laptop, an unlimited supply of\ncoconuts, and a copy of `ga.js` you could recreate the entire history of 2D video games,\nfrom SpaceWar! to Flappy Bird. And all of it would fit on a 3.5 inch\nfloppy disk.\n\n\u003ca id='plugins'\u003e\u003c/a\u003e\n### The plugins\n\nBut there's more! Ga comes with a `plugins.js` file that includes a\nhuge number of useful tools for making games. You can use as many or\nas few of these tools as you want to. Here are some of the goodies\nyou'll find in `plugins.js`:\n\n- Import and play sounds using a built-in WebAudio API sound manager.\n  Control sounds with `play`, `pause`, `stop`, `restart`,\n  `playFrom`, `fadeIn` and `fadeOut` methods. Change a sound's `volume` and `pan`.\n- Generate your own custom sound effects from pure code with\n  the versatile `soundEffect` method.\n- Shake sprites or the screen with `shake`.\n- Tween functions for sprite and scene transitions: `slide`,\n  `fadeIn`, `fadeOut`, `pulse`, `breathe`, `wobble`, `strobe` and\n  some useful low-level tweening methods to help you create your own\n  custom tweens.\n- Make a sprite follow a connected series of waypoints with `walkPath`\n  and `walkCurve`. \n- A handful of useful convenience functions: `followEase`,\n  `followConstant`,\n  `angle`, `distance`, `rotateAroundSprite`, `rotateAroundPoint`, `wait`,\n  `randomInt`, `randomFloat`, `contain` and `outsideBounds`.\n- A fast, universal `hit` method that handles collision testing and\n  reactions (blocking and bounce) for all types of sprites. Use one collision method for\n  everything: rectangles, circles, points, and arrays of sprites.\n  Easy!\n- A companion suite of lightweight, low-level 2D geometric collision methods.\n- A loading progress bar for game assets.\n- Make sprites shoot things with `shoot`. \n- Easily plot sprites in a grid formation with `grid`.\n- Use a `tilingSprite` to easily create a seamless scrolling background.\n- Tiled Editor support using `makeTiledWorld`. Design your game in\n  Tiled Editor and access all the sprites, layers and objects directly\n  in your game code. It's an extremely fun, quick and easy way to make\n  games.\n- A versatile, `hitTestTile` method that handles all the collision\n  checking you'll need for tile-based games. You can use it in combination\n  with the any of the 2D geometric collision methods for optimized\n  broadphase/narrowphase collision checking if you want to.\n- A `particleEffect` function for creating all kinds of particle\n  effects for games. Use the `emitter` function to create a constant\n  stream of particles.\n- Use `updateMap` to keep a tile-based world's map data array up-to-date\n  with moving sprites.\n- Create a `worldCamera` that follows sprites around a scrolling game\n  world.\n- Use `scaleToWindow` to make the game automatically scale to its maximum size and align itself for the best fit inside the browser window. Use `enterFullscreen` to make the browser enter full screen mode, and `exitFullscreen` to exit full screen mode.\n\nTo use the plugins, just copy/paste the code you want to use from `plugins.js` into your game. \nOr, if you're not worried about the extra size, \njust link the whole thing; it's really tiny anyway!\n\nIf you want to get fancy, you can alternatively create your own `custom.js` file that \ncontains a small custom sub-set of the plugins\nyou want to use for your game. Your `custom.js` file can load at\ncompile time, so it's ready to use before your game code runs. \n(See the `plugins.js` file for instructions on how to do this).\n\n\u003ca id='comingsoon'\u003e\u003c/a\u003e\n### Coming soon... \n\n- Tiled Editor isometric maps support.\n- Many more examples including complete game prototypes.\n- Additional documentation, examples, and tutorials.\n\n\u003ca id='philosophy'\u003e\u003c/a\u003e\nGa's philosophy and technical constraints\n-----------------------------------------\n\n- The `ga.js` core game engine file can't ever be bigger that 6.5k\n  minified and zipped. Yes, 6.5k! This makes it suitable for making games for micro game\n  competitions, like [js13k](http://js13kgames.com). This absurdly\n  low overhead means you can drop a full-featured 2D action game into a web page and have it load and play almost\n  instantly. But, more\n  importantly, this constraint also discourages feature-creep and keeps\n  the engine lean and focused. \n- The API has to be fun, intuitive and expressive with as little\n  boilerplate code as possible. Game designers should be \n  free to explore their imaginations without tripping over a tangled\n  and messy API. Less typing, Less thinking!\n- The source code must be easily readable and comment-rich so that\n  everyone can learn from it. It should also be architecturally flat\n  so that anyone can rip it apart and easily drop it into something\n  else.\n- For the same reasons, all the source code must be hand-written written from scratch without any 3rd party dependencies (external libraries.)\n- Any special features, like Tiled Editor support, can be added to the\n  plugins.js file, so that game developers can pick and choose a\n  minimal custom set of components they want for specific games without bloating the core engine.\n\n\u003ca id='minifying'\u003e\u003c/a\u003e\nMinifying, crushing and compressing\n-----------------------------------\n\nThe Ga repository doesn't include the minified and compressed version\nof the source code, because you should probably optimize that yourself. I recommend\nfirst minifying the code using with [Google Closure\nCompiler](http://closure-compiler.appspot.com/home) (Simple mode only) or\n[UglifyJS2](https://github.com/mishoo/UglifyJS2). Google Closure will\ngive you best minification, and Ga's source code is optimized for it.\n\nThen, zip it. I recommend [gzip](http://www.gzip.org).\n\nFor more aggressive optimization, you could further try running the\nminified code through\n[JSCrush](http://www.iteral.com/jscrush/). Although it sometimes makes\nthings worse rather than better - you'll have to test it with your\ncode.\n\nNote: If you're using Google Closure Compiler from the command line, set the `--language_in`\nflag to `ECMASCRIPT5`, like this:\n\n`java -jar ~/compiler.jar --language_in=ECMASCRIPT5 --js ga.js --js_output_file ga.min.js`\n\n\u003ca id='contributions'\u003e\u003c/a\u003e\nContributions and Licencing\n---------------------------\nIt's Ga's ambition to be the world's tiniest, cutest and funnest game engine.\nPlease help! If you find something that's bad, please help to fix it.\nIf you find something good, please help to make it better.  Ga\nwelcomes any and all contributions! \n\n+1 Bonus Points for removing code and simplifying the architecture. +2 Bonus\nPoints for making the code easier to understand. The aim of this\nproject is to discover the smallest universal set of reusable\ncomponents required to make\nthe widest variety of games possible with the least amount of code.\nWhat is the fundamental alphabet, or the primary colours, of game design?\nThat's what we're searching. Can you help?\n\nCheckout the `dev` branch to make experimental changes and bug fixes, and we'll merge it with the `master` branch when we can confirm that everything is stable. Make sure that any code changes you make are compatible with [Google Closure Compiler](http://closure-compiler.appspot.com/home). \n\nPlease feel free to PR (Pull Request) any bug fixes and minor code improvements and optimizations. Any changes to the user-facing public API will need to be discussed in the Issues first. If we make any public API changes, we'll need to commit to updating all affected example and tutorial files as well. Also, any major changes to the engine will need to be discused too.\n\n**Coding style**: Unconventionally, Ga\nuses **functional composition** patterns (the [module\npattern](http://toddmotto.com/mastering-the-module-pattern/) and\n[mixins](http://raganwald.com/2014/04/10/mixins-forwarding-delegation.html))\nfor object creation instead of inheritance. Why? It's really\njust an experiment in coding like that. It also means the code\nbecomes a little more compact.\n\nLicensing? Ga is vehemently *unlicenesed*.\nThat means its freer than free.\n\nIt's like a pebble.\nYou can pick it up and throw into the sea.\n\n\u003ca id='hexi'\u003e\u003c/a\u003e\nHexi\n----\nDo you like Ga, but wished that it had a powerful WebGL renderer and a gazillion other features that you will probably never use? Then checkout Ga's sister game engine: [Hexi](https://github.com/kittykatattack/hexi). It uses almost exactly the same API as Ga, but is built on top of the latest stable version of the powerful, full-featured [Pixi](http://www.pixijs.com) renderer. What that means is that you can prototype your games for js13k, and port 99% of that code unchanged into Hexi to build your prodction version. If you don't care about small file sizes, and need a highly flexible, mobile-optimized and production-ready game engine using the world's most streamlined API, then check out Hexi!\n\n\u003ca id='tutorials'\u003e\u003c/a\u003e\nTutorials\n---------\n\nHow do you make a video game? These tutorials will show you how. \n\nBut first, you should have a reasonable understanding of HTML and\nJavaScript. You don't have to be an expert, just an ambitious beginner\nwith an eagerness to learn. If you don't know HTML and JavaScript, the\nbest place to start learning it is this book:\n\n[Foundation Game Design with HTML5 and JavaScript](http://www.apress.com/9781430247166)\n\nI know for a fact that it's the best book, because I wrote it :)\n\nThere are also some good internet resources to help get you started:\n\n[Khan Academy: Computer\nProgramming](http://www.khanacademy.org/computing/cs)\n\n[Code Academy:\nJavaScript](http://www.codecademy.com/tracks/javascript)\n\nOk, got it?\nDo you know what JavaScript variables, functions, arrays and objects are and how to\nuse them? Good, then read on!\n\n\u003ca id='treasure'\u003e\u003c/a\u003e\n### Treasure Hunter\n\nThe first game we're going to make is a simple object collection and\nenemy avoidance game called Treasure Hunter. Open the file\n`01_treasureHunter.html` in a web browser. (You'll find it in Ga's\n`tutorials` folder, and you'll need to run it in a\n[webserver](https://github.com/nodeapps/http-server)). If you don't\nwant to bother setting up a webserver, use a text-editor like\n[Brackets](http://brackets.io) that will launch one for you\nautomatically (see Brackets' documentation for this feature).\n\n[![Treasure Hunter](/tutorials/screenshots/01.png)](https://cdn.rawgit.com/kittykatattack/ga/master/tutorials/01_treasureHunter.html)\n\n(Follow the link in the image above to play the game.) Use the keyboard to move the explorer (the blue square), collect the\ntreasure (the yellow square), avoid the monsters (the red squares) and\nreach the exit (the green square.) Yes, you have to use your\nimagination - for now. \n\nDon't be fooled by it's apparent simplicity. Treasure Hunter contains\neverything a video game needs:\n\n- Interactivity\n- Collision\n- Sprites\n- A game loop\n- Scenes\n- game logic\n- \"Juice\" (in the form of sounds)\n\n(What's juice? [Watch this\nvideo](https://www.youtube.com/watch?v=Fy0aCDmgnxg) and \n[read this article](http://www.gamasutra.com/view/feature/130848/how_to_prototype_a_game_in_under_7_.php?print=1) to learn\nabout this essential game design ingredient.)\n\nIf you can make a simple game like Treasure Hunter, you can make\nalmost any other kind of game. Yes, really! Getting from Treasure\nHunter to Skyrim or Zelda\nis just a matter of lots of small steps; adding more\ndetail as you go. How much detail you want to add is up to you. \n\nIn the first stage of this tutorial you'll learn how the basic\nTreasure Hunter game was made, and then we'll add some fun features like images and\ncharacter animation that will give you a complete overview of how the\nGa game engine works. \n\nIf you're an experienced game programmer and\nquick self-starter, you might find the code in Ga's `examples` folder to\nbe a more productive place to start learning - check it out. The fully\ncommented\ncode in the `examples` folder also details specific, and advanced uses\nof features, that aren't\ncovered in these tutorials. When you're finished working through these\ntutorials, the `examples` will take you on the next stage of your\njourney.\n\n\u003ca id='setingup'\u003e\u003c/a\u003e\n#### Setting up the HTML container page\n\nBefore you can start programming in JavaScript, you need to set up a\nminimal HTML container page. The HTML page loads `ga.js` and\n`plugins.js` which are the two files you need to use all of Ga's\nfeatures. You'll write all your game code inside the last pair of\n`\u003cscript\u003e` tags before the closing `\u003cbody\u003e` tag.\n\n```js\n\u003c!doctype html\u003e\n\u003cmeta charset=\"utf-8\"\u003e\n\u003ctitle\u003eTreasure hunter\u003c/title\u003e\n\u003cbody\u003e\n\u003c!-- Import the Ga game engine files --\u003e\n\u003cscript src=\"../ga.js\"\u003e\u003c/script\u003e\n\u003cscript src=\"../plugins.js\"\u003e\u003c/script\u003e\n\u003cscript\u003e\n\n//All of your game code will go here\n\n\u003c/script\u003e\n\u003c/body\u003e\n\n```\nThis is the [minimum amount of HTML code you need for a valid HTML5\ndocument](http://stackoverflow.com/questions/9797046/whats-a-valid-html5-document).\n\n\u003ca id='initializing'\u003e\u003c/a\u003e\n#### Initializing the Ga engine\n\nThe next step is to write some JavaScript code that initializes and starts the Ga game\nengine, according to some parameters that you specify. This bit of\ncode below initializes a game with a screen size of 512 by 512 pixels.\nIt also pre-loads the `chimes.wav` sound file from the `sounds`\nfolder.\n\n```js\nvar g = ga(\n  512, 512, setup,\n  [\n    \"sounds/chimes.wav\"\n  ]\n);\n\n//Start the Ga engine.\ng.start();\n\n```\n\nYou can see that the result of the `ga` function is being assigned to\nan variable called `g`. \n```js\nvar g = ga(\n```\nNow, whenever you want to use any of Ga's custom\nmethods or objects in your game, just prefix it with `g`. (You don't\nhave to use `g` to represent the game engine, you can use any variable\nname you want. `g` is just nice, short, and easy to remember; `g` =\n\"game\".)\n\nIn this example Ga creates a canvas element with a size of 512 by 512\npixels. That's specified by the first two arguments:\n```js  \n512, 512, setup,\n```\nThe third argument, `setup`, means that as soon as Ga is initialized,\nit should look for and run a function in your game code called `setup`.\nWhatever code is in the `setup` function is entirely up to you, and\nyou'll soon see how you can used it to initialize a game. (You don't\nhave to call this function `setup`, you can use any name you like.) \n\nGa lets you pre-load game assets with an optional 4th argument, which\nis an array of file names. In this first example, you only need to preload one file: `chimes.wav`\nYou can see that the full file path to `chimes.wav` is listed as a\nstring in the\ninitialization array:\n\n```js\n[\n  \"sounds/chimes.wav\"\n]\n```\n\nYou can list as many game assets as you like here, including images,\nfonts, and JSON files. Ga will load all these assets for you before\nrunning any of the game code.\n\nThe last thing you need to do is call Ga's `start` method. \n```js\ng.start();\n```\nThis is the switch that turns the Ga engine on.\n\n\u003ca id='definingglobals'\u003e\u003c/a\u003e\n#### Define your \"global\" variables\n\nAfter Ga has been started, declare all the variables that your game\nfunctions will need to use.\n\n```js\nvar dungeon, player, treasure, enemies, chimes, exit,\n    healthBar, message, gameScene, gameOverScene;\n```\n\nBecause they're not enclosed inside a function, these variables are \"global\" \nin the sense that you can use them across all of your game functions.\n(They're not necessarily \"global\" in the sense that they inhabit the\nglobal JavaScript name-space. If you want to ensure that they aren't, [wrap all of\nyour JavaScript code in an enclosing **immediate function** to isolate it\nfrom the global\nspace](http://stackoverflow.com/questions/17058606/why-using-self-executing-function-in-javascript).\n\n\u003ca id='setupfunction'\u003e\u003c/a\u003e\n#### Initialize your game with a setup function\n\nAs soon as Ga starts, it will look for and run a function in your game\ncode called `setup` (or whatever other name you want to give this\nfunction.) The `setup` function is only run once, and lets you perform\none-time setup tasks for your game. It's a great place to create and initialize\nobjects, create sprites, game scenes, populate data arrays or parse\nloaded JSON game data. \n\nHere's an abridged, birds-eye view of the `setup` function in Treasure Hunter,\nand the tasks that it performs.\n\n```js\nfunction setup() {\n  //Set the canvas border and background color\n  //Create the `chimes` sound object\n  //Create the `gameScene` group\n  //Create the `exit` door sprite\n  //Create the `player` sprite\n  //Create the `treasure` sprite\n  //Make the enemies\n  //Create the health bar\n  //Add some text for the game over message\n  //Create a `gameOverScene` group \n  //Assign the player's keyboard controllers\n\n  //set the game state to `play`\n  g.state = play;\n}\n\n```\nThe last line of code, `g.state = play` is perhaps the most important\nbecause it starts the `play` function. The `play` function runs all the game logic\nin a loop. But before we look at how that works, let's see what the\nspecific code inside the `setup` function does.\n\n\u003ca id='customizing'\u003e\u003c/a\u003e\n##### Customizing the canvas\n\nThe first two lines in the `setup` function give the canvas a black dashed border and set its\nbackground color to white.\n```js\ng.canvas.style.border = \"1px black dashed\";\ng.backgroundColor = \"white\";\n```\nHere's the effect these two lines have on the Ga canvas:\n\n![Treasure Hunter](/tutorials/screenshots/02.png)\n\nGa uses an ordinary 2D canvas element to display the game graphics,\nand you can access it in your code at any time with `g.canvas`. You\ncan modify it with any ordinary HTML/CSS properties.\n\n\u003ca id='creatingsound'\u003e\u003c/a\u003e\n##### Creating the `chimes` sound object\n\nYou'll remember from the code above that we preloaded a sound file\ninto the game called `chimes.wav`. Before you can use it in your game,\nyou have to make a reference to it using Ga's `sound` method,\nlike this:\n```js\nchimes = g.sound(\"sounds/chimes.wav\");\n```\nAlternatively, you can access any assets that you've loaded via Ga's\n`assets` object, like this:\n```js\ng.assets[\"sounds/chimes.wav\"]\n```\nAny assets that you've preloaded like this are accessible in the\n`assets` object.\n\nMany assets that you might want to use, like sounds, fonts, and JSON\nfiles, can\nonly be loaded by the browser if your code is running inside a\nweb server. If you're trying to load or use an asset, and the browser is\ngiving your a\nstrange security related error message, check to make sure that the\nweb server is initialized.\n\n\u003ca id='gamescenes'\u003e\u003c/a\u003e\n##### Creating game scenes\n\nGa has a useful method called `group` that lets you group game objects\ntogether so that you can work with them as one unit. Groups are used for\ngrouping together special objects called **sprites**  (which you'll\nlearn all about in the next section.) But they're also used for making game scenes. \n\nTreasure Hunter uses two game scenes: `gameScene` which is the main game, \nand `gameOverScene` which is displayed when the game is finished. \nHere's how the `gameScene` is made using the `group` method:\n```js\ngameScene = g.group();\n```\nAfter you've made the group, you can add sprites (game objects) to the `gameScene`, using\nthe `addChild` method.\n```js   \ngameScene.addChild(anySprite);\n```\nOr, you can add multiple sprites at one time with the `add` method, like this:\n```js\ngameScene.add(spriteOne, spriteTwo, spriteThree);\n```\nOr, if you prefer, you can create the game scene after you've made all\nthe sprites, and group all the sprites together with one line of code, like this:\n```js\ngameScene = g.group(spriteOne, spriteTwp, spriteThree);\n```\nYou'll see a few different examples of how to add sprites to groups in\nthe examples ahead.\n\nBut what are sprites, and how do you make them?\n\n\u003ca id='makingsprites'\u003e\u003c/a\u003e\n##### Making sprites\n\nSprites are the most important elements in any game. Sprites are\njust graphics (shapes or images) that you can control with\nspecial properties. Everything you can see in your games, like\ngame characters, objects and backgrounds, are sprites. Ga lets you make\n5 kinds of basic sprites: `rectangle`, `circle`, `line`, `text`, and\n`sprite` (an image-based sprite). You can make almost any 2D action game\nwith these basic sprite types. (If they aren't enough, you can also define your own custom\nsprite types.) This first version of Treasure Hunter\nonly uses `rectangle` sprites. You can make a rectangle sprite like\nthis:\n```js\nvar box = g.rectangle(\n  widthInPixels, \n  heightInPixels, \n  \"fillColor\", \n  \"strokeColor\", \n  lineWidth, \n  xPosition, \n  yPosition\n);\n```\nYou can use Ga's `circle` method to make a circular shaped sprite:\n```js\nvar ball = g.circle(\n  diameterInPixels, \n  \"fillColor\", \n  \"strokeColor\", \n  lineWidth,\n  xPosition, \n  yPosition \n);\n```\nIt's often useful to prototype a new game using only `rectangle` and\n`circle` sprites, because that can help you focus on the mechanics of your\ngame in a pure, elemental way. That's what this first version of\nTreasure Hunter does. Here's the code from the `setup` function that\ncreates the `exit`, `player` and `treasure` sprites.\n\n```js\n//The exit door\nexit = g.rectangle(48, 48, \"green\");\nexit.x = 8;\nexit.y = 8;\ngameScene.addChild(exit);\n\n//The player sprite\nplayer = g.rectangle(32, 32, \"blue\");\nplayer.x = 68;\nplayer.y = g.canvas.height / 2 - player.halfHeight;\ngameScene.addChild(player);\n\n//Create the treasure sprite\ntreasure = g.rectangle(16, 16, \"gold\");\n\n//Position the treasure next to the right edge of the canvas\ntreasure.x = g.canvas.width - treasure.width - 32;\ntreasure.y = g.canvas.height / 2 - treasure.halfHeight;\n\n//Create a `pickedUp` property on the treasure to help us figure\n//out whether or not the treasure has been picked up by the player\ntreasure.pickedUp = false;\n\n//Add the treasure to the gameScene\ngameScene.addChild(treasure);\n\n```\nNotice that after each sprite is created, it's added to the\n`gameScene` using `addChild`. Here's what the above code produces:\n\n![Treasure Hunter](/tutorials/screenshots/03.png)\n\nLet's find out a little more about how these sprites are positioned on\nthe canvas.\n\n\u003ca id='positioningsprites'\u003e\u003c/a\u003e\n##### Positioning sprites\n\nAll sprites have `x` and `y` properties that you can use to precisely\nposition sprites on the canvas. The `x` and `y` values refer to the sprites' pixel\ncoordinates relative to the canvas's top left corner. The top\nleft corner has `x` and `y` values of 0. That means any\npositive `x` and `y` values you assign to sprites will position them left (`x`) and down\n(`y`) relative to that corner point. For example, Here's the\ncode that positions the `exit` door (the green square). \n```js\nexit.x = 8;\nexit.y = 8;\n```\nYou can see that this code places the door 8 pixel to the right and 8 pixels below the\ncanvas's top left corner. Positive `x` values position sprites to the\nright of the canvas's left edge. Positive `y` values position them\nbelow the canvas's top edge.\n\nSprites also have `width` and `height`\nproperties that tell you their width and height in pixels. If you need\nto find out what half the width or half the height of a sprite is, use\n`halfWidth` and `halfHeight`.\n\nGa also has a some convenience methods that help you quickly position\nsprites relative to other sprites: `putTop`, `putRight`, `putBottom`, `putLeft` and `putCenter`.\nFor example, here are the lines from the code above that\nposition the treasure sprite (the gold box). The code places the\ntreasure 26 pixels to the left of the\ncanvas's right edge, and centers it vertically.\n```js\ntreasure.x = g.canvas.width - treasure.width - 32;\ntreasure.y = g.canvas.height / 2 - treasure.halfHeight;\n```\nThat's a lot of complicated positioning code to write. Instead, you\ncould use Ga's built-in `putCenter` method to achieve the same effect\nlike this:\n```js\ng.stage.putCenter(treasure, 220, 0);\n```\nWhat is the `stage`? It's the root container for all the sprites, and\nhas exactly the same dimensions as the canvas. You can think of the\n`stage` as\na big, invisible sprite, the same size as the canvas, that contains\nall the sprites in your game, as well as any containers those sprites\nmight be grouped in (Like the `gameScene`). `putCenter` works by\ncentering the `treasure` inside the `stage`, and then offsetting its\n`x` position by 220 pixels. Here's the format for using `putCenter`:\n```js\nanySprite.putCenter(anyOtherSprite, xOffset, yOffset);\n```\nYou can use the other `put` methods in the same way. For example, if\nyou wanted to position a sprite directly to the left of another\nsprite, without any offset, you could use `putLeft`, like this:\n```js\nspriteOne.putLeft(spriteTwo);\n```\nThis would place `spriteTwo` directly to the left of `spriteOne`, and\nalign it vertically .You'll see many examples of how to use these `put` methods throughout\nthese tutorials.\n\n\u003ca id='dynamicproperties'\u003e\u003c/a\u003e\n##### Assigning dynamic properties\n\nBefore we continue, there's one small detail you need to notice. The\ncode that creates the sprites also adds a `pickedUp` property to the\n`treasure` sprite:\n```js\ntreasure.pickedUp = false;\n```\nYou'll see how we're going to use `treasure.pickedUp` later in the game logic to help us determine the\nprogress of the game. You can dynamically assign any custom properties or methods to sprites like this, if you need to.\n\n\u003ca id='enemysprites'\u003e\u003c/a\u003e\n##### Creating the enemy sprites\n\nThere are 6 enemies sprites (red squares) in Treasure Hunter. They're\nspaced evenly horizontally but but have random initial vertical\npositions. All the enemies sprites are created in a `for` loop using\nthis code in the `setup` function:\n\n```js\n//Make the enemies\nvar numberOfEnemies = 6,\n    spacing = 48,\n    xOffset = 150,\n    speed = 2,\n    direction = 1;\n\nenemies = [];\n\n//Make as many enemies as there are `numberOfEnemies`\nfor (var i = 0; i \u003c numberOfEnemies; i++) {\n\n  //Each enemy is a red rectangle\n  var enemy = g.rectangle(32, 32, \"red\");\n\n  //Space each enemey horizontally according to the `spacing` value.\n  //`xOffset` determines the point from the left of the screen\n  //at which the first enemy should be added.\n  var x = spacing * i + xOffset;\n\n  //Give the enemy a random y position\n  var y = g.randomInt(0, g.canvas.height - enemy.height);\n\n  //Set the enemy's direction\n  enemy.x = x;\n  enemy.y = y;\n\n  //Set the enemy's vertical velocity. `direction` will be either `1` or\n  //`-1`. `1` means the enemy will move down and `-1` means the enemy will\n  //move up. Multiplying `direction` by `speed` determines the enemy's\n  //vertical direction\n  enemy.vy = speed * direction;\n\n  //Reverse the direction for the next enemy\n  direction *= -1;\n\n  //Push the enemy into the `enemies` array\n  enemies.push(enemy);\n\n  //Add the enemy to the `gameScene`\n  gameScene.addChild(enemy);\n}\n\n```\nHere's what this code produces:\n\n![Treasure Hunter](/tutorials/screenshots/04.png)\n\nThe code gives each of the enemies a random `y` position with the help\nof Ga's `randomInt` method:\n```js\nvar y = g.randomInt(0, g.canvas.height - enemy.height);\n```\n`randomInt` will give you a random number between any two integers that you\nprovide in the arguments. (If you need a random decimal number, use\n`randomFloat` instead).\n\nAll sprites have properties called `vx` and `vy`. They determine the\nspeed and direction that the sprite will move in the horizontal\ndirection (`vx`) and vertical direction (`vy`).  The enemies in\nTreasure Hunter only move up and down, so they just need a `vy` value.\nTheir `vy` is `speed` (2) multiplied by `direction` (which will be\neither `1` or `-1`).\n```js\nenemy.vy = speed * direction;\n```\nIf `direction` is `1`, the enemy's `vy` will be `2`. That means the\nenemy will move down the screen at a rate of 2 pixels per frame. If\n`direction` is `-1`, the enemy's speed will be `-2`. That means the\nenemy will move up the screen at 2 pixels per frame. \n\nAfter the enemy's `vy` is set, `direction` is reversed so that the next\nenemy will move in the opposite direction.\n```js\ndirection *= -1;\n```\nYou can see that each enemy that's created is pushed into an array\ncalled `enemies`.\n```js\nenemies.push(enemy);\n```\nLater in the code you'll see how we'll access all the enemies in this\narray to figure out if they're touching the player.\n\n\u003ca id='healthbar'\u003e\u003c/a\u003e\n##### The health bar\n\nYou'll notice that when the player\ntouches one of the enemies, the width of the health bar at the top right corner of\nthe screen decreases. \n\n![Treasure Hunter](/tutorials/screenshots/05.png)\n\nHow was this health bar made? It's just two rectangle sprites at the same\nposition: a black rectangle behind, and a green rectangle in front. They're grouped\ntogether to make a single compound sprite called `healthBar`. The\n`healthBar` is then added to the `gameScene`.\n\n```js\n//Create the health bar\nvar outerBar = g.rectangle(128, 16, \"black\"),\n    innerBar = g.rectangle(128, 16, \"yellowGreen\");\n\n//Group the inner and outer bars\nhealthBar = g.group(outerBar, innerBar);\n\n//Set the `innerBar` as a property of the `healthBar`\nhealthBar.inner = innerBar;\n\n//Position the health bar\nhealthBar.x = g.canvas.width - 148;\nhealthBar.y = 16;\n\n//Add the health bar to the `gameScene`\ngameScene.addChild(healthBar);\n```\nYou can see that a property called `inner` has been added to the\n`healthBar`. It just references the `innerBar` (the green rectangle) so that\nit will be convenient to access later.\n```js\nhealthBar.inner = innerBar;\n```\nYou don't *have* to do this; but, hey why not! It means that if you\nwant to control the width of the `innerBar`, you can write some smooth code\nthat looks like this:\n```js\nhealthBar.inner.width = 30;\n```\nThat's pretty neat and readable, so we'll keep it!\n\n\u003ca id='gameoverscene'\u003e\u003c/a\u003e\n##### The game over scene\n\nIf the player's health drops to zero, or the player manages to\ncarry the treasure to the exit, the game ends and the game over screen\nis displayed.  The game over scene is just some text that displays \"You won!\" or \"You\nlost!\" depending on the outcome. \n\n![Treasure Hunter](/tutorials/screenshots/06.png)\n\nHow was this made? The text is made with a `text` sprite. \n\n```js\nvar anyText = g.text(\n  \"Hello!\", \"CSS font properties\", \"fillColor\", xPosition, yPosition\n);\n\n```\nThe first argument, \"Hello!\" in the above example, is the text content\nyou want to display. Use the `content` property to change the text\nsprite's content later.\n```js\nanyText.content = \"Some new content\";\n```\nHere's how the game over message text is created in the `setup`\nfunction. \n\n```js\n//Add some text for the game over message\nmessage = g.text(\"Game Over!\", \"64px Futura\", \"black\", 20, 20);\nmessage.x = 120;\nmessage.y = g.canvas.height / 2 - 64;\n```\nNext, a new `group` is created called `gameOverScene`. The `message` text\nis added to it. The `gameOverScene`'s `visible` property is set to\n`false` so that it's not visible when the game first starts.\n\n```js\n//Create a `gameOverScene` group and add the message sprite to it\ngameOverScene = g.group(message);\n\n//Make the `gameOverScene` invisible for now\ngameOverScene.visible = false;\n\n```\nAt the end of the game we'll set the `gameOverScene`'s `visible`\nproperty to `true` to display the text message. We'll also set the\n`gameScene`'s `visible` property to `false` so that all the game\nsprites are hidden.\n\n\u003ca id='keyboard'\u003e\u003c/a\u003e\n##### Keyboard interactivity\n\nYou control the player (the blue square) with the keyboard arrow keys.\nGa has a built-in `key` object with keyboard bindings \nto the arrow keys and space bar. Access them like this:\n`key.leftArray`, `key.rightArrow`, `key.upArrow`, `key.downArrow`,\n`key.space`. All these keys have `press` and\n`release` methods that you can define. Here's code in the `setup`\nfunction that customizes the `press` and `release` methods of   \nGa's pre-defined arrow keys to control the player character: \n```js\n//Left arrow key `press` method\ng.key.leftArrow.press = function() {\n  //Change the player's velocity when the key is pressed\n  player.vx = -5;\n  player.vy = 0;\n};\n\n//Left arrow key `release` method\ng.key.leftArrow.release = function() {\n  //If the left arrow has been released, and the right arrow isn't down,\n  //and the player isn't moving vertically:\n  //Stop the player\n  if (!g.key.rightArrow.isDown \u0026\u0026 player.vy === 0) {\n    player.vx = 0;\n  }\n};\n\ng.key.upArrow.press = function() {\n  player.vy = -5;\n  player.vx = 0;\n};\n\ng.key.upArrow.release = function() {\n  if (!g.key.downArrow.isDown \u0026\u0026 player.vx === 0) {\n    player.vy = 0;\n  }\n};\n\ng.key.rightArrow.press = function() {\n  player.vx = 5;\n  player.vy = 0;\n};\n\ng.key.rightArrow.release = function() {\n  if (!g.key.leftArrow.isDown \u0026\u0026 player.vy === 0) {\n    player.vx = 0;\n  }\n};\n\ng.key.downArrow.press = function() {\n  player.vy = 5;\n  player.vx = 0;\n};\n\ng.key.downArrow.release = function() {\n  if (!g.key.upArrow.isDown \u0026\u0026 player.vx === 0) {\n    player.vy = 0;\n  }\n};\n\n```\nYou can see that the value of the player's `vx` and `vy` properties is\nchanged depending on which keys are being pressed or released.\nA positive `vx` value will make the player move right, a negative\nvalue will make it move left. A positive `vy` value will make the\nplayer move\ndown, a negative value will make it move up. \n\nIs that too much typing? Because controlling a player character with 4\nkeyboard keys is such a common requirement, Ga has a built-in function called\n`fourKeyController` that accomplishes all this in one line of code.\n```js\ng.fourKeyController(player, 5, 38, 39, 40, 37);\n```\nThe first argument is the sprite you want to control: `player`. The\nsecond argument is the number of pixels that the sprite should move each frame: `5`.\nThe last four arguments are the [ascii key code numbers](http://www.asciitable.com) for the top,\nright, bottom and left keys. (You can remember this because their\norder is listed clockwise, starting from the top.)\n\nReference to the arrow keys and space key are built-in to Ga, but you\nif want to use other keys, you can easily create and assign your own\nwith Ga's `keyboard` method:\n```js\nvar customKey = g.keyboard(asciiCode);\n```\nYour new `customKey` has `press` and `release` methods\nthat you can program in the same way as the examples above. \n\n\u003ca id='gamestate'\u003e\u003c/a\u003e\n##### Setting the game state\n\nThe **game state** is the function that Ga is currently running. When\nGa first starts, it runs the `setup` function (or whatever other\nfunction you specify in Ga's constructor function arguments.) If you\nwant to change the game state, assign a new function to Ga's `state`\nproperty. Here's how:\n```js\ng.state = anyFunction;\n```\nIn Treasure Hunter, when the `setup` function is finished, the game\n`state` is set to `play`:\n```\ng.state = play;\n```\nThis makes Ga look for and run a function called `play`. By default,\nany function assigned to the game state will run in a continuous loop, at\n60 frames per second. (You can change the frame rate at any time by setting Ga's\n`fps` property). Game logic usually runs in a continuous loop, which\nis known as the **game loop**. Ga handles the loop management for you,\nso you don't need to worry about how it works. (In case you're curious, Ga uses\na `requestAnimationFrame` loop with a [fixed logic time step and variable rendering time](http://gameprogrammingpatterns.com/game-loop.html). It\nalso does sprite position interpolation to smoothe out any inconsistent\nspikes in the frame rate.)\n\nIf you ever need to pause the loop, just use Ga's `pause`method, like\nthis:\n```js\ng.pause();\n```\nYou can start the game loop again with the `resume` method, like this:\n```\ng.resume();\n```\nNow let's find out how Treasure Hunter's `play` function works. \n\n\u003ca id='gamelogic'\u003e\u003c/a\u003e\n#### Game logic with the play function loop\n\nAs you've just learned, everything in the `play` function runs in a\ncontinuous loop.\n\n```js\nfunction play() {\n  //This code loops from top to bottom 60 times per second  \n}\n```\nThis is where all the game logic happens. It's the fun part,\nso let's find out what the code inside the `play` function does.\n\n\u003ca id='movingplayer'\u003e\u003c/a\u003e\n##### Moving the player sprite\n\nTreasure Hunter uses Ga's `move` method inside the `play` function to move the sprites in the\ngame.\n```js\ng.move(player);\n```\nThis is the equivalent of writing code like this:\n\n```js\nplayer.x += player.vx;\nplayer.y += player.vy;\n```\nIt just updates the player's `x` and `y` position by adding its `vx`\nand `vy` velocity values. (Remember, those values were\nset by the key `press` and `release` methods.) Using `move` just saves\nyou from having to type-in and look-at this very standard boilerplate\ncode.\n\nYou can also move a whole array of sprites with one line of code by\nsupplying the array as the argument.\n```js\ng.move(arrayOfSprites);\n```\nSo now you can easily move the player, but what happens when the\nplayer reaches the edges of the screen?\n\n\u003ca id='boundries'\u003e\u003c/a\u003e\n##### Containing sprites inside the screen boundaries\n\nUse Ga's `contain` method to keep sprites inside the boundaries of\nthe screen.\n```js\ng.contain(player, g.stage.localBounds);\n```\nThe first argument is the sprite you want to contain, and the second\nargument is any JavaScript object with an `x`, `y`, `width`, and\n`height` property. As a convenience, all Ga sprites have a property\ncalled `localBounds` that return an object with this information.\n\nAs you learnt earlier, `stage` is the root container object for all Ga's sprites, and it has\nthe same width and height as the `canvas`. That means you can use its\n`localBounds` property to keep the sprite contained inside the canvas.\n\nBut you can alternatively supply a custom object to do the same thing. Here's how:\n\n```js\ng.contain(\n  player, \n  {\n    x: 0,\n    y: 0,\n    width: 512,\n    height: 512\n  }\n);\n```\nThis will contain the `player` sprite to an area defined by the\ndimensions of the object. This is really convenient if you want to\nprecisely fine-tune the area in which the object should be contained.\n\n`contain` has an extra useful feature. If the sprite reaches one of\nthe containment edges, `contain` will return a string that tells you\nwhich edge it reached: \"top\", \"right\", \"bottom\", or \"left\". Here's how\nyou could use this feature to find out which edge of the canvas the\nsprite is touching:\n\n```js\nvar playerHitsEdges = g.contain(player, g.stage.localBounds);\n\n//Display the edge of canvas that the player hit\nif (playerHitsEdges) {\n  message.content \n    = \"The player hit the \" + playerHitsEdges + \" of the canvas\";\n}\n```\n\u003ca id='collisionenemy'\u003e\u003c/a\u003e\n##### Collision with the enemies\n\nWhen the player hits any of the enemies, the width of the health bar\ndecreases and the player becomes semi-transparent.\n\n![Treasure Hunter](/tutorials/screenshots/07.png)\n\nHow does this work?\n\nGa has a full suite of useful 2D geometric and tile-based collision\ndetection methods. You can read all about them in Ga's `examples`\nfolder. Treasure Hunter only uses one of these collision methods:\n`hitTestRectangle`. It takes two rectangular sprites and tells you\nwhether they're overlapping. It will return `true` if they are, and\n`false` if they aren't.\n```\ng.hitTestRectangle(spriteOne, spriteTwo);\n```\nHere's how the code in the `play` function uses `hitTestRectangle` to\ncheck for a collision between any of the enemies and the player.\n```js\n//Set `playerHit` to `false` before checking for a collision\nvar playerHit = false;\n\n//Loop through all the sprites in the `enemies` array\nenemies.forEach(function(enemy) {\n\n  //Move the enemy\n  g.move(enemy);\n\n  //Check the enemy's screen boundaries\n  var enemyHitsEdges = g.contain(enemy, g.stage.localBounds);\n\n  //If the enemy hits the top or bottom of the stage, reverse\n  //its direction\n  if (enemyHitsEdges === \"top\" || enemyHitsEdges === \"bottom\") {\n    enemy.vy *= -1;\n  }\n\n  //Test for a collision. If any of the enemies are touching\n  //the player, set `playerHit` to `true`\n  if(g.hitTestRectangle(player, enemy)) {\n    playerHit = true;\n  }\n});\n\n//If the player is hit...\nif(playerHit) {\n\n  //Make the player semi-transparent\n  player.alpha = 0.5;\n\n  //Reduce the width of the health bar's inner rectangle by 1 pixel\n  healthBar.inner.width -= 1;\n\n} else {\n\n  //Make the player fully opaque (non-transparent) if it hasn't been hit\n  player.alpha = 1;\n}\n```\nThis bit of code creates a variable called `playerHit`, which is\ninitialized to `false` just before the `forEach` loop checks all the\nenemies for a collision.\n```js\nvar playerHit = false;\n```\n(Because the `play` function runs 60 times per second, `playerHit`\nwill be reinitialized to `false` on every new frame.)\n\nIf `hitTestRectangle` returns `true`, the `forEach` loop sets\n`playerHit` to `true`.\n\n```js\nif(g.hitTestRectangle(player, enemy)) {\n  playerHit = true;\n}\n```\n\nIf the player has been hit, the code makes the player semi-transparent by\nsetting its `alpha` value to 0.5. It also reduces the width of the\n`healthBar`'s `inner` sprite by 1 pixel.\n\n```js\nif(playerHit) {\n\n  //Make the player semi-transparent\n  player.alpha = 0.5;\n\n  //Reduce the width of the health bar's inner rectangle by 1 pixel\n  healthBar.inner.width -= 1;\n\n} else {\n\n  //Make the player fully opaque (non-transparent) if it hasn't been hit\n  player.alpha = 1;\n}\n```\nYou can set the `alpha` property of sprites to any value between `0`\n(fully transparent) to `1` (fully opaque). A value of `0.5` makes it\nsemi-transparent.b (**Alpha** is a\nwell-worn graphic design term that just means **transparency**.)\n\nThis bit of code also uses the `move` method to move the enemies, and\n`contain` to keep them contained inside the canvas. The code also uses\nthe return value of `contain` to find out if the enemy is hitting the\ntop or bottom of the canvas. If it hits the top or bottom, the enemy's direction is\nreversed with the help of this code:\n\n```js\n//Check the enemy's screen boundaries\nvar enemyHitsEdges = g.contain(enemy, g.stage.localBounds);\n\n//If the enemy hits the top or bottom of the stage, reverse\n//its direction\nif (enemyHitsEdges === \"top\" || enemyHitsEdges === \"bottom\") {\n  enemy.vy *= -1;\n}\n```\n\nMultiplying the enemy's `vy` (vertical velocity) value by negative 1\nmakes it go in the opposite direction. It's a really simple **bounce**\neffect.\n\n\u003ca id='collisiontreasure'\u003e\u003c/a\u003e\n###### Collision with the treasure\n\nIf the player touches the treasure (the yellow square), the `chimes`\nsound plays. The player can then\ncarry the treasure to the exit. The treasure is centered over the player and\nmoves along with it. \n\n![Treasure Hunter](/tutorials/screenshots/08.png)\n\nHere's the code from the `play` function that achieves these effects.\n\n```js\n//Check for a collision between the player and the treasure\nif (g.hitTestRectangle(player, treasure)) {\n\n  //If the treasure is touching the player, center it over the player\n  treasure.x = player.x + 8;\n  treasure.y = player.y + 8;\n\n  if(!treasure.pickedUp) {\n\n    //If the treasure hasn't already been picked up,\n    //play the `chimes` sound\n    chimes.play();\n    treasure.pickedUp = true;\n  };\n}\n```\nYou can see that the code uses `hitTestRectangle` inside an `if`\nstatement to test for a collision between the player and the treasure.\n```js\nif (g.hitTestRectangle(player, treasure)) {\n```\nIf it's `true`, the treasure is centered over the player.\n\n```js\ntreasure.x = player.x + 8;\ntreasure.y = player.y + 8;\n```\n\nIf `treasure.pickedUp` is `false`, then you know that the treasure hasn't already been \npicked up, and you can play the `chimes` sound:\n```js\nchimes.play();\n```\nIn addition to `play` Ga's sound objects also have a few more methods that you can use to control them:\n`pause`, `restart` and `playFrom`. (Use `playFrom` to start playing\nthe sound from a specific second in the sound file, like this:\n`soundObject.playFrom(5)`. This will make the sound start playing from\nthe 5 second mark.)\n\nYou can also set the sound object's `volume` by assigning\na value between 0 and 1. Here's how to set the `volume` to mid-level\n(50%).\n```js\nsoundObject.volume = 0.5;\n```\nYou can set the sound object's `pan` by assigning a value between -1 (left speaker)\nto 1 (right speaker). A pan value of 0 makes the sound equal volume in\nboth speakers. Here's how you could set the `pan` to be slightly more\nprominent in the left speaker.\n```js\nsoundObject.pan = -0.2;\n```\nIf you want to make a sound repeat continuously, set its `loop` property to `true`.\n```js\nsoundObject.loop = true;\n```\nGa uses a [lightweight wrapper for the WebAudio\nAPI](https://gist.github.com/kittykatattack/cd41b480e94fd32d8ad5) to achieve all these\neffects.\n\nBecause you don't want to play the `chimes` sound more than once after\nthe treasure has been picked up, the code sets `treasure.pickedUp` to\n`true` just after the sound plays.\n```js\ntreasure.pickedUp = true;\n```\nNow that the player has picked up the treasure, how can you check for\nthe end of the game?\n\n\u003ca id='endinggame1'\u003e\u003c/a\u003e\n##### Ending the game\n\nThere are two ways the game can end. The player's health can run out,\nin which case the game is lost. Or, the player can successfully carry\nthe treasure to the exit, in which case the game is won. If either of\nthese two conditions are met,  the game's `state` is set to `end` and\nthe `message` text's `content` displays the outcome. Here's the last\nbit of code in the `play` function that does this:\n```js\n//Does the player have enough health? If the width of the `innerBar`\n//is less than zero, end the game and display \"You lost!\"\nif (healthBar.inner.width \u003c 0) {\n  g.state = end;\n  message.content = \"You lost!\";\n}\n\n//If the player has brought the treasure to the exit,\n//end the game and display \"You won!\"\nif (g.hitTestRectangle(treasure, exit)) {\n  g.state = end;\n  message.content = \"You won!\";\n}\n\n```\nThe `end` function is really simple. It just hides the `gameScene` and\ndisplays the `gameOverScene`.\n```js\nfunction end() {\n  gameScene.visible = false;\n  gameOverScene.visible = true;\n}\n\n```\nAnd that's it for Treasure Hunter! Before you continue, try making\nyour own game from scratch using some of these same techniques. When\nyou're ready, read on!\n\n\u003ca id='usingimages'\u003e\u003c/a\u003e\n### Using images\n\nThere are three main ways you can use images in your Ga games. \n\n- Use individual image files for each sprite.\n- Use a **texture atlas**. This is a single image file that includes\n  sub-images for each sprite in your game. The image file is\n  accompanied by a matching JSON\n  data file that describes the name, size and location of each\n  sub-image.\n- Use a **tileset** (also known as a **spritesheet**). This is also a single\n  image file that includes sub-images for each sprite. However, unlike a\n  texture atlas, it doesn't come with a JSON file describing the\n  sprite data. Instead, you need to specify the size and location of\n  each sprite in your game code with JavaScript. This can have some\n  advantages over a texture atlas in certain circumstances.\n\nAll three ways of making image sprites use Ga's `sprite` method.\nHere's the simplest way of using it to make an image sprite.\n```js\nvar imageSprite = g.sprite(\"images/theSpriteImage.png\");\n```\nIn\nthis next section we'll update Treasure Hunter with image sprites, and\nyou'll learn all three ways of adding images to your games.\n\n(All the images in this section were created by Lanea Zimmerman. You\ncan find more of her artwork\n[here](http://opengameart.org/users/sharm).\nThanks, Lanea!)\n\n\u003ca id='individualimages'\u003e\u003c/a\u003e\n#### Individual images\n\nOpen and play the next version of Treasure Hunter:\n`02_treasureHunterImages.html` (you'll find it in the `tutorials`\nfolder.) It plays exactly the same as the first version, but all the\ncolored squares have been replaced by images.\n\n[![Treasure Hunter](/tutorials/screenshots/09.png)](https://cdn.rawgit.com/kittykatattack/ga/master/tutorials/02_treasureHunterImages.html)\n\n(Click the image and follow the link to play the game.) Take a look at the source code, and you'll notice that the game logic\nand structure is exactly the same as the first version of the game.\nThe only thing that's changed is the appearance of the sprites.\nHow was this done?\n\n\u003ca id='loadingimagefile'\u003e\u003c/a\u003e\n##### Loading image files \n\nEach sprite in the game uses an individual PNG image file. You'll find\nall the images in the tutorials' `images` sub-folder.\n\n![Treasure Hunter](/tutorials/screenshots/10.png)\n\nBefore you can use them to make sprites, you need to pre-load them into\nGa's `assets`. The easiest way to do this is to list the image names,\nwith their full file paths, in Ga's assets array when you first\ninitialize the engine.\n```js\nvar g = ga(\n  512, 512, setup,\n  [\n    \"images/explorer.png\",\n    \"images/dungeon.png\",\n    \"images/blob.png\",\n    \"images/treasure.png\",\n    \"images/door.png\",\n    \"sounds/chimes.wav\"\n  ]\n);\ng.start();\n```\n(If you open up the JavaScript console in the web browser, you can\nmonitor the loading progress of these assets.)\n\nNow you can access any of these images in your game code like this:\n```js\ng.image(\"images/blob.png\")\n```\nThis is just a short-cut for accessing the image directly in the\n`assets` object like this:\n```js\ng.assets[\"images/blob.png\"]\n```\nYou can use whichever style you prefer. In any case, the image file\nis just an ordinary JavaScript `Image` object, so you can use\nit the same way you would any other `Image` object. \n\nAlthough pre-loading the images and other assets is the simplest way\nto get them into your game, you can also load assets at any other time\nusing the `assets` object's `load` method. Just supply an array of strings\nthat list the asset names and their file paths.\n```js\ng.assets.load([\n  \"images/imageOne.png\", \n  \"images/imageTwo.png\",\n  \"sounds/chimes.wav\"\n]);\n```\nNext, assign a callback function called `whenLoaded` that will run when the assets have\nloaded. \n```js\ng.assets.whenLoaded = function() {\n  //Do something when the assets have loaded\n};\n```\nNow that you've loaded the images into the game, let's find out how to\nuse them to make sprites.\n\n\u003ca id='makingsprites'\u003e\u003c/a\u003e\n##### Making sprites with images\n\nCreate an image sprite using the `sprite` method using the same format you learnt\nearlier. Here's how to create a sprite using the `dungeon.png` image.\n(`dungeon.png` is a 512 by 512 pixel background image.)\n\n    dungeon = g.sprite(\"images/dungeon.png\");\n\nThat's all! Now instead of displaying as a simple colored rectangle,\nthe sprite will be displayed as a 512 by 512 image. There's no need\nto specify the width or height, because Ga figures that our for you\nautomatically based on the size of the image. You can use all the other\nsprite properties, like `x`, `y`, `width`, and `height`, just as you\nwould with ordinary rectangle sprites. \n\nHere's the code from the `setup` function that creates the dungeon\nbackground, exit door, player and treasure, and adds them all to the\n`gameScene` group. \n```js\n//The dungeon background\ndungeon = g.sprite(\"images/dungeon.png\");\n\n//The exit door\nexit = g.sprite(\"images/door.png\");\nexit.x = 32;\n\n//The player sprite\nplayer = g.sprite(\"images/explorer.png\");\nplayer.x = 68;\nplayer.y = g.canvas.height / 2 - player.halfWidth;\n\n//Create the treasure\ntreasure = g.sprite(\"images/treasure.png\");\n\n//Position it next to the left edge of the canvas\ntreasure.x = g.canvas.width - treasure.width - 32;\ntreasure.y = g.canvas.height / 2 - treasure.halfHeight;\n\n//Create a `pickedUp` property on the treasure to help us Figure\n//out whether or not the treasure has been picked up by the player\ntreasure.pickedUp = false;\n\n//Create the `gameScene` group and add all the sprites\ngameScene = g.group(dungeon, exit, player, treasure);\n```\n(As a slightly more efficient improvement to the\noriginal version of this code, `group` creates the `gameScene` and groups\nthe sprites in a single step.)\n\nLook familiar? That's right, the only code that has changed are the\nlines that create the sprites. This modularity is a feature of Ga that lets you create quick\ngame prototypes using simple shapes that you can easily swap out for\ndetailed images as your game ideas develops. The rest of the code in the\ngame can remain as-is.\n\n\u003ca id='finetuning'\u003e\u003c/a\u003e\n##### Fine-tuning the containment area\n\nOne small improvement that was made to this new version Treasure\nHunter is the new way that the sprites are contained inside the walls of the\ndungeon. They're contained in such a way that naturally matches the 2.5D perspective of the\nartwork, as shown by the green square in this screen shot:\n\n![Treasure Hunter](/tutorials/screenshots/11.png)\n\nThis is a very easy modification to make. All you need to do is supply\nthe `contain` method with a custom object that defines the size and\nposition of the containing rectangle. Here's how:\n```js\ng.contain(\n  player,\n  {\n    x: 32, y: 16,\n    width: g.canvas.width - 32,\n    height: g.canvas.height - 32\n  }\n);\n```\nJust tweak the `x`, `y`, `width` and `height` values so that the\ncontaining area looks natural for the game you're making.\n\n\u003ca id='textureatlas'\u003e\u003c/a\u003e\n#### Using a texture atlas\n\nIf you’re working on a big, complex game, you’ll want a fast and\nefficient way to work with images. A texture atlas can help you do\nthis. A texture atlas is actually two separate files that are closely\nrelated:\n\n- A single PNG **tileset** image file that contains all the images you\n  want to use in your game. (A tileset image is sometimes called a\n  spritesheet.)\n-\tA JSON file that describes the size and position of those sub-images\n  in the tileset.\n\nUsing a texture atlas is a big time saver. You can arrange the\ntileset’s sub-images in any order and the JSON file will keep\ntrack of their sizes and positions for you. This is really convenient\nbecause it means the sizes and positions of the sub-images aren’t\nhard-coded into your game program. If you make changes to the tileset,\nlike adding images, resizing them, or removing them, just re-publish\nthe JSON file and your game will use that updated data to display the\nimages correctly. If you’re going to be making anything bigger than a\nvery small game, you’ll definitely want to use a texture atlas.\n\nThe de-facto standard for tileset JSON data is the format that is\noutput by a popular software tool called [Texture Packer](https://www.codeandweb.com/texturepacker) (Texture\nPacker's \"Essential\" license is free ). Even if you\ndon’t use Texture Packer, similar tools like [Shoebox](http://renderhjs.net/shoebox/) output JSON files\nin the same format. Let’s find out how to use it to make a texture\natlas with Texture Packer, and how to load it into a game.\n\n\u003ca id='preparingimages'\u003e\u003c/a\u003e\n##### Preparing the images\n\nYou first need individual PNG images for each image in your game.\nYou've already got them for Treasure Hunter, so you're all set. Open Texture\nPacker and choose the {JS} configuration option. Drag your game images\ninto its workspace. You can also point Texture Packer to any folder that contains\nyour images. Texture Packer will automatically arrange the images on a\nsingle tileset image, and give them names that match their original\nimage file names. It will give them a 2 pixel padding by default.\n\n![Texture Packer](/tutorials/screenshots/12.png)\n\nEach of the sub-images in the atlas is called a **frame**. Although\nit's just one big image, the texture atlas has 5 frames. The name of each\nframe is the same its original PNG file name: \"dungeon.png\",\n\"blob.png\", \"explorer.png\", \"treasure.png\" and \"door.png\". These\nframes names are used to help the atlas reference each sub-image.\n\nWhen you’re done, make sure the Data Format is set to JSON (Hash) and\nclick the Publish button. Choose the file name and location, and save the\npublished files. You’ll end up with a PNG file and a JSON file. In\nthis example my file names are `treasureHunter.json` and\n`treasureHunter.png`. To make\nyour life easier, just keep both files in your project’s `images`\nfolder. (Think of the JSON file as extra metadata for the image file.)\n\n\u003ca id='loadingatlas'\u003e\u003c/a\u003e\n##### loading the texture atlas\n\nTo load the texture atlas into your game, just include the JSON file\nin Ga's assets array when you initialize the game.\n\n```js\nvar g = ga(\n  512, 512, setup,\n  [\n    \"images/treasureHunter.json\",\n    \"sounds/chimes.wav\"\n  ]\n);\ng.start();\n```\nThat's all! You don't have to load the PNG file - Ga does that\nautomatically in the background. The JSON file is all you need to tell\nGa which tileset frame (sub-image) to display.\n\nNow if you want to use a frame from the texture atlas to make a\nsprite, you can do it like this:\n\n```js\nanySprite = g.sprite(\"frameName.png\");\n```\nGa will create the sprite and display the correct image from the\ntexture atlas's tileset.\n\nHere's how to you could create the sprites in Treasure Hunter using\ntexture atlas frames:\n```js\n//The dungeon background image\ndungeon = g.sprite(\"dungeon.png\");\n\n//The exit door\nexit = g.sprite(\"door.png\");\nexit.x = 32;\n\n//The player sprite\nplayer = g.sprite(\"explorer.png\");\nplayer.x = 68;\nplayer.y = g.canvas.height / 2 - player.halfWidth;\n\n//The treasure\ntreasure = g.sprite(\"treasure.png\");\n```\nThat's all! Ga knows that those are texture atlas frame names, not individual\nimages, and it displays them directly from the tileset.\n\nIf you ever need to access the texture atlas's JSON file in your game,\nyou can get it like this:\n```js\njsonFile = g.json(\"jsonFileName.json\");\n```\nTake a look at `treasureHunterAtlas.html` file in the `tutorials` folder\nto see a working example of how to load a texture atlas and use it to\nmake sprites.\n\n\u003ca id='alienarmada'\u003e\u003c/a\u003e\n### Alien Armada\n\nThe next example game in this series of tutorials is Alien Armada. Can you\ndestroy 60 aliens before one of them lands and destroys the Earth? Click the\nimage link below to play the game:\n\n[![Alien Armada](/tutorials/screenshots/13.png)](https://cdn.rawgit.com/kittykatattack/ga/master/tutorials/04_alienArmada.html)\n\nUse the arrow keys to move and press the space bar to shoot. The\naliens descend from the top of the screen with\nincreasing frequency as the game progresses. Here's how the game is played:\n\n![Alien Armada gameplay](/tutorials/screenshots/14.png)\n\nAlien Armada illustrates some new techniques that you'll definitely want\nto use in your games:\n\n- Load and use custom fonts.\n- Automatically scale and center the game to the browser window. \n- Display a loading progress bar while the game assets load.\n- Shoot bullets.\n- Create sprites with multiple image states.\n- Generate random enemies.\n- Remove sprites from a game.\n- Display a game score.\n- Reset and restart a game.\n\nYou'll find the fully commented Alien Armada source code in the\n`tutorials` folder. Make sure to take a look at it so that you can see\nall of this code in its proper context. Its general structure is identical\nto Treasure Hunter, with the addition of these new techniques. Let's\nfind out how they were implemented.\n\n\u003ca id='customfonts'\u003e\u003c/a\u003e\n#### Load and use a custom font\n\nAlien Armada uses a custom font called `emulogic.ttf` to display the\nscore at the top right corner of the screen. The font file is\npreloaded with the rest of the asset files (sounds and images) in the assets array that\ninitializes the game. \n```js\nvar g = ga(\n  480, 320, setup,\n  [\n    \"images/alienArmada.json\",\n    \"sounds/explosion.mp3\",\n    \"sounds/music.mp3\",\n    \"sounds/shoot.mp3\",\n    \"fonts/emulogic.ttf\"  //\u003c- The custom font.\n  ],\n  load\n);\n```\nTo use the font, create a `text` sprite in the game's `setup`\nfunction. The `text` method's second argument is a\nstring that describes the font's point size and name: \"20px emulogic\".  \n```js\nscoreDisplay = g.text(\"0\", \"20px emulogic\", \"#00FF00\", 400, 10);\n```\nYou can and load and use any fonts in TTF, OTF, TTC or WOFF format.\n\n\u003ca id='scalebrowser'\u003e\u003c/a\u003e\n#### Scale and center the game in the browser\n\nYou'll notice that when you play Alien Armada, the game is centered\ninside the browser window, and automatically fills to the window's maximum\nwidth and height.\n\n![Alien Armada gameplay](/tutorials/screenshots/15.png)\n\nThe browser background that borders the game is set to a dark gray\ncolor. This\nis thanks to one of Ga's built-in features: the\n`scaleToWindow` method. To use it, call `scaleToWindow` just after\nyou call Ga's `start` method, like this:\n```js\ng.start();\ng.scaleToWindow();\n```\n`scaleToWindow` will center your game for the best fit. Long, wide\ngame screens are centered vertically. Tall or square screens are\ncentered horizontally. If you want to specify your own browser\nbackground color that borders the game, supply it in `scaleToWindow`'s\narguments, like this:\n```js\ng.scaleToWindow(\"seaGreen\");\n```\nFor best results, make sure you set the default margins and paddings\non all your HTML elements to `0`. The following bit of CSS does the\ntrick: \n```js\n\u003cstyle\u003e * {margin: 0; padding: 0;} \u003c/style\u003e\n```\nHere's how this `\u003cstyle\u003e` tag is inserted into Alien Armada's HTML\ncontainer page:\n```js\n\u003c!doctype html\u003e\n\u003cmeta charset=\"utf-8\"\u003e\n\u003ctitle\u003eAlien Armada\u003c/title\u003e\n\u003cstyle\u003e * {margin: 0; padding: 0;} \u003c/style\u003e\n```\nOptionally, if you want to make sure that your game dynamically\nre-sizes and re-centers itself if the user changes the browser window\nsize, just drop in this bit of code: \n```js\nwindow.addEventListener(\"resize\", function(event){ \n  g.scaleToWindow();\n});\n```\nAdd it just after you've\ncalled `scaleToWindow` the first time. Here's what all this code looks\nlike in context:\n```js\n//...Initialize Ga...\n\ng.start();\ng.scaleToWindow();\nwindow.addEventListener(\"resize\", function(event){ \n  g.scaleToWindow();\n});\n\n//...The rest of your game code...\n\n```\nIf you want to find out how it works, or you want to customize it further, you'll\nfind the `scaleToWindow` method in Ga's `plugins.js` file. \n\n\u003ca id='progressbar'\u003e\u003c/a\u003e\n####A loading progress bar\n\nAlien Armada loads three MP3 sound files: a shooting sound, an\nexplosion sound, and music. The music sound is about 2 MB in size so\non a slow network connection this sound could take a few seconds to\nload. While this is happening players would just see the blank canvas while Alien Armada\nloads. Some players might think the game has frozen, so the game\nhelpfully implements a loading bar to inform\nplayers that the assets are loading. It's a blue rectangle that expands from left to right, and\ndisplays a number that tells you the percentage of game assets\nloaded so far.\n\n![Loading progress bar](/tutorials/screenshots/16.png)\n\nThis is a feature that's built into the Ga engine. \nGa has a optional loading state that runs while game assets are being\nloaded. You can decide what you want to have happen during the loading\nstate. All you need to do is write a function with code that should\nrun while the assets are loading, and tell Ga what the name of that\nfunction is. Ga's engine will automatically run that function in a\nloop until the assets have finished loading.\n\nLet's find out how this works in Alien Armada. The game code tells \nGa to use a function called `load` during the loading state. It does\nthis by listing `load` as the final argument\nin Ga's initialization constructor. (Look for `load` in the code below):\n```js\nvar g = ga(\n  480, 320, setup,\n  [\n    \"images/alienArmada.json\",\n    \"sounds/explosion.mp3\",\n    \"sounds/music.mp3\",\n    \"sounds/shoot.mp3\",\n    \"fonts/emulogic.ttf\"\n  ],\n  load  //\u003c- This is the function that will run while loading.\n);\n```\nThis tells Ga to run the `load` function in a loop while the assets\nare loading. \n\nHere's the `load` function from Alien Armada. It creates a `progressBar` object, and then calls the progress bar's\n`update` method each frame. \n```js\nfunction load(){\n\n    //Use Ga's built in `progressBar` to display a loading progress\n    //percentage bar while the assets are loading.\n    g.progressBar.create(g.canvas, g.assets);\n\n    //Call the `progressBar`'s `update` method each frame. \n    g.progressBar.update();\n}\n```\nAfter the assets have loaded, the `setup` state runs automatically. The first\nthing it does is call the `progressBar`'s `remove` method to make the\nbar disappear:\n```js\nfunction setup() {\n\n  g.progressBar.remove();\n \n  //... the rest of the setup function...\n}\n```\nYou'll find the `progressBar` code in the `plugins.js` file. It's\nmeant to be a very simple example that you can use as the basis for\nwriting your own custom loading animation, if you want to. You can run any code you\nlike in the `load` function, so it's entirely up to you to decide what\nshould happen or what is displayed while your game is loading.\n\n\u003ca id='shootingbullets'\u003e\u003c/a\u003e\n#### Shooting bullets\n\nHow can you make the cannon fire bullets? \n\nWhen you press the space bar, the cannon fires bullets at the enemies.\nThe bullets start from the end of the cannon's turret, and travel up the\ncanvas at 7 pixels per frame. If they hit an alien, the alien\nexplodes. If a bullet misses and flies past the top of the stage, the\ngame code removes it.\n\n![Firing bullets](/tutorials/screenshots/17.png)\n\nTo implement a bullet-firing system in your game, the first thing you\nneed is an array to store the all the bullet sprites.\n```js\nbullets = [];\n```\nThis `bullets` array is initialized in the game's `setup` function.\n\nYou can then use Ga's custom `shoot` method to make any sprite fire\nbullets in any direction. Here's the general format you can use to\nimplement the `shoot` method.\n```js\ng.shoot(\n  cannon,      //The shooting sprite\n  4.71,        //The angle, in radians, at which to shoot (4.71 is up)\n  16,          //The bullet's offset from the center of the sprite\n  7,           //The bullet's speed (pixels per frame)\n  bullets,     //The array used to store the bullets\n\n  //A function that returns the sprite that should\n  //be used to make each bullet\n  function() {\n    return g.sprite(\"bullet.png\");\n  }\n);\n\n```\nThe second argument determines the angle, in radians, at which the\nbullet should travel. 4.71 radians, used in this example, is up. 0 is\nto the right, 1.57 is down, and 3.14 is to the left.\n\nThe last argument is a function that returns a sprite that should be\nused as the bullet. In this example the bullet is created using using the \n\"bullet.png\" frame from the game's loaded texture atlas.\n```js\nfunction() {\n  return g.sprite(\"bullet.png\");\n}\n```\nReplace this function with your own to create any kind of custom\nbullet you might need.\n\nWhen will your bullets be fired? You can call the `shoot` method\nwhenever you want to make bullets, at any point in your code. In Alien\nArmada, bullets are fired when the player presses the space key. So\nthe game implements this by calling `shoot` inside the space key's\n`press` method. Here's how:\n```js\ng.key.space.press = function() {\n\n  g.shoot(\n    cannon,      //The shooting sprite\n    4.71,        //The angle at which to shoot (4.71 is up)\n    16,          //The bullet's offset from the center\n    7,           //The bullet's speed (pixels per frame)\n    bullets,     //The array used to store the bullets\n\n    //A function that returns the sprite that should\n    //be used to make each bullet\n    function() {\n      return g.sprite(\"bullet.png\");\n    }\n  );\n\n  //Play the shoot sound.\n  shootSound.play();\n};\n\n```\nYou can see that the `press` method also makes the `shootSound` play.\n(The code above is initialized in the game's `setup` function.)\n\nThere's one more thing you need to do: you have to make the bullets move.\nYou can do this with some code inside the game's looping `play` function. Use Ga's\n`move` method and supply the `bullets` array as an argument:\n```js\ng.move(bullets);\n```\nThe `move` method automatically loops through all the sprites in the\narray and updates their x and y positions with the value of their `vx` and `vy` velocity values.\n\nSo now you know how the bullets are created and animated. But what happens when\nthey hit one of the aliens?\n\n\u003ca id='spritestates'\u003e\u003c/a\u003e\n#### Sprite states\n\nWhen a bullet hits an alien, a yellow explosion image appears. This\nsimple effect is created by giving each alien sprite two states: a `normal`\nstate and a `destroyed` state. Aliens are created with their states\nset to `normal`. If they're hit, their states change to `destroyed`.\n\n![The sprite's states](/tutorials/screenshots/18.png)\n\nHow does this system work?\n\nFirst, let's take a look at the Alien Armada tileset, shown here:\n\n![The Alien Armada tileset](/tutorials/screenshots/19.png)\n\nYou can see two image frames that define these two states: `alien.png`\nand `explosion.png`. Before you create the sprite, first create an\narray that lists these two frames: \n```js\nvar alienFrames = [\n  \"alien.png\", \n  \"explosion.png\"\n];\n```\nNext use the `alienFrames` array to initialize the `alien` sprite.\n```js\nalien = g.sprite(alienFrames);\n```\nIf you prefer, you could combine these two steps into one, like this:\n```js\nalien = g.sprite([\n  \"alien.png\", \n  \"explosion.png\"\n]);\n```\nThis loads the sprite up with two frames. Frame `0` is the `alien.png`\nframe, and frame `1` is the `explosion.png` frame. Frame `0` is\ndisplayed by default by when the sprite is first created. \n\nYou can use the sprite's `show` method to display any other frame number on the\nsprite, like this:\n```js\nalien.show(1);\n```\nThe code above will set the alien to frame number one, which is the\n`explosion.png` frame.\n\nTo make your code a little more readable, its a good idea to define\nyour sprite's states in a special `states` object. Give each state a\nname, with a value that corresponds to that state's frame number.\nHere's how you could define two states on the alien: `normal` and\n`destroyed`:\n```js\nalien.states = {\n  normal: 0,\n  destroyed: 1\n};\n```\n`alien.states.normal` now has the value `0`, and\n`alien.states.destroyed` now has the value `1`. That means you could\ndisplay the alien's `normal` state like this:\n```js\nalien.show(alien.states.normal);\n```\nAnd display the alien's `destroyed` state like this:\n```js\nalien.show(alien.states.destroyed);\n```\nThis makes your code a little more readable because you can tell at a\nglance which sprite state is being displayed.\n\n(Note: Ga also has a lower-level `gotoAndStop` method that does\nexactly the\nsame thing as `show`. Although you're free use `gotoAndStop` in your\ngame code, by convention it's only used internally by Ga's rendering\nengine.)\n\n\u003ca id='randomaliens'\u003e\u003c/a\u003e\n#### Generating random aliens\n\nAlien Armada generates aliens at any 1 of 14 randomly chosen positions\njust above the top boundary of the stage. The aliens first appear\ninfrequently, but gradually start to\nappear at an ever-increasing rate. This makes the game gradually more\ndifficult as it\nprogresses. Let's find out how these two features are implemented.\n\n\u003ca id='timingaliens'\u003e\u003c/a\u003e\n##### Timing the aliens\n\nWhen the game starts, the first new alien is generated after 100\nframes have elapsed. A variable called `alienFrequency`, initialized in\nthe game's `setup` function is used to help track this. it's\ninitialized to 100.\n```js\nalienFrequency = 100;\n```\nAnother variable called `alienTimer` is used to count the number of\nof frames that have elapsed between the previously generated alien,\nand the next one. \n```js\nalienTimer = 0;\n```\n`alienTimer` is updated by 1 each frame in the `play` function (the game loop).\nWhen `alienTimer` reaches the value of `alienFrequency`, a new alien\nsprite is generated. Here's the code from the `play` function that\ndoes this. (This code omits the actual code that generates the alien\nsprite - we'll look at that ahead)\n```js\n//Add one to the alienTimer.\nalienTimer++;\n\n//Make a new alien if `alienTimer` equals the `alienFrequency`.\nif(alienTimer === alienFrequency) {\n\n  //... Create the alien: see ahead for the missing code that does this...\n\n  //Set the `alienTimer` back to zero.\n  alienTimer = 0;\n\n  //Reduce `alienFrequency` by one to gradually increase\n  //the frequency that aliens are created\n  if(alienFrequency \u003e 2){  \n    alienFrequency--;\n  }\n}\n```\nYou can see in the code above that `alienFrequency` is reduced by 1\nafter the sprite has been created. That will make the next alien appear 1 frame earlier than the\nprevious alien, and which is why the rate of falling aliens slowly\nincreases. You can also see that the `alienTimer` is set back to 0 after the sprite\nhas been created so that it can restart counting towards making\nthe next new alien. \n\n\u003ca id='randomposition'\u003e\u003c/a\u003e\n##### The aliens' random start positions\n\nBefore we generate any aliens, we need an array to store all the alien\nsprites. An empty array called `aliens` is initialized in the `setup`\nfunction for this purpose.\n```js\naliens = [];\n```\nEach alien is then created in the `play` function, inside the same\n`if` statement we looked at above. This code has a lot of work to do:\n\n- It sets the alien's image frames and states. \n- Its sets the alien's velocity (`vx` and `vy`.) \n- It positions the alien at a random horizontal position above the top stage boundary.\n- And, finally, it pushes the alien into the `aliens` array. \n\nHere's the full code that does all this:\n```js\n//Add one to the alienTimer.\nalienTimer++;\n\n//Make a new alien if `alienTimer` equals the `alienFrequency`.\nif(alienTimer === alienFrequency) {\n\n  //Create the alien.\n  //Assign two frames from the texture atlas as the \n  //alien's two states.\n  var alienFrames = [\n    \"alien.png\", \n    \"explosion.png\"\n  ];\n\n  //Initialize the alien sprite with the frames\n  var alien = g.sprite(alienFrames);\n\n  //Define some states on the alien that correspond\n  //to its two frames.\n  alien.states = {\n    normal: 0,\n    destroyed: 1\n  };\n  \n  //Set its y position above the screen boundary.\n  alien.y = 0 - alien.height;\n  \n  //Assign the alien a random x position.\n  alien.x = g.randomInt(0, 14) * alien.width;\n  \n  //Set its speed.\n  alien.vy = 1;\n  \n  //Push the alien into the `aliens` array.\n  aliens.push(alien);\n\n  //Set the `alienTimer` back to zero.\n  alienTimer = 0;\n\n  //Reduce `alienFrequency` by one to gradually increase\n  //the frequency that aliens are created\n  if(alienFrequency \u003e 2){  \n    alienFrequency--;\n  }\n}\n```\nYou can see in the code above that th alien's `y` position places it\nout of sight just above the stage's top boundary.\n```js\nalien.y = 0 - alien.height;\n```\nIt's `x` position, however, is random. \n```js\nalien.x = g.randomInt(0, 14) * alien.width;\n```\nThis code places it in one of 15 possible random positions (0 to 14) above the\ntop of the stage. Here's an illustration of these positions:\n\n![The Alien Armada tileset](/tutorials/screenshots/20.png)\n\nFinally, and very importantly, the code pushes the alien sprite into\nthe `aliens` array.\n```js\naliens.push(alien);\n```\nAll this code starts pumping out aliens at a steadily increasing rate.\n\n\u003ca id='movingaliens'\u003e\u003c/a\u003e\n#### Moving the aliens\n\nHow do we make the aliens move? In exactly the same way made the\nbullets move. You'll notice in the code above that\neach alien is initialized with a `vy` (vertical velocity) value of 1.\n```js\nalien.vy = 1;\n```\nWhen this value is applied to the alien's `y` position, it will make the alien move down, towards the bottom of the stage,\nat the rate of 1 pixel per frame. All the alien sprites in the game are in\nthe `aliens` array. So to make all of them move you need to loop\nthrough each sprite in the `aliens` array each frame and add their\n`vy` values to their `y` positions. Some code like this in the `play`\nfunction would work:\n```js\naliens.forEach(function(alien){\n  alien.y += alien.vy;\n});\n```\nHowever, its easier just to use Ga's convenient built-in `move` function. Just\nsupply `move` with the array of sprites that you want to move, like\nthis:\n```js\ng.move(aliens);\n```\nThis updates the aliens positions with their velocities automatically.\n\n\u003ca id='explodealiens'\u003e\u003c/a\u003e\n#### Making the aliens explode\n\nNow that you know how to change the alien's state, how can you use\nthis skill to create the explosion effect? Here's the simplified code\nfrom Alien Armada that shows you how to do this. Use `hitTestRectangle` to\ncheck for a collision between an alien and bullet. If a collision is detected,\nremove the bullet, show the alien's `destroyed` state, and then remove\nthe alien after a delay of one second.\n\n```js\nif (g.hitTestRectangle(alien, bullet)) {\n\n  //Remove the bullet sprite.\n  g.remove(bullet);\n\n  //Show the alien's `destroyed` state.\n  alien.show(alien.states.destroyed);\n\n  //Wait for 1 second (1000 milliseconds) then \n  //remove the alien sprite.\n  g.wait(1000, function(){\n    g.remove(alien);\n  });\n}\n\n```\nYou can use Ga's universal `remove` function to remove any sprite from a\na game, like this:\n```js\ng.remove(anySprite);\n```\nYou can optionally use it to remove more than one sprite at a time by\nlisting the sprites to remove in the arguments, like this:\n```js\ng.remove(spriteOne, spriteTwo, spriteThree);\n```\nYou can even use it to remove all the sprites in an array of sprites. Just\nsupply the sprite array as `remove`'s only argument:\n```js\ng.remove(arrayOfSprites);\n```\nThis will both make the sprites disappear from the screen, and also\nempty them out of the array that they were in.\n\nGa also has a convenient method called `wait` that will run a function\nafter any delay (in milliseconds) that you specify. The Alien Armada\ngame code uses `wait` to remove the alien after a one second delay,\nlike this:\n```js\ng.wait(1000, function(){\n  g.remove(alien);\n});\n\n```\nThis allows the alien to display its `explosion` image state for one\nsecond before it disappears from the game.\n\nThese are the basic techniques involved in making the aliens explode\nand removing the aliens and bullets from the game when they collide.\nBut the actual code used in Alien Armada is a little more complex. That's\nbecause the code uses nested `filter` loops to loop through all the bullets\nand aliens so that they can be checked against each other for\ncollisions. The code also plays an explosion sound when a collision\noccurs, and updates the score by 1. Here's all the code from the\ngame's `play` function that does this. (If you're new to JavaScript's\n`filter` loops, you can [read about how to use them here.](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter))\n\n```js\n//Check for a collision between the aliens and the bullets.\n//Filter through each alien in the `aliens` array.\naliens = aliens.filter(function(alien) {\n\n  //A variable to help check if the alien is\n  //alive or dead.\n  var alienIsAlive = true;\n\n  //Filter though all the bullets.\n  bullets = bullets.filter(function(bullet) {\n\n    //Check for a collision between an alien and bullet.\n    if (g.hitTestRectangle(alien, bullet)) {\n\n      //Remove the bullet sprite.\n      g.remove(bullet);\n\n      //Show the alien's `destroyed` state.\n      alien.show(alien.states.destroyed);\n\n      //You could alternatively use the frame number,\n      //like this:\n      //alien.show(1);\n\n      //Play the explosion sound.\n      explosionSound.play();\n\n      //Stop the alien from moving.\n      alien.vy = 0;\n\n      //Set `alienAlive` to false so that it can be\n      //removed from the array.\n      alienIsAlive = false;\n\n      //Wait for 1 second (1000 milliseconds) then \n      //remove the alien sprite.\n      g.wait(1000, function(){\n        g.remove(alien);\n      });\n\n      //Update the score.\n      score += 1;\n\n      //Remove the bullet from the `bullets array.\n      return false;\n\n    } else {\n\n      //If there's no collision, keep the bullet in the\n      //bullets array.\n      return true;\n    }\n  });\n\n  //Return the value of `alienIsAlive` back to the \n  //filter loop. If it's `true`, the alien will be\n  //kept in the `aliens` array. \n  //If it's `false` it will be removed from the `aliens` array.\n  return alienIsAlive;\n});\n```\nAs long as the filter loops return `true`, the current sprite being\nchecked will remain in the array. If there's a collision, however, the\nloops return `false` and the current alien and bullet will be removed\nfrom their arrays. \n\nAnd that's how the game's collision works!\n\n\u003ca id='displayingscore'\u003e\u003c/a\u003e\n#### Displaying the score\n\nAnother new feature introduced by Alien Armada is a dynamic score\ndisplay. Each time an alien is hit, the score at the top right corner\nof the game screen increases by one. How does this work?\n\nAlien Armada initializes a `text` sprite called `scoreDisplay` in the\ngame's `setup` function.\n```js\nscoreDisplay = g.text(\"0\", \"20px emulogic\", \"#00FF00\", 400, 10);\n```\nYou saw in the previous section\nthat 1 is added to the game's `score` variable each time an alien is\nhit:\n```js\nscore += 1;\n```\nTo visibly update the score, all you need to do is set the `score`\nvalue as the `scoreDisplay`'s `content`, like this:\n```js\nscoreDisplay.content = score;\n```\nAnd that's all there is to it!\n\n\u003ca id='endinggame2'\u003e\u003c/a\u003e\n#### Ending and resetting the game\n\nThere are two ways the game can end. Either the player shoots down 60\naliens, in which case the player wins. Or, one of the aliens has to travel\nbeyond the bottom edge of the stage, in which case the aliens win. \n\nA simple if statement in the `play` function checks for this. If\neither condition becomes `true`, the `winner` is set to either\n\"player\" or \"aliens\" and the game's `state` is changed to `end`.\n```js\n//The player wins if the score matches the value\n//of `scoreNeededToWin`, which is 60\nif (score === scoreNeededToWin) {\n\n  //Set the player as the winner.\n  winner = \"player\";\n\n  //Change the game's state to `end`.\n  g.state = end;\n}\n\n//The aliens win if one of them reaches the bottom of\n//the stage.\naliens.forEach(function(alien){\n\n  //Check to see if the `alien`'s `y` position is greater\n  //than the `stage`'s `height`\n  if (alien.y \u003e g.stage.height) { \n\n    //Set the aliens as the winner.\n    winner = \"aliens\";\n\n    //Change the game's state to `end`.\n    g.state = end;\n  }\n});\n```\nThe `end` function pauses the game, so that the animation freezes. It\nthen displays the `gameOverMessage`, which will either be \"Earth\nSaved!\" or \"Earth Destroyed!\", depending on the outcome. As an extra\ntouch, the music `volume` is also set to 50%. Then after a\ndelay of 3 seconds, a function named `reset` is called. Here's the\ncomplete `end` function that does all this:\n\n```js\nfunction end() {\n\n  //Pause the game loop.\n  g.pause();\n  \n  //Create the game over message text.\n  gameOverMessage = g.text(\"\", \"20px emulogic\", \"#00FF00\", 90, 120);\n\n  //Reduce the music volume by half.\n  //1 is full volume, 0 is no volume, and 0.5 is half volume.\n  music.volume = 0.5;\n\n  //Display \"Earth Saved!\" if the player wins.\n  if (winner === \"player\") {\n    gameOverMessage.content = \"Earth Saved!\";\n    gameOverMessage.x = 120;\n  }\n\n  //Display \"Earth Destroyed!\" if the aliens win.\n  if (winner === \"aliens\") {\n    gameOverMessage.content = \"Earth Destroyed!\";  \n  }\n\n  //Wait for 3 seconds then run the `reset` function.\n  g.wait(3000, function(){\n    reset(); \n  });\n}\n```\nThe `reset` function resets all of the game variables back to their\nstarting values. It also turns the music volume back up to 1. It uses\nthe `remove` function to remove any remaining sprites from the\n`aliens` and `bullets` arrays, so that those arrays can be\nre-populated when the game starts again. `remove` is also used to\nremove the `gameOverMessage`, and the `cannon` sprite is re-centered\nat the bottom of the stage. Finally, the game `state` is set back to\n`play`, and the game loop is un-paused by calling Ga's `resume`\nmethod.\n```js\nfunction reset() {\n\n  //Reset the game variables.\n  score = 0;\n  alienFrequency = 100;\n  alienTimer = 0;\n  winner = \"\";\n\n  //Set the music back to full volume.\n  music.volume = 1;\n\n  //Remove any remaining alien and bullet sprites.\n  //The universal `remove` method will loop through\n  //all the sprites in an array of sprites, removed them\n  //from their parent container, and splice them out of the array.\n  g.remove(aliens);\n  g.remove(bullets);\n\n  //You can also use the universal `remove` function to remove.\n  //a single sprite.\n  g.remove(gameOverMessage);\n\n  //Re-center the cannon.\n  g.stage.putBottom(cannon, 0, -40);\n\n  //Change the game state back to `play`.\n  g.state = play;\n  g.resume();\n}\n```\nAnd this is all the code needed to start the game again. You can play\nAlien Armada as many times as you like and it will reset and restart\nitself like this endlessly.\n\n\u003ca id='flappyfairy'\u003e\u003c/a\u003e\n### Flappy Fairy!\n\nFlappy Fairy is a homage to one of the infamous games ever made: [Flappy\nBird](http://en.wikipedia.org/wiki/Flappy_Bird). Click the\nimage link below to play the game:\n\n[![FlappyFairy](/tutorials/screenshots/21.png)](https://cdn.rawgit.com/kittykatattack/ga/master/tutorials/05_flappyFairy.html)\n\nClick the \"Go\" button, and game will launch in fullscreen mode. Tap\nanywhere on the screen to make the fairy fly, and help her navigate\nthrough the gaps in 15 pillars to reach the finish. A trail of multicolored \nfairy dust follows the fairy as she flies through the maze. \nIf she hits one of the green blocks she explodes in a shower of dust. \nBut if she manages to navigate through the increasingly narrowing gaps between \nall 15 pillars, she reaches a big floating “Finish” sign. \n\n![Flappy Fairy gameplay](/tutorials/screenshots/22.png)\n\nIf you can make a game like Flappy Fairy, you can make almost any\nother kind of 2D action game. In addition to using the all techniques you've\nalready learnt, Flappy Fairy introduces some exciting new ones:\n\n- Launching a game in fullscreen mode.\n- Make a click-able button. \n- Create an animated sprite.\n- Use a `tilingSprite` to make a scrolling background.\n- Use particle effects.\n\nYou'll find the fully commented Flappy Fairy source code in the\n`tutorials` folder. Make sure to take a look at it so that you can see\nall of this code in its proper context. Its general structure is identical\nto the other games in this tutorial, with the addition of these new techniques. Let's\nfind out how they were implemented.\n\n\u003ca id='launchagameinfullscreenmode'\u003e\u003c/a\u003e\n#### Launch a game in fullscreen mode\n\nWhen you start Flappy Fairy by clicking the \"Go\" button,\nthe game expands to fill your entire screen. This is done with\nthe help of a built-in method called `enableFullscreen`.\n```js\ng.enableFullsreen(listOfAsciiExitKeyCodes);\n```\nIt's one optional argument is a list of Ascii key codes. They refer to keyboard\nkeys that could be used to exit fullscreen mode. For example, if you\nwant fullscreen mode to exit if a user presses upper-case \"X\" or\nlower-case \"x\", list their Ascii code values in the arguments like\nthis:\n```js\ng.enableFullscreen(88, 120);\n```\n(88 is \"X\" and 120 is \"x\".) You can list as many key codes as you\nlike. If you leave these arguments out, the default `esc` key will do the trick.\n\n`enableFullscreen`'s behaviour is very simple: it just launches fullscreen mode\nwhenever the user releases the pointer (mouse or touch) over the\ncanvas. Add it just below your game's `start` method, like this:\n```js\nvar g = ga(\n  910, 512, setupTitleScreen,\n  [\n    \"images/flappyFairy/flappyFairy.json\"\n  ]\n);\n\ng.start();\ng.enableFullscreen(88, 120); //\u003c- Add it here\n```\nIt's a quick and easy way to make any games run fullscreen.\n\n(Note: Fullscreen mode is different than `scaleToWindow` because it\ncompletely takes over the user's screen. And I mean completely: the\nbrowser disappears and the only thing on the screen is your game. That's cool, but many users\nwill find it disorienting and become stressed or panicked if they\ncan't figure out how to exit your game. So you do decide to run your game in fullscreen\nmode, be confident that users will know how to exit it. Or, play it\nsafe and just use `scaleToWindow`, which still looks great but doesn't\ntake over the entire browser UI.)\n\n\u003ca id='makeabutton'\u003e\u003c/a\u003e\n#### Make a button\n\nThe game starts when you press the \"Go\" button. The \"Go\" button is a special sprite\ncalled a `button`. `button` sprites have 3 image frame states: up, over and\ndown. You can create a `button` with three states like this:\n```js\ngoButton = g.button([\n  \"up.png\",\n  \"over.png\",\n  \"down.png\"\n]);\n```\n`up.png` is an image that shows what the button should look like when the it's not\ninteracting with the pointer. `over.png` shows what the button looks\nlike when the pointer is over it, and `down.png` is the image that is\ndisplayed when the pointer presses down on the button.\n\n![Button states](/tutorials/screenshots/23.png)\n\n(The `down.png` image is offset slightly down and to the right, so it\nlooks like its being pressed down.) You can assign any images you like\nto these states, and the `button`\nwill display them automatically based on how the pointer is\ninteracting with it. \n\n(Note: If your game is touch-only, you might have only\ntwo button states: up and down. In that case, just assign two image frames,\nand Ga will assume they refer to the up and down states.)\n\nButtons have special methods that you can define: `press`,\n`release`,`over`, `out` and `tap`. You can assign any code you like to\nthese methods. For example, here's how you could change the game's\nstate when the user releases the `playButton`:\n```js\ngoButton.release = function(){\n  g.state = setupGame;\n};\n```\nButtons also have a Boolean (true/false) property called `enabled`\nthat you\ncan set to `false` if you want to disable the button. (Set `enabled`\nto `true` to re-enable it.) You can also use the button's `state`\nproperty to find out if the button state is currently `\"up\"`, `\"over\"`\nor `\"down\"`. (These state values are strings.)\n\nImportant! You can give **any** sprite the qualities of button just by\nsetting its `interactive` property to `true`, like this:\n```js\nanySprite.interactive = true;\n```\nThis will give the sprite `press`, `release`, `over`, `out` and `tap`\nmethods, and the same `state` property as ordinary buttons. This means\nthat you can make any sprite click-able, which is really useful for a\nwide variety of interactive games.\n\nYou can also make the `stage` object interactive, which turns the whole \ngame screen into an interactive button:\n```js\ng.stage.interactive = true;\n```\nFor more detail on how to use buttons, see the `buttons.html` file\nin the `examples` folder.\n\n\u003ca id='animatingsprites'\u003e\u003c/a\u003e\n#### Animating sprites\n\nA neat feature of Flappy Fairy is that the fairy character flaps her wings\nwhen she's flying up. This animation was created by rapidly displaying 3\nsimple images in a continuous loop. Each image displays a slightly different\nframe of the animation, as shown below:\n\n![Animation frames](/tutorials/screenshots/24.png)\n\nThese three images are just three ordinary frames in the game's texture atlas, called\n`0.png`, `1.png` and `2.png`.\nBut how can you turn a sequence of frames like this into a sprite\nanimation?\n\nFirst, create an array that defines the frames of the animation, like\nthis:\n```js\nvar fairyFrames = [\n  \"0.png\", \n  \"1.png\", \n  \"2.png\"\n];\n```\nThen create a sprite using those frames, like this:\n```js\nvar fairy = g.sprite(fairyFrames);\n```\nOr, if you prefer, you can combine this into one step:\n```js\nvar fairy = g.sprite([\n  \"0.png\", \n  \"1.png\", \n  \"2.png\"\n]);\n\n```\nAny sprite with more than one image frame automatically becomes an\nanimated sprite. If you want the animation frames to start playing,\njust call the sprite's `play` method:\n```js\nfairy.play();\n```\nThe frames will automatically play in a continuous loop. If you don't want them\nto loop, set `loop` to `false`.\n```js\nfairy.loop = false;\n```\nUse the `stop` method to stop an animation:\n```js\nfairy.stop();\n```\nIf you want to know whether or not a sprite's animation is currently\nplaying, use the Boolean (true/false) `playing` property to find out.\n\nHow quickly or slowly do you want the animation to play? You can set\nthe animation's frames-per-second (`fps`) like this:\n```js\nfairy.fps = 24;\n```\nA sprite animation's frame rate is independent of the game's frame\nrate. That gives you a lot of flexibility to fine-tune sprite\nanimations.\n\nWhat if you don't want to use all the sprite's image frames in the\nanimation, only some of them? You can use the `playSequence` method.\nFor example, imagine that you have a sprite with 30 frames, but you\nonly want to play frames 10 to 15 as part of the animation. Use the\n`playSequence` method and supply it with an array containing two\nnumbers: the first and last frames of the sequence you want to play.\n```js\nanimatedSprite.playSequence([10, 15]);\n```\nNow only the frames between 10 to 15 will play as part of the animation. To make\nthis more readable, you can define the sequence as an array that\ndescribes what those animated frames actually do. For example, perhaps\nthey define a character's walk cycle. You could create an array called\n`walkCycle` that defines those frames:\n```js\nvar walkCycle = [10, 15];\n```\nThen use that array with `playSequence`, like this:\n```js\nanimatedSprite.playSequence(walkCycle);\n```\nThat's a bit more code to write, but much more readable!\n\nFor more details on Ga's sprite animation system and what you can do\nwith it, see the `keyframeAnimation.html`,\n`textureAtlasAnimation.html` and  `animationStates.html` file in the `examples` folder.\n\n\u003ca id='makingthefairyfly'\u003e\u003c/a\u003e\n#### Making the fairy fly\n\nNow that you know how to animate a sprite, how is Flappy Fairy's\nflying animation triggered when you tap on the game screen?\n\nA value of `0.05`, which represents gravity, is subtracted from the\nfairy's `y` position each frame in the `play` function. This is the\ngravity effect that pulls the fairy to the bottom of the screen. \n```js\nfairy.vy += -0.05;\nfairy.y -= fairy.vy;\n```\nBut when you tap the screen, the fairy flies up. This is thanks to\nGa's built-in `pointer` object. It has a `tap` method w","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkittykatattack%2Fga","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkittykatattack%2Fga","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkittykatattack%2Fga/lists"}