• Stars
    star
    414
  • Rank 104,550 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 11 years ago
  • Updated almost 9 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A micro framework for JavaScript games

Coquette

A micro framework for JavaScript games.

Handles collision detection, the game update loop, canvas rendering, and keyboard and mouse input.

http://coquette.maryrosecook.com

Get the code

Example

A game where you, the valiant player, must find a person of indeterminate gender in distress so you can take them away from all this. The code below appears in /demos/simple/. Open /demos/simple/index.html to play.

The HTML below defines a canvas element and loads in Coquette and the game code.

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="../../coquette.js"></script>
    <script type="text/javascript" src="game.js"></script>
  </head>
  <body><canvas id="canvas"></canvas></body>
</html>

The game code:

var Game = function() {
  this.c = new Coquette(this, "canvas", 500, 150, "#000");

  // paramour
  this.c.entities.create(Person, { center: { x:250, y:40 }, color:"#099" });

  // player
  this.c.entities.create(Person, { center: { x:256, y:110 }, color:"#f07",
    update: function() {
      if (this.c.inputter.isDown(this.c.inputter.UP_ARROW)) {
        this.center.y -= 0.4;
      }
    },

    collision: function(other) {
      other.center.y = this.center.y; // follow the player
    }
  });
};

var Person = function(game, settings) {
  this.c = game.c;
  for (var i in settings) {
    this[i] = settings[i];
  }

  this.size = { x:9, y:9 };
  this.draw = function(ctx) {
    ctx.fillStyle = settings.color;
    ctx.fillRect(this.center.x - this.size.x / 2,
                 this.center.y - this.size.y / 2,
                 this.size.x,
                 this.size.y);
  };
};

window.addEventListener('load', function() {
  new Game();
});

Demos

Five demos are included in this repository:

  • /demos/spinning-shapes - an example of collisions between rotated entities.
  • /demos/racecar - a 2D racing game.
  • /demos/box2d-physics - a game that uses the Box2D physics engine.
  • /demos/leftrightspace - a complete game.
  • /demos/simple - the example at the top of this readme.

Reference

Instantiate Coquette

Pass in:

  • Your main game object.
  • The ID of the canvas element, e.g. "canvas".
  • The desired width of the canvas element.
  • The desired height of the canvas element.
  • The background colour of your game, e.g. "#000".
var YourGame = function() {
  this.c = new Coquette(this, "canvas", 150, 150, "#000");
};

Modules

When you instantiate Coquette, you get an object that has some modules. You can use these modules in your game.

Entities

Keeps track of all the entities in the game: the player, enemies, obstacles.

Define an entity

Most entities will have these attributes:

  • center: The center of the entity, e.g. { x: 10, y: 20 }
  • size: The size of the entity, e.g. { x: 50, y: 30 }
  • angle: The orientation of the entity in degrees, e.g. 30

And these methods:

  • update(timeSinceLastTick): Called every tick. You should change the state of the entity in this method.
  • draw(canvasCtx): Called every tick. You should draw the entity upright in this method. The drawing will automatically get rotated to the orientation indicated by angle.

For example:

var Block = function(game, settings) {
  this.game = game;
  this.center = settings.center;
  this.size = settings.size;
  this.angle = 30;
};

Block.prototype = {
  update: function(timeSinceLastTick) {
    this.center.x += 0.02 * timeSinceLastTick;
    this.center.y += 0.02 * timeSinceLastTick;
  },

  draw: function(canvasCtx) {
    ctx.fillStyle = "black";
    ctx.fillRect(this.center.x - this.size.x / 2,
                 this.center.y - this.size.y / 2,
                 this.size.x,
                 this.size.y);
  }
};

See the Collider section for instructions on enabling collision detection.

Create an entity

Call c.entities.create() with:

  • The constructor function of the entity you want to create, e.g. Block.
  • An optional settings object that will be passed into the constructor, e.g. { center: { x: 5, y: 10 }, size: { x: 10, y: 30 } }.

Returns the created entity.

var Block = function(game, settings) {
  this.game = game;
  this.center = settings.center;
  this.size = settings.size;
  this.angle = 0;
};

var myBlock = c.entities.create(Block, {
  center: { x: 5, y: 10 },
  size: { x: 10, y: 30 }
});
Destroy an entity

Call c.entities.destroy() with:

  • The entity you want to destroy, e.g. myBlock.
c.entities.destroy(myBlock);
Get all the entities in the game
var all = c.entities.all();
Get all the entities of a certain type
var invaders = c.entities.all(Invader);

