Fantasy 8Bit system (F8), is a fantasy 8bit console and a set of libraries for creating fantasy 8bit consoles.

65 lines
1.3KB

  1. class Clock{
  2. constructor(layers){
  3. layers = (typeof(layers === 'number') && layers > 0) ?
  4. Math.floor(layers) :
  5. 1;
  6. this.__ticktime = 1000;
  7. this.__dt = -1;
  8. this.__out = [];
  9. this.__cl = 0;
  10. for (let i=0; i < layers; i++)
  11. this.__out.push([]);
  12. }
  13. get hz(){return Math.floor(1000 / this.__ticktime);}
  14. set hz(hz){
  15. if(hz >= 1){
  16. this.__ticktime = 1000 / hz;
  17. this.__dt = -1;
  18. }
  19. }
  20. get layers(){return this.__out.length;}
  21. clk(fn, layer){
  22. layer = (typeof(layer === 'number') && layer >= 0) ?
  23. Math.floor(layer) :
  24. 0;
  25. if (layer < 0 || layer >= this.__out.length)
  26. throw new RangeError("Layer out of bounds.");
  27. if (typeof(fn) === 'function')
  28. this.__out[layer].push(fn);
  29. return this;
  30. }
  31. // NOTE: dt in milliseconds.
  32. tick(dt){
  33. let extraTick = false;
  34. if (this.__dt < 0){
  35. this.__dt = 0;
  36. extraTick = true;
  37. }
  38. let proc = (ddt) => {
  39. this.__out[this.__cl].forEach((fn)=>{fn();});
  40. if (ddt)
  41. this.__dt -= this.__ticktime;
  42. if (this.__out.length > 1)
  43. this.__cl = (this.__cl === this.__out.length - 1) ? 0 : this.__cl + 1;
  44. };
  45. this.__dt += dt;
  46. while(this.__dt > this.__ticktime)
  47. proc(true);
  48. if (extraTick)
  49. proc(false);
  50. return this;
  51. }
  52. }
  53. module.exports = Clock;