2.4.2 • Published 6 years ago

timer-engine v2.4.2

Weekly downloads
21
License
MIT
Repository
github
Last release
6 years ago

TIMER-ENGINE

CircleCI Status Codecov npm npm npm

Timer make loop with "update" and "draw" states function

Live example

Install

npm i timer-engine --save
or
yarn add timer-engine


Importing

import Timer from "timer-engine";

const timer = Timer();
timer.update = frequenceValue => {
    /*make something*/
};
timer.draw = cumultateValue => {
    /*make something*/
};
timer.start();

Sample SNAKE GAME

simple game to test Timer-engine plugin

index.html file

<canvas width="320" height="240" style="border:red 1px solid"></canvas>

script.js file

var canvas = document.body.children[0];
var context = canvas.getContext("2d");
context.scale(10, 10);
snake = [[16, 1]];

action = {
    ArrowUp: [0, -1],
    ArrowDown: [0, 1],
    ArrowLeft: [-1, 0],
    ArrowRight: [1, 0]
};

direction = [0, 1];
apple = [5, 5];

// intance and choose frequence
timer = Timer.default(1 / 5);

// use keyboard to move snake
window.onkeydown = ({ key }) => {
    direction = action[key] || direction;
};

// set Update function
timer.update = () => {
    head = snake[0];
    snake.unshift([head[0] + direction[0], head[1] + direction[1]]);

    if (apple[0] === head[0] && apple[1] === head[1]) {
        apple = [(Math.random() * 32) | 0, (Math.random() * 24) | 0];
    } else {
        snake.pop();
    }
};

// set Draw function
timer.draw = () => {
    context.clearRect(0, 0, 100, 100);
    context.fillStyle = "red";
    context.fillRect(apple[0], apple[1], 1, 1);

    context.fillStyle = "black";
    snake.forEach(([x, y]) => {
        context.fillRect(x, y, 1, 1);
    });
};

//first draw
timer.draw();

//click to start game
document.addEventListener("click", () => {
    timer.start();
});

Options


Methods

.start()

TypeDescription
functionStart the loop, if it wasn't already start

.stop()

TypeDescription
functionStop the loop, if it wasn't already stop

.setFrequence(num)

TypeDescription
functionset new frequence loop
argumenttypeDescription
numnumbernew value of frequence
2.4.2

6 years ago

2.4.1

6 years ago

2.4.0

6 years ago

2.3.0

6 years ago

2.2.1

6 years ago

2.2.0

6 years ago

2.2.2

6 years ago

2.1.0

6 years ago

2.0.2

6 years ago

1.0.1

6 years ago

2.0.1

6 years ago

2.0.0

6 years ago

1.2.0-beta.0

6 years ago

1.2.0

6 years ago

1.1.0

6 years ago

1.0.0

6 years ago