Inputter

Handles keyboard and mouse input from the player.

Find out if a certain key or mouse button is down
var leftArrowDown = c.inputter.isDown(c.inputter.LEFT_ARROW);
var rightMouseDown = c.inputter.isDown(c.inputter.RIGHT_MOUSE);
Find out if a certain key or mouse button is pressed

This returns true for the tick following the key going down. In subsequent ticks, it returns false until the key is released and pressed down again.

var leftArrowPressed = c.inputter.isPressed(c.inputter.LEFT_ARROW);
var rightMousePressed = c.inputter.isPressed(c.inputter.RIGHT_MOUSE);
Run a function every time the mouse is moved
c.inputter.bindMouseMove(function(position) {
  console.log("The mouse is at", position.x, position.y);
});

position is relative to the game canvas. If the mouse pointer is in the top left corner, position will be { x: 0, y: 0 }.

Get the current mouse position
var position = c.inputter.getMousePosition();

position is relative to the game canvas. If the mouse pointer is in the top left corner, position will be { x: 0, y: 0 }.

Renderer

Holds the canvas drawing context. Calls draw() on the main game object and all the game entities.

Draw an entity

See the Define an Entity sub-section of the Entities section.

Get the canvas drawing context
  var ctx = c.renderer.getCtx();
  ctx.fillStyle = "#f00";
  ctx.fillRect(0, 0, 10, 10);
Set the order that entities are drawn

When you create your entities, set an integer zindex attribute on them. An entity with a higher zindex will get drawn on top of an entity with a lower zindex. The default zindex is 0.

  var BackgroundTile = function() {
    this.zindex = -1;
  };

  var Player = function() {
    this.zindex = 0;
  };

  c.entities.create(BackgroundTile, {});
  c.entities.create(Player, {}); // drawn on top
Move the view

You can use c.renderer.setViewCenter() to move the view around the world. For example, to make the view follow a specific object, you could call setViewCenter(specificObj.center) in the update() function of your game:

  var Game = function() {
    var c = new Coquette(this, "canvas", 500, 500, "#000");
    var specialObject = c.entities.create(SpecialObject, {});

    this.update = function() {
      c.renderer.setViewCenter(specialObject.center);
    };
  };

Collider

Reports when entities collide.

Entity setup

To make an entity support collisions, put these attributes on it:

  • center: The center of the entity, e.g. { x: 10, y: 20 }.
  • size: The size of the entity, e.g. { x: 50, y: 30 }.
  • boundingBox: The shape that best approximates the shape of the entity, either c.collider.RECTANGLE or c.collider.CIRCLE.
  • angle: The orientation of the entity in degrees, e.g. 30.

And, optionally, this method:

  • collision(other): Called when the entity collides with another entity. Takes other, the other entity involved in the collision.

For example:

var Player = function() {
  this.center = { x: 10, y: 20 };
  this.size = { x: 50, y: 50 };
  this.boundingBox = c.collider.CIRCLE;
  this.angle = 0;
};

Player.prototype = {
  collision: function(other) {
    console.log("Ow,", other, "hit me.");
  }
};

Run the tests

Install Node.js and npm: https://github.com/isaacs/npm

Install the node dependencies and run the tests with:

$ cd path/to/coquette
$ npm install --dev
$ npm test

More Repositories

1

gitlet

Git implemented in JavaScript
JavaScript
2,108
star
2

littlelisp

A small Lisp interpreter in JavaScript
JavaScript
597
star
3

islaclj

A programming language for young children
Clojure
320
star
4

annotated-code

A series of short, heavily annotated JavaScript programs
HTML
219
star
5

DEPRECATED-essays

[DEPRECATED] essay repo
201
star
6

machinejs

Make behaviour trees in JavaScript
JavaScript
157
star
7

isla

A programming language for young children
JavaScript
109
star
8

pistolslut

2D platform shooter in JavaScript.
JavaScript
103
star
9

androjs

Mix behaviours into objects
JavaScript
70
star
10

retro-games

Asteroids, Lunar Lander, Space Invaders and Snake in JavaScript
JavaScript
66
star
11

drum-machine

How to write a simple drum machine that runs in the browser
JavaScript
53
star
12

gamelivecode

Space Invaders live-coded in front of Hacker Schoolers
JavaScript
43
star
13

code-lauren

Game programming for beginners
JavaScript
31
star
14

emacs

My emacs config
Emacs Lisp
24
star
15

strange-loop

