Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

https://github.com/kittykatattack/ga

The world's tiniest, cutest and funnest game engine
https://github.com/kittykatattack/ga

Last synced: 25 days ago
JSON representation

The world's tiniest, cutest and funnest game engine

Lists

README

        

![Ga](/tutorials/screenshots/logoAndIllustration.png)

Ga
===

*"Ga!"*
*- A baby's exclamation of surprise.*

*Ga* is a tiny, cute and friendly system for making HTML5 games or any other
kind interactive media. You can use it to make any kind of 2D action
game you can imagine, with unbelievably tiny file sizes (under 6.5k!)

Take a look at the feature list and the `examples` folder to get
started. Keep scrolling, and you'll find a complete beginner's
tutorial ahead. If you've never made a game before, the tutorials are
the best place to start.

Ga 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!

[中文文档](./README_zh_CN.md)

### Table of contents:

1. [Features](#features)
2. [The Plugins](#plugins)
3. [Coming soon...](#comingsoon)
4. [Ga's philosophy and technical constraints](#philosophy)
5. [Minifying, crushing and compressing](#minifying)
6. [Contributions and Licencing](#contibutions)
7. [Hexi](#hexi)
8. [Tutorials](#tutorials)
1. [Treasure Hunter](#treasure)
1. [Setting up the HTML container page](#settingup)
2. [Initializing the Ga engine](#initializing)
3. [Define your "global" variables](#defineglobals)
4. [Initialize your game with a setup function](#setupfunction)
1. [Customizing the canvas](#customizing)
2. [Creating the `chimes` sound object](#creatingsound)
3. [Creating game scenes](#gamescenes)
4. [Making sprites](#makingsprites)
5. [Positioning sprites](#positioningsprites)
6. [Assigning dynamic properties](#dynamicproperties)
7. [Creating the enemy sprites](#enemysprites)
8. [The health bar](#healthbar)
9. [The game over scene](#gameoverscene)
10. [Keyboard interactivity](#keyboard)
11. [Setting the game state](#gamestate)
5. [Game logic with the play function loop](#gamelogic)
1. [Moving the player sprite](#movingplayer)
2. [Containing sprites inside the screen boundaries](#boundries)
3. [Collision with the enemies](#collisionenemy)
1. [Collision with the treasure](#collisiontreasure)
4. [Ending the game](#endinggame1)
6. [Using images](#usingimages)
1. [Individual images](#individualimages)
1. [Loading image files](#loadingimagefile)
2. [Making sprites with images](#makingsprites)
3. [Fine-tuning the containment area](#finetuning)
7. [Using a texture atlas](#textureatlas)
1. [Preparing the images](#preparingimages)
2. [loading the texture atlas](#loadingatlas)
2. [Alien Armada](#alienarmada)
1. [Load and use a custom font](#customfonts)
2. [Scale and center the game in the browser](#scalebrowser)
3. [A loading progress bar](#progressbar)
4. [Shooting bullets](#shootingbullets)
5. [Sprite states](#spritestates)
6. [Generating random aliens](#randomaliens)
1. [Timing the aliens](#timingaliens)
2. [The aliens' random start positions](#randomposition)
7. [Moving the aliens](#movingaliens)
8. [Making the aliens explode](#explodealiens)
9. [Displaying the score](#displayingscore)
10. [Ending and resetting the game](#endinggame2)
3. [Flappy Fairy!](#flappyfairy)
1. [Launch a game in fullscreen mode](#launchagameinfullscreenmode)
2. [Make a button](#makeabutton)
3. [Making the fairy fly](#makingthefairyfly)
4. [Make a scrolling background](#makeascrollingbackground)
5. [The fairy dust explosions](#thefairydustexplosions)
6. [Use a particle emitter](#useaparticleemitter)
7. [Creating and moving the pillars](#creatingandmovingthepillars)
9. [A Guide to the examples](#aguidetotheexamples)


Features
--------

Here's Ga's core feature list:

- All the most important sprites you need: rectangles, circles, lines,
text, image sprites and animated "MovieClip" style sprites. You can make any of these
sprites with one only line of code. You can also create your own custom sprite
types.
- A complete scene graph with nested child-parent hierarchies (including
a `stage`, and `addChild`/`removeChild` methods), local and global
coordinates, depth layers, and rotation pivots.
- `group` sprites together to make game scenes.
- A game loop with a user-definable `fps` and fully customizable and
drop-dead-simple game state manager. `pause` and `resume` the game
loop at any time.
- Tileset (spritesheet) support using `frame` and `filmstrip` methods to make
sprites using tileset frames.
- Built-in texture atlas support for the popular Texture Packer
format. Use a sprite's `setTexture` method if you want to change a sprite's image source while the game is running
- A keyframe animation and state manager for sprites. Use `show` to
display a sprite's image state. Use `play` or `playSequence` to play
a sequence of frames (in a `loop` if you want to). Use
`show` to display a specific frame number. Use `fps` to set the
frame rate for sprite animations which is independent from the game's
frame rate.
- Interactive `button` sprites with `up`, `over` and `down` states.
- Any sprite can be set as `interactive` to receive mouse and touch
actions.
Intuitive `press`, `release`, `over`, `out` and `tap` methods for buttons and interactive
sprites.
- Easy-to-use keyboard key bindings. The arrow and space keys are
built-in, and you can easily define your own with the `keyboard`
method.
- A built-in universal `pointer` that works with both the mouse and
touch. Assign your own custom `press`, `release` and `tap` methods
or use any of the pointer's built-in properties: `isUp`, `isDown`,
`tapped`, `x` and `y`. Define as many pointers as you need for multi-touch.
- Conveniently position sprites relative to other sprites using
`putTop`, `putRight`, `putBottom`, `putLeft` and `putCenter`.
- A universal asset loader to pre-load images, fonts, sounds and JSON
data files. All popular file formats are supported. You can load new assets into the game at
any time.
- An optional `load` state that lets you run actions while assets are
loading. You can use the `load` state to add a loading progress bar.
- A fast and focused canvas-based rendering engine.
- A sophisticated game loop using a fixed timestep with variable rendering
and sprite interpolation. That means you get butter-smooth sprite animations
at any framerate.
- A `plugins.js` file full of extra tools.
- A compact and powerful "Haiku" style API that's centered on shallow,
composable components. Get more done writing less code.
- Ga is totally hackable. Overwrite any of its default methods or objects
with your own at compile or run time.
- Yes, Ga is mobile friendly!
- Yes, the core `ga.js` engine is less than 6.5k minified and zipped!
That makes Ga the world's smallest, most light-weight full featured game engine.
It's all you need to start making any any 2D action, puzzle or
strategy game.

And the coolest part? If you were alone on a desert island with only
a solar powered laptop, an unlimited supply of
coconuts, and a copy of `ga.js` you could recreate the entire history of 2D video games,
from SpaceWar! to Flappy Bird. And all of it would fit on a 3.5 inch
floppy disk.


### The plugins

But there's more! Ga comes with a `plugins.js` file that includes a
huge number of useful tools for making games. You can use as many or
as few of these tools as you want to. Here are some of the goodies
you'll find in `plugins.js`:

- Import and play sounds using a built-in WebAudio API sound manager.
Control sounds with `play`, `pause`, `stop`, `restart`,
`playFrom`, `fadeIn` and `fadeOut` methods. Change a sound's `volume` and `pan`.
- Generate your own custom sound effects from pure code with
the versatile `soundEffect` method.
- Shake sprites or the screen with `shake`.
- Tween functions for sprite and scene transitions: `slide`,
`fadeIn`, `fadeOut`, `pulse`, `breathe`, `wobble`, `strobe` and
some useful low-level tweening methods to help you create your own
custom tweens.
- Make a sprite follow a connected series of waypoints with `walkPath`
and `walkCurve`.
- A handful of useful convenience functions: `followEase`,
`followConstant`,
`angle`, `distance`, `rotateAroundSprite`, `rotateAroundPoint`, `wait`,
`randomInt`, `randomFloat`, `contain` and `outsideBounds`.
- A fast, universal `hit` method that handles collision testing and
reactions (blocking and bounce) for all types of sprites. Use one collision method for
everything: rectangles, circles, points, and arrays of sprites.
Easy!
- A companion suite of lightweight, low-level 2D geometric collision methods.
- A loading progress bar for game assets.
- Make sprites shoot things with `shoot`.
- Easily plot sprites in a grid formation with `grid`.
- Use a `tilingSprite` to easily create a seamless scrolling background.
- Tiled Editor support using `makeTiledWorld`. Design your game in
Tiled Editor and access all the sprites, layers and objects directly
in your game code. It's an extremely fun, quick and easy way to make
games.
- A versatile, `hitTestTile` method that handles all the collision
checking you'll need for tile-based games. You can use it in combination
with the any of the 2D geometric collision methods for optimized
broadphase/narrowphase collision checking if you want to.
- A `particleEffect` function for creating all kinds of particle
effects for games. Use the `emitter` function to create a constant
stream of particles.
- Use `updateMap` to keep a tile-based world's map data array up-to-date
with moving sprites.
- Create a `worldCamera` that follows sprites around a scrolling game
world.
- 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.

To use the plugins, just copy/paste the code you want to use from `plugins.js` into your game.
Or, if you're not worried about the extra size,
just link the whole thing; it's really tiny anyway!

If you want to get fancy, you can alternatively create your own `custom.js` file that
contains a small custom sub-set of the plugins
you want to use for your game. Your `custom.js` file can load at
compile time, so it's ready to use before your game code runs.
(See the `plugins.js` file for instructions on how to do this).


### Coming soon...

- Tiled Editor isometric maps support.
- Many more examples including complete game prototypes.
- Additional documentation, examples, and tutorials.


Ga's philosophy and technical constraints
-----------------------------------------

- The `ga.js` core game engine file can't ever be bigger that 6.5k
minified and zipped. Yes, 6.5k! This makes it suitable for making games for micro game
competitions, like [js13k](http://js13kgames.com). This absurdly
low overhead means you can drop a full-featured 2D action game into a web page and have it load and play almost
instantly. But, more
importantly, this constraint also discourages feature-creep and keeps
the engine lean and focused.
- The API has to be fun, intuitive and expressive with as little
boilerplate code as possible. Game designers should be
free to explore their imaginations without tripping over a tangled
and messy API. Less typing, Less thinking!
- The source code must be easily readable and comment-rich so that
everyone can learn from it. It should also be architecturally flat
so that anyone can rip it apart and easily drop it into something
else.
- For the same reasons, all the source code must be hand-written written from scratch without any 3rd party dependencies (external libraries.)
- Any special features, like Tiled Editor support, can be added to the
plugins.js file, so that game developers can pick and choose a
minimal custom set of components they want for specific games without bloating the core engine.


Minifying, crushing and compressing
-----------------------------------

The Ga repository doesn't include the minified and compressed version
of the source code, because you should probably optimize that yourself. I recommend
first minifying the code using with [Google Closure
Compiler](http://closure-compiler.appspot.com/home) (Simple mode only) or
[UglifyJS2](https://github.com/mishoo/UglifyJS2). Google Closure will
give you best minification, and Ga's source code is optimized for it.

Then, zip it. I recommend [gzip](http://www.gzip.org).

For more aggressive optimization, you could further try running the
minified code through
[JSCrush](http://www.iteral.com/jscrush/). Although it sometimes makes
things worse rather than better - you'll have to test it with your
code.

Note: If you're using Google Closure Compiler from the command line, set the `--language_in`
flag to `ECMASCRIPT5`, like this:

`java -jar ~/compiler.jar --language_in=ECMASCRIPT5 --js ga.js --js_output_file ga.min.js`


Contributions and Licencing
---------------------------
It's Ga's ambition to be the world's tiniest, cutest and funnest game engine.
Please help! If you find something that's bad, please help to fix it.
If you find something good, please help to make it better. Ga
welcomes any and all contributions!

+1 Bonus Points for removing code and simplifying the architecture. +2 Bonus
Points for making the code easier to understand. The aim of this
project is to discover the smallest universal set of reusable
components required to make
the widest variety of games possible with the least amount of code.
What is the fundamental alphabet, or the primary colours, of game design?
That's what we're searching. Can you help?

Checkout 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).

Please 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.

**Coding style**: Unconventionally, Ga
uses **functional composition** patterns (the [module
pattern](http://toddmotto.com/mastering-the-module-pattern/) and
[mixins](http://raganwald.com/2014/04/10/mixins-forwarding-delegation.html))
for object creation instead of inheritance. Why? It's really
just an experiment in coding like that. It also means the code
becomes a little more compact.

Licensing? Ga is vehemently *unlicenesed*.
That means its freer than free.

It's like a pebble.
You can pick it up and throw into the sea.


Hexi
----
Do 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!


Tutorials
---------

How do you make a video game? These tutorials will show you how.

But first, you should have a reasonable understanding of HTML and
JavaScript. You don't have to be an expert, just an ambitious beginner
with an eagerness to learn. If you don't know HTML and JavaScript, the
best place to start learning it is this book:

[Foundation Game Design with HTML5 and JavaScript](http://www.apress.com/9781430247166)

I know for a fact that it's the best book, because I wrote it :)

There are also some good internet resources to help get you started:

[Khan Academy: Computer
Programming](http://www.khanacademy.org/computing/cs)

[Code Academy:
JavaScript](http://www.codecademy.com/tracks/javascript)

Ok, got it?
Do you know what JavaScript variables, functions, arrays and objects are and how to
use them? Good, then read on!


### Treasure Hunter

The first game we're going to make is a simple object collection and
enemy avoidance game called Treasure Hunter. Open the file
`01_treasureHunter.html` in a web browser. (You'll find it in Ga's
`tutorials` folder, and you'll need to run it in a
[webserver](https://github.com/nodeapps/http-server)). If you don't
want to bother setting up a webserver, use a text-editor like
[Brackets](http://brackets.io) that will launch one for you
automatically (see Brackets' documentation for this feature).

[![Treasure Hunter](/tutorials/screenshots/01.png)](https://cdn.rawgit.com/kittykatattack/ga/master/tutorials/01_treasureHunter.html)

(Follow the link in the image above to play the game.) Use the keyboard to move the explorer (the blue square), collect the
treasure (the yellow square), avoid the monsters (the red squares) and
reach the exit (the green square.) Yes, you have to use your
imagination - for now.

Don't be fooled by it's apparent simplicity. Treasure Hunter contains
everything a video game needs:

- Interactivity
- Collision
- Sprites
- A game loop
- Scenes
- game logic
- "Juice" (in the form of sounds)

(What's juice? [Watch this
video](https://www.youtube.com/watch?v=Fy0aCDmgnxg) and
[read this article](http://www.gamasutra.com/view/feature/130848/how_to_prototype_a_game_in_under_7_.php?print=1) to learn
about this essential game design ingredient.)

If you can make a simple game like Treasure Hunter, you can make
almost any other kind of game. Yes, really! Getting from Treasure
Hunter to Skyrim or Zelda
is just a matter of lots of small steps; adding more
detail as you go. How much detail you want to add is up to you.

In the first stage of this tutorial you'll learn how the basic
Treasure Hunter game was made, and then we'll add some fun features like images and
character animation that will give you a complete overview of how the
Ga game engine works.

If you're an experienced game programmer and
quick self-starter, you might find the code in Ga's `examples` folder to
be a more productive place to start learning - check it out. The fully
commented
code in the `examples` folder also details specific, and advanced uses
of features, that aren't
covered in these tutorials. When you're finished working through these
tutorials, the `examples` will take you on the next stage of your
journey.


#### Setting up the HTML container page

Before you can start programming in JavaScript, you need to set up a
minimal HTML container page. The HTML page loads `ga.js` and
`plugins.js` which are the two files you need to use all of Ga's
features. You'll write all your game code inside the last pair of
`` tags before the closing `<body>` tag.

```js
<!doctype html>
<meta charset="utf-8">
<title>Treasure hunter</title>
<body>
<!-- Import the Ga game engine files -->
<script src="../ga.js">

//All of your game code will go here