2.4.2 • Published 6 years ago
timer-engine v2.4.2
TIMER-ENGINE
Timer make loop with "update" and "draw" states function
Live example
Install
npm i timer-engine --save
oryarn 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()
Type | Description |
---|---|
function | Start the loop, if it wasn't already start |
.stop()
Type | Description |
---|---|
function | Stop the loop, if it wasn't already stop |
.setFrequence(num)
Type | Description |
---|---|
function | set new frequence loop |
argument | type | Description |
---|---|---|
num | number | new value of frequence |