A warioware-like browser game; Finals project
1import {GameState, loopStates} from "../gameState.js";
2
3export enum controls {
4 "mouse" = 0,
5 "keyboard" = 1,
6 "keyboard_mouse" = 2
7}
8
9export interface microGameInterface {
10 control?: controls
11 rendered: boolean
12 finished: { state: boolean, success: boolean },
13 abortController: AbortController
14 gameState: GameState
15
16 htmlContent?: string
17 name: string
18
19 preLoop(): void
20 loop(): void
21 postLoop(): void
22
23 finish(win: boolean): void
24
25 render(): void
26 unRender(): void
27 loadEvents(): void
28}
29
30export class MicroGameBase implements microGameInterface {
31 control?: controls;
32 rendered: boolean;
33 finished: { state: boolean, success: boolean };
34 abortController: AbortController;
35
36 gameState: GameState
37
38 htmlContent?: string;
39 name: string;
40
41 constructor(
42 name: string,
43 control: controls,
44 gameState: GameState
45 ) {
46 this.name = name;
47 this.control = control;
48
49 this.gameState = gameState;
50 this.rendered = false;
51 this.finished = { state: false, success: false };
52 this.abortController = new AbortController();
53 }
54
55 // Stuff that happens before the game-loop happens
56 preLoop() {
57 this.render();
58 }
59
60 // The game loop itself
61 loop(): void { }
62
63 // this should act as function that completes the loop and instantly turns to the switch loop
64 postLoop(): void {
65 this.unRender();
66
67 this.finished = {
68 state: false,
69 success: false,
70 };
71 }
72
73 finish(win: boolean): void {
74 if (!this.finished.state) {
75 this.finished = {
76 state: true,
77 success: win
78 }
79
80 // generalized fluff that should happen ones the game finishes
81 if (this.gameState.clock.time >= 15) this.gameState.clock.time = 15;
82 }
83 }
84
85
86 render(): void {
87 if (this.rendered) return;
88
89 const el: HTMLElement | null = document.querySelector('main .content');
90 if (!el) throw new Error("Main content block did not load correctly !!");
91
92 if (!this.htmlContent) throw new Error("No content to render was given");
93
94 const ell: HTMLDivElement = document.createElement("div");
95 ell.className = "game__" + this.name;
96 ell.innerHTML = this.htmlContent;
97
98
99 el.appendChild(ell);
100 this.loadEvents();
101 this.rendered = true;
102 }
103
104 unRender() {
105 if (!this.rendered) return;
106
107 const content: HTMLElement | null = document.querySelector('main .content');
108 if (!content) throw new Error("Could not find content area");
109
110 content.innerHTML = ''; // game needs to reload abort and eventListeners; need to remove content completely
111 this.abortController.abort();
112
113 this.rendered = false;
114 }
115
116 loadEvents() {
117 if (this.gameState.loopState != loopStates.IN_GAME) return;
118
119 this.abortController = new AbortController();
120 }
121
122}
123