advent22/ui/src/lib/door.ts

53 lines
1.1 KiB
TypeScript
Raw Normal View History

2023-09-12 16:55:34 +00:00
import { DoorSaved } from "./api";
2023-09-07 02:08:56 +00:00
import { Rectangle } from "./rectangle";
2023-09-07 03:30:21 +00:00
import { Vector2D } from "./vector2d";
2023-02-02 18:06:55 +00:00
export class Door {
2023-09-12 14:55:08 +00:00
public static readonly MIN_DAY = 1;
private _day = Door.MIN_DAY;
2023-02-02 18:06:55 +00:00
public position: Rectangle;
2023-09-07 03:29:53 +00:00
constructor(position: Rectangle);
constructor(position: Rectangle, day: number);
2023-09-12 14:55:08 +00:00
constructor(position: Rectangle, day = Door.MIN_DAY) {
2023-02-02 18:06:55 +00:00
this.day = day;
this.position = position;
}
public get day(): number {
2023-09-07 01:17:14 +00:00
return this._day;
2023-02-02 18:06:55 +00:00
}
public set day(day: unknown) {
// integer coercion
const result = Number(day);
if (isNaN(result)) {
2023-09-12 14:55:08 +00:00
this._day = Door.MIN_DAY;
} else {
2023-09-12 14:55:08 +00:00
this._day = Math.max(Math.floor(result), Door.MIN_DAY);
}
2023-02-02 18:06:55 +00:00
}
2023-09-07 03:30:21 +00:00
2023-09-07 19:34:11 +00:00
public static load(serialized: DoorSaved): Door {
2023-09-07 03:30:21 +00:00
return new Door(
new Rectangle(
new Vector2D(serialized.x1, serialized.y1),
new Vector2D(serialized.x2, serialized.y2),
),
serialized.day,
);
}
2023-09-07 19:34:11 +00:00
public save(): DoorSaved {
2023-09-07 03:30:21 +00:00
return {
day: this.day,
x1: this.position.origin.x,
y1: this.position.origin.y,
x2: this.position.corner.x,
y2: this.position.corner.y,
};
}
2023-09-07 01:17:14 +00:00
}