Giter VIP home page Giter VIP logo

gamejs's Introduction

GameJs

GameJs is a JavaScript library for writing 2D games or other interactive graphic applications for the HTML Canvas.

Topics

Drawing on the screen

  • image loading image files
  • graphics image transformation (rotate, transform,...) and drawing with geometric shapes
  • font rendering text

Mouse and keyboard

  • event Recieve events for user input

Audio

  • audio Playback with multiple channels

Game logic

Advanced

Math

Usage

See the examples directory for working examples.

Standalone

HTML File loads GameJs and sets the main module:

<script src="./public/gamejs.min.js"></script>
<script>
    require.setModuleRoot('./javascript/');
    require.run('main')
</script>

The main module javascript/main.js starts the application:

var gamejs = require('gamejs');
gamejs.ready(function() {
    var display = gamejs.display.getSurface();
    ...
});

GameJs as a CommonJs package with browserify

GameJs is a CommonJs package published on NPM. To use it with browserify install the GameJs package in your game's directory:

$ npm install gamejs

And install browserify, if you don't already have it.

$ npm install -g browserify

You can then bundle your application ("main.js") with all its dependencies - including GameJs - like so:

$ browserify ./main.js --out bundled.js

More Help

See the GameJs Website for more help or drop us an email in the Mailing List.

Example application can be found in the examples/ directory.

Development - How to build

GameJs consists of CommonJs modules in ./src/ which we build and jshint with grunt. If you don't already have node and npm, install those. You will also need java on your path for building the distribution file.

Install grunt:

$ npm install -g grunt-cli

In the GameJs folder you cloned, install the dependencies to build using npm:

$ npm install

Build GameJs:

$ grunt

This will create the gamejs-VERSION.js file and a minified gamejs-VERSION.min.js which you can use standalone in the browser, as demonstrated in the examples.

gamejs's People

Contributors

4d47 avatar adriantoine avatar arcman7 avatar danielgtaylor avatar domasx2 avatar dorisenthecat avatar fmunshi avatar gilbert avatar jlfwong avatar lvcivs avatar oberhamsi avatar rejacobson avatar robi42 avatar sorki avatar systemstart avatar tnajdek avatar troyjfarrell avatar weeezes avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gamejs's Issues

requestAnimationFrame