Content for Strange Loop 2014 workshop
JavaScript
23
star
16

codewithisla

Isla website. Includes interactive coding demos.
JavaScript
22
star
17

dijkstra

An implementation of Dijkstra in Clojure
Clojure
19
star
18

fibonacciheap

Clojure
15
star
19

timeline

Timeline
JavaScript
14
star
20

theperceptron

Astute music recommendations
Ruby
14
star
21

playmary

A touch-based synth in ClojureScript
JavaScript
12
star
22

glazz

Give your objects eyes
JavaScript
12
star
23

build-a-javascript-game-workshop

Build a JavaScript game from scratch
JavaScript
11
star
24

barecljs

The tiniest possible ClojureScript project
Clojure
11
star
25

scrawl

A sickeningly simple mp3 crawler. Built as I learn Clojure.
Clojure
10
star
26

minid3

A bare-bones implementation of D3
JavaScript
9
star
27

asteroids

A simple version of Asteroids that I might livecode at Front-Trends 2014
JavaScript
8
star
28

gameoflife

Conway's Game of Life, implemented in Ioke
Ioke
8
star
29

count

A tiny full stack web app
JavaScript
8
star
30

notes-exemplar

JavaScript
7
star
31

tinygame

A tiny game I wrote to illustrate how easy it is to write a game from scratch in JavaScript
JavaScript
7
star
32

bash

My bash file
Shell
5
star
33

substantiate

A library to help you prototype React apps faster
TypeScript
5
star
34

hacker-school-application-tasks

4
star
35

snowflake

Run code in particular circumstances
JavaScript
4
star
36

kisses

Helps people understand the magnitude of stuff, like a guided missile destroyer costs as much as three million fluffy kittens.
Ruby
4
star
37

streethoarding

Hoarding upon which you, and everyone else, can write, or, a ruthlessly simple example of a proper Node.js program.
JavaScript
4
star
38

logtoload

Takes an Apache log and turns it into a list of URLs that were requested and an XML file for the JMeter load tester.
Ruby
3
star
39

callbacks-workshop

HTML
3
star
40

maryandlauren.com

HTML
3
star
41

testing-from-the-ground-up

The code for my essay, Testing from the ground up
JavaScript
3
star
42

book-notes

3
star
43

leftrightspace

Entry for Ludum Dare 26
JavaScript
3
star
44

authentic

Code for Ableton job interview
Ruby
2
star
45

bank-kata

Ruby
2
star
46

this-workshop

HTML
2
star
47

learnc

Learn C the Hard Way
C
2
star
48

sicp

My solutions to the SICP exercises.
Scheme
2
star
49

todos

Ruby
2
star
50

filmranker

Find good films that are probably available for download.
Ruby
2
star
51

introductiontoalgorithms

Working through Introduction to Algorithms
Ruby
2
star
52

bitly-clone

JavaScript
2
star
53

eardefender

Tells you what you feel like listening to, based on your scrobble history.
Ruby
2
star
54

thinking-in-react

JavaScript
2
star
55

todo

Clojure
2
star
56

hacker-school-testing-seminar

Code for the Hacker School testing seminar
JavaScript
2
star
57

lollipopsandgumdrops

A music recommendation site
Ruby
2
star
58

films

JavaScript
2
star
59

ecosystem

A little world where ants roam
JavaScript
1
star
60

githubcontest2009

GitHub Contest 2009
Ruby
1
star
61

sortc

Some sort algorithms in C
C
1
star
62

pl101

JavaScript
1
star
63

mic

JavaScript
1
star
64

dasher

Objective-C
1
star
65

animation

Clojure
1
star
66

ttt

JavaScript
1
star
67

recursion

Python
1
star
68

closures-and-process-workshop

1
star
69

linecirclecollisions

Animation of circles bouncing off lines
JavaScript
1
star
70

the-more-you-have-the-worse-it-is

JavaScript
1
star
71

handy

A place to put the handy scripts I write.
Ruby
1
star
72

themarymanual

A practical and impractical guide
Ruby
1
star
73

playmarymixtape

Your life in songs
Ruby
1
star
74

recorder

Store data by calling a url
Ruby
1
star
75

switchoffthelightbeforeyouleave

A lightswitch on the internet.
JavaScript
1
star
76

viable-domains

JavaScript
1
star
77

parlour

Private discussion amongst friends
Ruby
1
star
78

ontherails

A starter for my Rails apps.
Ruby
1
star
79

clement

JavaScript
1
star
80

airtable-game-runner

JavaScript
1
star