# ga
**Repository Path**: flashpig8014/ga
## Basic Information
- **Project Name**: ga
- **Description**: ga 游戏引擎
- **Primary Language**: JavaScript
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2021-10-27
- **Last Updated**: 2024-10-23
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README

Ga
===
*"Ga!"*
*- 一个小宝贝惊叹地叫道。*
*Ga* 是一个轻量级、讨人喜欢的、且友好的引擎,用于制作HTML5游戏或其他类型的互动媒体。您可以制作任何您想要的2D动作游戏,并且文件体积小得惊人!(甚至小于6.5k!)
通过阅读引擎特性和`examples`文件夹下的示例来快速上手本引擎。往下滚动,您可以在找到一套完整的、面向新人的教程。如果您曾经没有做过游戏,那么这套教程简直再适合不过了。
Ga 是一个“已经竣工”的软件。正式因为它完美无bug,最近它只有少量的更新。继续往下,您会找到永远使用它的理由!
[English Version](./README.md)
### 目录:
1. [引擎特性](#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)
引擎特性
--------
以下是 Ga 的核心特性:
- 拥有所有您需要的精灵,包括:矩形、圆形、线、文字、图片和动画精灵“MovieClip”。您可以只用一行代码就创建这些精灵。您也可以创建您自己的精灵。
- 一个可嵌套、有父子层次结构、完整的场景图(包括一个`stage`,和`addChild`/`removeChild`方法)。场景图包含了本地和全局坐标系,不同深度的图层以及旋转轴。
- 利用`group` 来构建一组用于游戏场景的精灵。
- 可自定义`fps`(运行帧率)的游戏循环。并且有着简单易用且完全自定义的游戏场景管理器。利用`pause` 和`resume`随时暂停、恢复游戏循环。
- 地图块(或精灵表)可以通过`frame` 和 `filmstrip`方法来调用帧序列以创建精灵。
- 内置的纹理集支持流行的Texture Packer格式。可以调用精灵的`setTexture`方法在游戏中改变精灵的贴图。
- 拥有精灵的关键帧动画和状态管理器。利用 `show`来显示精灵的图像状态。利用`play` 或 `playSequence`方法播放帧序列(可以用`loop` 进行循环播放)。利用`show` 显示特定的帧编号。利用 `fps` 设定精灵动画的帧率,精灵动画的帧率和游戏帧率是相互独立的。
- 拥有 `up`, `over` 和`down`三个状态的可交互精灵按钮`button`。
- 任何精灵都可以被设定为`interactive`(可交互的),它们接受鼠标或触摸屏的控制。
按钮和交互式精灵通过直观的`press`(按下), `release`(松开), `over`(悬浮), `out`(退出)和 `tap` (轻触)方法来操控。
- 简单易用的键盘键位绑定。Ga 内置了方向键和空格键的控制,您也可以通过`keyboard`方法来轻松定义您自己的按键映射。
- 一个用于鼠标和触摸控制的通用指针`pointer` 。定义您自己的 `press`, `release` 和 `tap` 方法或使用指针内置的属性: `isUp`, `isDown`,`tapped`, `x` and `y`。 请定义多点触控所需的所有指针。
- 以下方法可以相对某个精灵的位置放置一个新的精灵:`putTop`, `putRight`, `putBottom`, `putLeft` and `putCenter`。
- 一个全局通用的资源加载器,用于预加载图片、字体、音效和JSON数据文件。Ga 支持所有流行的格式。您也可以随时在游戏中加载新的资源文件。
- 一个可选的`load`状态来保证资源加载时您的游戏处于运行状态。您在`load`状态下可以添加加载进度条。
- 快速且专注的、基于canvas的渲染引擎。
- 顶级的游戏循环,使用固定的时间步长进行可变渲染和精灵插值。 这意味着您可以在任何帧速率下获得流畅的精灵动画。
- `plugins.js` 文件用于存放插件和额外的工具。
- "Haiku"风格的API紧凑但强大,围绕各类简单、但灵活多变可组合的组件展开。用更少的代码完成更多的工作。
- Ga 完全可以自行修改源代码。 在编译或运行时使用您自己的方法覆盖其默认方法或对象。
- 没错,Ga 对移动端也非常友好!
- 而且,精简和压缩后的Ga的核心代码`ga.js` 只有不到6.5k!
这使得Ga成为世界上最小、最轻量级的引擎,不过麻雀虽小,五脏俱全,Ga有所有游戏引擎的特性。
你需要做的只是用它来做2D动作、解密或策略游戏!
最酷的是什么呢?如果您流落荒岛,只有一台太阳能笔记本和无限供应的椰子以及一份`ga.js` 的副本。您可以重建整个2D电子游戏历史,从SpaceWar!到Flappy Brid。而这所有的一切都可以装进小小的3.5英寸软盘。
### 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).
[](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
`