requestanimationframe should be used for gamejs/time. gamejs/time is already prepared to work with it (in fact, that's why it looks so strange).

i'm unsure if it's too early to implement it - browser support good enough? how much work to test?

https://developer.mozilla.org/en/DOM/window.mozRequestAnimationFrame

http://hacks.mozilla.org/2010/08/more-efficient-javascript-animations-with-mozrequestanimationframe/

http://weblogs.mozillazine.org/roc/archives/2010/08/mozrequestanima.html

https://gist.github.com/838785tw

Image transformation doesn't give correct results

When I try to scale image of size 499x640 to 800x600 its bottom is cropped.

I'm using following code to accomplish this:

  var display = gamejs.display.setMode([800, 600]);
  var img = gamejs.image.load(path);
  var dims = img.getSize();
  var simg = gamejs.transform.scale(img, [800/dims[0], 600/dims[1]]);
  display.blit(simg);

I believe it has something to do with float rounding because slightly higher or lower values gives different results (no cropping).
I can provide complete example if required.

less preventDefault()ed keys

it's a PITA that gamejs prevents default from ALL keys so you can't write anything into an

otoh it's useful for SPACE, which would scroll the page or "/" which would open a search field.

wrong function doc

--- vectors.js.orig 2011-06-05 00:30:55.000000000 +0700
+++ vectors.js 2011-06-05 17:13:36.000000000 +0700
@@ -27,7 +27,7 @@

  • multiply vector with scalar or other vector
  • @param {Array} vector [v0, v1]
  • @param {Number|Array} vector or number
    • * @param {Number|Array} result
    • * @returns {Number|Array} result
      */
      exports.multiply = function(a, s) {
      if (typeof s === 'number') {

examples lib path is wrong

Examples try to include a missing script:

File: gamejs/examples/examples-draw/index.html

<script src="../skeleton/public/yabble.js"></script>
<script src="../skeleton/public/gamejs.min.js"></script>

gamejs.min.js does not exist.

Unecessary dependancy in draw.js + matrix

The following code in draw.js

// line 653 of gamejs.js
var m = matrix.translate(matrix.identity(), rDest.left, rDest.top);
m = matrix.multiply(m, src._matrix);
this.context.transform(m[0], m[1], m[2], m[3], m[4], m[5]);

add an unecessary dependancy in code, and could be replaced by:

this.context.translate(rDest.left, rDest.top);

Every example seem to still work, but some unit test (not all of them) of rotation and scale seem to break, maybe some refactoring will be needed with transform.js.

Talking about matrix, if such module exists it should not be so coupled to the transformation matrix (add and multiply ,method only work with one dimension matrix with a definite number of arguments which just break reusability of the module), but moved where specific transform are made.

rect.x rect.y ?

Hi,

I noticed that rect.x and rect.y are missing. They're useful attributes from pygame.Rect, which if there would make porting a little easier. Also, I just like typing r.x rather than r.left.

Not really needed though.

cu.

custom index.html broken with statifier

i would expect the same index.html file to work with the dev server as well as in the static version produced by the statifier.

but a custom index.html does not work at all with the statifier

collidePoint for Mask

Would it be possible to do this?

    this.image = gamejs.image.load("images/hex/hexagon1.png");
    this.mImage = mask.fromSurface(this.image);

    return this.mImage.collidePoint(event.pos); 

Thank you.

Worker misconception

Gamejs worker is for me a set bad practice and misguiding for people not familiar with worker.

Intro:

Gamejs worker is basically create another instance of gamejs in a javascript Web Worker.
When you look at gamejs source code, you can see in several reference at different places to gamejs worker. This behavior is similar to application environment. Still a worker is not an environment, and neither an application clone.

Heavy and useless loading

Instantiating a "heavy" worker with lots of features is not an issue, but when cloning the application in a worker the user has access to lot of component that:

  • he will not use (why load it, if you don't need it)
  • he should not use (e.g. Display, mixer, ...)

Computation performance

A simple worker calculate prime number (ref: gamejs/example/worker) ~4 time faster than gamejs worker implementation.

Below is a simple bench:

  • time counter starts at the beginning of the worker file,
  • time is logged every time a prime number is found.

// Simple worker

  1. 181ms
  2. 281ms
  3. 387ms
  4. 495ms
  5. 608ms

// GameJs worker

  1. 557ms
  2. 968ms
  3. 1386ms
  4. 1832ms
  5. 2291ms

(Instanciation of simple worker is also faster because in actual gamejs Worker implementation, gamejs worker re-instanciate the whole application !)

Coupled and not reusable:

GameJs worker creates a blob that use yabble require implementation and thus is not reusable by people who don't wanna use yabble or this precise implementation.

Misguiding for new-comers:

One of gamejs purpose is to be light and simple to use.
For people who never used advanced concept such as worker and don't go read library source code, they could easily imagine that performance are already optimized and consider that gamejs implementation as their standard.
This is like teaching bad practice.

Rename utils/math

math module name could be quite confusing as long as it's very similar to Math.
Also it's a very wide name for the function it contains.

I would suggest utils/geometry.js, but maybe we could find better name.

provide gamejs as AMD module compatible package

we already have a build step, so providing it as something usable with requirejs shouldn't be too hard.

there's even a converter script for cjs->AMD shipping with requirejs.

the best idea would probably be to produce one gamejs.min.js, which is plain commonjs and one gamejs.min.amd.js, which can be loaded by AMD loaders.

Canvas layers or the art of multi-canvas

We talked a bit about it on irc a month ago,
to recall the main lines:

At some point you can have an advanced game that require lots of resource because of heavy graphics many layered elements.Having multiple layer element and implementing dirty redrawing can be very time consuming and require a complex architecture (not easy to maintain).

I actually experienced it when I wrote a rpg where I used a particule engine to generate blood explosion where blood stayed after explosion uppon the background but behind the main character.
To fix my problem I had to sacrifice my lazy redrawing and spend several days changing my game logic.
With multiple canvas I could have move background to a another canvas, and apply those blood explosion on the background canvas.

This technique also spare performance because if you have a fancy background it will not repaint it on every frame (at least not by js)

Note that we can simply keep single canvas by default, and people who would do advanced game could use this feature just by updating simply option in a constructor.

missing sprite.collideCircle

http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.collide_circle

pygame.sprite.collide_circle
collision detection between two sprites, using circles.
pygame.sprite.collide_circle(left, right): return bool
Tests for collision between two sprites, by testing to see if two circles centered on the sprites overlap. If the sprites have a "radius" attribute, that is used to create the circle, otherwise a circle is created that is big enough to completely enclose the sprites rect as given by the "rect" attribute. Intended to be passed as a collided callback function to the *collide functions. Sprites must have a "rect" and an optional "radius" attribute.
New in pygame 1.8.1

onerror handler to display debug/error info

this would be useful for displaying "browser is too old", etc messages to enduser

as well as showing and explaining yabble problems or just JS exceptions to game developer

scale(s,[10,10]) modifies the input s.

Hi,

scale(s,[10,10]) modifies the input s. Whereas it should return a new scaled surface, not modify the input.

Using scale(s.clone(),[10,10]) to copy input first is a work around.

implement type/typelist argument for gamejs.event.get

especially now that we have worker events, this is very handy:

  • pygame.event.get(): return Eventlist
  • gamejs.event.get(type): return Eventlist
  • gamejs.event.get(types): return Eventlist

If a type or array of types is given only those messages will be returned and removed from the queue.

Strange behavior and dependancy for surfaceArray util

When constructor param is an array (of dimensions), SurfaceArray depends on display module. I think we should only be able to inject a surface.
To me, display refers more to the canvas and should not be injected (c.f. noise example) or used on a static call (using array param).

The actual bahavior allow somebody to write:

display = gamejs.display.setMode([800, 600]);
surface = new gamejs.Surface([200, 200]);
displayArray = new gamejs.SurfaceArray([100, 100]);
// use some pattern to modify surface
// displayArray.set([..]);
SurfaceArray.blitArray(surface, displayArray);

When I read the code above and see the result I feel like:
"WOW, Somehow I get noise out of my display (canvas) image data on my surface, what is this dark magic ?"

Is there any particular reason for that ?

Suggestion of a more proper use would be:

displayArray = new gamejs.SurfaceArray(display.getSurface());
// OR
displayArray = new gamejs.SurfaceArray(someSurface);
// I don't like the following because it will create a surface behind the scene which simply break Inversion Of Control.
displayArray = new gamejs.SurfaceArray([100, 100]);

Rename Event in Key

I think the name is event is a bit tricky, when I personally think off application event more than system event.
Also in pygame the class is named Key.

loading of assets after ready()

currently only one set of assets can be preloaded before ready() is executed. for large games it would be useful to be able to load additional resources after the game is already initialized (e.g. for loading the next map assets).

API RFC

calling preload() after initialization triggers another async preloader. Once all assets were loaded, an event PRELOAD_SUCCESS or PRELOAD_ERROR is triggered.

the preloadId returned by preload() and in the resulting event is there, in case the game triggers multiple preload()s and needs to differantiate which one was finished:

// in game code:
var preloadId = gamejs.preload(['./images/foo.png']);

// in event handler:
if (event.type === gamejs.event.PRELOAD_SUCCESS) {
       gamejs.log('Loaded assets ', event.preloadId);
}

RenderUpdates sprite.Group subclass

RenderUpdates

A sprite group that's more efficient at updating. This group supports drawing to the screen, but its draw method also returns a list of the Rects updated by the draw (and any clears in between the last draw and the current one). You can use gamejs.display.update(group.draw(screen)) to minimize the updated part of the screen. This can usually make things much faster.

http://www.nongnu.org/pygsear/doc/api_html/private/pygame.sprite.RenderUpdates-class.html

better skeleton

current skeleton is crap. it references ../gamejs.min.js, has too much css/html

make something decent.

implement last arg to Surface.blit(src, dst, area, specialFlags)

we won't be able to support exactly what pygame has BLEND_ADD, BLEND_SUB, BLEND_MULT, BLEND_MIN, BLEND_MAX new in 1.8.1: BLEND_RGBA_ADD, BLEND_RGBA_SUB, BLEND_RGBA_MULT, BLEND_RGBA_MIN, BLEND_RGBA_MAX BLEND_RGB_ADD, BLEND_RGB_SUB, BLEND_RGB_MULT, BLEND_RGB_MIN, BLEND_RGB_MAX

but canvas API specifies its own list of blending operations: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html?style=highlight#dom-context-2d-globalcompositeoperation

the docs should take extra care to explain what they do!

1px wide line is actually drawn as 2px wide

this is due to this (scroll a bit down): http://diveintohtml5.org/canvas.html#paths

If you draw a one-unit-wide line between whole-number coordinates, it will overlap opposite sides of the pixel square, and the resulting line will be drawn two pixels wide. To draw a line that is only one pixel wide, you need to shift the coordinates by 0.5 perpendicular to the line's direction.

gamejs could internally fix all pixel coordinates to +0.5 (processingjs does that) but i don't like it :|

move module to class

I strongly believe that gamejs overuse module and should use more class instead.
I would also add static class for object that have static method instead of allocating it to exports.
actual code:

// ugly class requiring
Display = require('gamejs/display').Display
// and a style even more ugly
gamejs = require('gamejs')
mySurface = new gamejs.Surface()
// strange usage of contants encapsulated in gamejs or sometime from nowhere
gamejs.Event.K_UP
exports.SOME_CONSTANTS
exports.someFunction()

my proposal:

Display = require('gamejs/display')
Surface = require('gamejs/surface')
Event.K_UP
module.someStaticFunction()
//  or
Class.someStaticFunction

Adding globals (in exports) encourage spaghetti programming even if gamejs itself doesn't abuse from its own globals.
I also find trivial using gamejs module from internal gamejs module/class (c.f. gamejs.Event.K_up, or gamejs.Surface). Note that for final user refering to gamejs module to get gamejs component is not a bad practice.

I'm actually refactoring gamecs applying those suggestion.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.