humus-old/common/world-time.synchronized.js
2019-09-29 13:20:08 -05:00

90 lines
1.8 KiB
JavaScript

import {compose} from '@avocado/core';
import {SynchronizedMixin} from '@avocado/net';
import {Ticker} from '@avocado/timing';
import {WorldTimePacket} from './world-time.packet';
const MAGIC_TO_FIT_HOUR_INTO_USHORT = 2730;
const decorate = compose(
SynchronizedMixin,
);
export class WorldTime extends decorate(class {}) {
constructor(json) {
super();
this._hour = 0;
this._isUpdateReady = true;
this._lastHour = 0;
this.ticker = new Ticker(0.25);
this.ticker.on('tick', () => {
this._isUpdateReady = true;
});
if ('undefined' !== typeof json) {
this.fromJSON(json);
}
}
acceptPacket(packet) {
if (packet instanceof WorldTimePacket) {
this.fromNetwork(packet.data);
}
}
cleanPackets() {
super.cleanPackets();
this._isUpdateReady = false;
}
static format(time) {
const rawHour = (time + 12) % 12;
const hour = Math.floor(0 === Math.floor(rawHour) ? 12 : rawHour);
const minutes = String(Math.floor((rawHour - Math.floor(rawHour)) * 60)).padStart(2, '0');
if (time >= 12) {
return `${hour}:${minutes} pm`;
}
else {
return `${hour}:${minutes} am`;
}
}
fromJSON(json) {
if (json.hour) {
this._hour = json.hour / MAGIC_TO_FIT_HOUR_INTO_USHORT;
}
}
get hour() {
return this._hour;
}
set hour(hour) {
this._hour = hour;
}
packets(informed) {
if (!this._isUpdateReady) {
return;
}
return new WorldTimePacket(this.toNetwork(informed));
}
secondsPerHour() {
return 60;
}
tick(elapsed) {
this._hour += (elapsed / this.secondsPerHour());
this._hour = this._hour % 24;
this.ticker.tick(elapsed);
}
toJSON() {
return {
hour: (this._hour * MAGIC_TO_FIT_HOUR_INTO_USHORT) >> 0,
};
}
}