brick-engine-js 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (225) hide show
  1. package/dist/docs/GAME_DEVELOPER_GUIDE.html +1 -1
  2. package/dist/docs/brick-engine-guide.html +1 -1
  3. package/dist/docs/getting-started.html +1 -1
  4. package/dist/docs/jsdoc_standard.html +1 -1
  5. package/dist/docs/publishing.html +1 -1
  6. package/dist/docs/reference/interfaces/modules/Session.html +1 -1
  7. package/dist/docs/reference/modules/GameMenu.html +1 -1
  8. package/dist/docs/reference/modules/GameSession.html +1 -1
  9. package/dist/docs/reference/modules/InitialStateSnapshot.html +1 -1
  10. package/dist/docs/reference/modules/SessionModal.html +1 -1
  11. package/dist/docs/testing_best_practices.html +1 -1
  12. package/package.json +7 -1
  13. package/.env.local.example +0 -2
  14. package/.github/workflows/publish.yml +0 -73
  15. package/.prettierignore +0 -2
  16. package/.prettierrc.json +0 -8
  17. package/eslint.config.mjs +0 -29
  18. package/public/CNAME +0 -1
  19. package/public/docs/GAME_DEVELOPER_GUIDE.html +0 -727
  20. package/public/docs/brick-engine-guide.html +0 -610
  21. package/public/docs/diagrams/lifecycle.mmd +0 -19
  22. package/public/docs/documentation_style_guide.html +0 -994
  23. package/public/docs/getting-started.html +0 -648
  24. package/public/docs/images/lifecycle.svg +0 -1
  25. package/public/docs/index.html +0 -593
  26. package/public/docs/jsdoc_standard.html +0 -656
  27. package/public/docs/publishing.html +0 -573
  28. package/public/docs/reference/enums/Color.html +0 -533
  29. package/public/docs/reference/enums/ControlEventType.html +0 -505
  30. package/public/docs/reference/enums/ControlKey.html +0 -529
  31. package/public/docs/reference/enums/FontAlignment.html +0 -545
  32. package/public/docs/reference/enums/FontSize.html +0 -517
  33. package/public/docs/reference/enums/Sound.html +0 -558
  34. package/public/docs/reference/enums/StateProperty.html +0 -525
  35. package/public/docs/reference/helpers/CellHelper.html +0 -520
  36. package/public/docs/reference/helpers/ControlInputHandlerHelper.html +0 -569
  37. package/public/docs/reference/helpers/CoordinateHelper.html +0 -703
  38. package/public/docs/reference/helpers/RelativeValuesHelper.html +0 -560
  39. package/public/docs/reference/interfaces/Debuggable.html +0 -501
  40. package/public/docs/reference/interfaces/GameModules.html +0 -544
  41. package/public/docs/reference/interfaces/Initializable.html +0 -495
  42. package/public/docs/reference/interfaces/RendererInitializable.html +0 -517
  43. package/public/docs/reference/interfaces/StateSyncable.html +0 -542
  44. package/public/docs/reference/interfaces/modules/Control.html +0 -648
  45. package/public/docs/reference/interfaces/modules/Grid.html +0 -1256
  46. package/public/docs/reference/interfaces/modules/Renderer.html +0 -522
  47. package/public/docs/reference/interfaces/modules/RendererComposite.html +0 -577
  48. package/public/docs/reference/interfaces/modules/Score.html +0 -669
  49. package/public/docs/reference/interfaces/modules/Session.html +0 -585
  50. package/public/docs/reference/interfaces/modules/State.html +0 -897
  51. package/public/docs/reference/interfaces/modules/Text.html +0 -668
  52. package/public/docs/reference/interfaces/modules/Time.html +0 -684
  53. package/public/docs/reference/modules/Debugger.html +0 -579
  54. package/public/docs/reference/modules/DisplayRenderer.html +0 -557
  55. package/public/docs/reference/modules/Game.html +0 -909
  56. package/public/docs/reference/modules/GameControl.html +0 -716
  57. package/public/docs/reference/modules/GameGrid.html +0 -1910
  58. package/public/docs/reference/modules/GameHudGrid.html +0 -508
  59. package/public/docs/reference/modules/GameMenu.html +0 -538
  60. package/public/docs/reference/modules/GameRenderer.html +0 -589
  61. package/public/docs/reference/modules/GameScore.html +0 -664
  62. package/public/docs/reference/modules/GameSession.html +0 -533
  63. package/public/docs/reference/modules/GameSound.html +0 -636
  64. package/public/docs/reference/modules/GameState.html +0 -922
  65. package/public/docs/reference/modules/GameText.html +0 -701
  66. package/public/docs/reference/modules/GameTime.html +0 -696
  67. package/public/docs/reference/modules/HudRenderer.html +0 -568
  68. package/public/docs/reference/modules/InitialStateSnapshot.html +0 -557
  69. package/public/docs/reference/modules/SessionModal.html +0 -520
  70. package/public/docs/reference/types/Axis.html +0 -505
  71. package/public/docs/reference/types/Cell.html +0 -514
  72. package/public/docs/reference/types/ControlCallback.html +0 -488
  73. package/public/docs/reference/types/Coordinate.html +0 -510
  74. package/public/docs/reference/types/GameEntry.html +0 -514
  75. package/public/docs/reference/types/GameEvent.html +0 -514
  76. package/public/docs/reference/types/Piece.html +0 -506
  77. package/public/docs/reference/types/RendererMetrics.html +0 -514
  78. package/public/docs/reference/types/Vector.html +0 -509
  79. package/public/docs/testing_best_practices.html +0 -770
  80. package/public/favicon.ico +0 -0
  81. package/public/fonts/digital-7.monoitalic.ttf +0 -0
  82. package/public/images/cell.svg +0 -32
  83. package/public/images/close.png +0 -0
  84. package/public/images/games.png +0 -0
  85. package/public/images/github.png +0 -0
  86. package/public/images/letter-a.png +0 -0
  87. package/public/images/letter-d.png +0 -0
  88. package/public/images/letter-j.png +0 -0
  89. package/public/images/letter-s.png +0 -0
  90. package/public/images/letter-w.png +0 -0
  91. package/public/images/meta-image.png +0 -0
  92. package/public/images/number-1.png +0 -0
  93. package/public/images/number-2.png +0 -0
  94. package/public/images/number-3.png +0 -0
  95. package/public/images/number-4.png +0 -0
  96. package/public/images/number-5.png +0 -0
  97. package/public/images/number-6.png +0 -0
  98. package/public/images/splash.gif +0 -0
  99. package/public/index.html +0 -15
  100. package/public/sounds/sound_00.wav +0 -0
  101. package/public/sounds/sound_01.wav +0 -0
  102. package/public/sounds/sound_02.wav +0 -0
  103. package/public/sounds/sound_03.wav +0 -0
  104. package/public/sounds/sound_04.wav +0 -0
  105. package/public/sounds/sound_05.wav +0 -0
  106. package/public/sounds/sound_06.wav +0 -0
  107. package/public/sounds/sound_07.wav +0 -0
  108. package/public/sounds/sound_08.wav +0 -0
  109. package/public/sounds/sound_09.wav +0 -0
  110. package/public/sounds/sound_10.wav +0 -0
  111. package/public/sounds/sound_11.wav +0 -0
  112. package/public/sounds/sound_12.wav +0 -0
  113. package/public/sounds/sound_13.wav +0 -0
  114. package/public/sounds/sound_14.wav +0 -0
  115. package/public/sounds/sound_15.wav +0 -0
  116. package/public/style/body.css +0 -86
  117. package/public/style/buttons.css +0 -233
  118. package/public/style/debugger.css +0 -117
  119. package/public/style/sessionModal.css +0 -155
  120. package/public/style/sourceCodeAndCommands.css +0 -74
  121. package/public/style/splash.css +0 -13
  122. package/public/style/theme.css +0 -137
  123. package/scripts/generate-diagrams.sh +0 -20
  124. package/scripts/generate-docs.js +0 -111
  125. package/src/client-game.d.ts +0 -1
  126. package/src/config/configs.test.ts +0 -20
  127. package/src/config/configs.ts +0 -197
  128. package/src/config/env.test.ts +0 -59
  129. package/src/config/env.ts +0 -7
  130. package/src/config/styles.ts +0 -5
  131. package/src/core/Game.test.ts +0 -167
  132. package/src/core/Game.ts +0 -307
  133. package/src/core/InitialStateSnapshot.test.ts +0 -51
  134. package/src/core/InitialStateSnapshot.ts +0 -46
  135. package/src/core/helpers/CellHelper.test.ts +0 -33
  136. package/src/core/helpers/CellHelper.ts +0 -21
  137. package/src/core/helpers/ControlInputHandlerHelper.test.ts +0 -116
  138. package/src/core/helpers/ControlInputHandlerHelper.ts +0 -68
  139. package/src/core/helpers/CoordinateHelper.test.ts +0 -113
  140. package/src/core/helpers/CoordinateHelper.ts +0 -82
  141. package/src/core/helpers/InterfaceIdentifierHelper.test.ts +0 -122
  142. package/src/core/helpers/InterfaceIdentifierHelper.ts +0 -43
  143. package/src/core/helpers/RelativeValuesHelper.test.ts +0 -47
  144. package/src/core/helpers/RelativeValuesHelper.ts +0 -29
  145. package/src/core/module/control/GameControl.test.ts +0 -82
  146. package/src/core/module/control/GameControl.ts +0 -142
  147. package/src/core/module/control/GameControlKeyBinding.test.ts +0 -59
  148. package/src/core/module/control/GameControlKeyBinding.ts +0 -92
  149. package/src/core/module/grid/GameGrid.test.ts +0 -83
  150. package/src/core/module/grid/GameGrid.ts +0 -610
  151. package/src/core/module/grid/GameHudGrid.test.ts +0 -22
  152. package/src/core/module/grid/GameHudGrid.ts +0 -40
  153. package/src/core/module/grid/engines/GridAnalysisEngine.test.ts +0 -157
  154. package/src/core/module/grid/engines/GridAnalysisEngine.ts +0 -124
  155. package/src/core/module/grid/engines/GridLineEngine.test.ts +0 -132
  156. package/src/core/module/grid/engines/GridLineEngine.ts +0 -165
  157. package/src/core/module/grid/engines/GridMovementEngine.test.ts +0 -125
  158. package/src/core/module/grid/engines/GridMovementEngine.ts +0 -113
  159. package/src/core/module/grid/engines/GridRegionEngine.test.ts +0 -136
  160. package/src/core/module/grid/engines/GridRegionEngine.ts +0 -52
  161. package/src/core/module/grid/engines/GridTransformEngine.test.ts +0 -98
  162. package/src/core/module/grid/engines/GridTransformEngine.ts +0 -70
  163. package/src/core/module/renderer/DisplayRenderer.test.ts +0 -86
  164. package/src/core/module/renderer/DisplayRenderer.ts +0 -152
  165. package/src/core/module/renderer/GameRenderer.test.ts +0 -103
  166. package/src/core/module/renderer/GameRenderer.ts +0 -144
  167. package/src/core/module/renderer/HudRenderer.test.ts +0 -108
  168. package/src/core/module/renderer/HudRenderer.ts +0 -203
  169. package/src/core/module/score/GameScore.test.ts +0 -71
  170. package/src/core/module/score/GameScore.ts +0 -188
  171. package/src/core/module/session/GameSession.test.ts +0 -176
  172. package/src/core/module/session/GameSession.ts +0 -103
  173. package/src/core/module/sound/GameSound.test.ts +0 -117
  174. package/src/core/module/sound/GameSound.ts +0 -229
  175. package/src/core/module/state/GameState.test.ts +0 -101
  176. package/src/core/module/state/GameState.ts +0 -339
  177. package/src/core/module/text/GameText.test.ts +0 -87
  178. package/src/core/module/text/GameText.ts +0 -150
  179. package/src/core/module/time/GameTime.test.ts +0 -86
  180. package/src/core/module/time/GameTime.ts +0 -144
  181. package/src/core/types/Interfaces.ts +0 -59
  182. package/src/core/types/Types.ts +0 -124
  183. package/src/core/types/enums.ts +0 -113
  184. package/src/core/types/modules.ts +0 -841
  185. package/src/index.test.ts +0 -15
  186. package/src/index.ts +0 -9
  187. package/src/main.test.ts +0 -137
  188. package/src/main.ts +0 -77
  189. package/src/menu/GameMenu.test.ts +0 -157
  190. package/src/menu/GameMenu.ts +0 -124
  191. package/src/menu/GameMenuSingleton.test.ts +0 -26
  192. package/src/menu/GameMenuSingleton.ts +0 -13
  193. package/src/menu/GameRepository.test.ts +0 -46
  194. package/src/menu/GameRepository.ts +0 -47
  195. package/src/menu/manager/GameManager.test.ts +0 -68
  196. package/src/menu/manager/GameManager.ts +0 -50
  197. package/src/types/global.d.ts +0 -8
  198. package/src/types/interfaces.ts +0 -5
  199. package/src/view/Debugger.test.ts +0 -152
  200. package/src/view/Debugger.ts +0 -124
  201. package/src/view/GameView.test.ts +0 -95
  202. package/src/view/GameView.ts +0 -244
  203. package/src/view/SessionModal.test.ts +0 -141
  204. package/src/view/SessionModal.ts +0 -73
  205. package/src/view/components/layout/ButtonLayout.test.ts +0 -28
  206. package/src/view/components/layout/ButtonLayout.ts +0 -63
  207. package/src/view/components/layout/ContainerLayout.test.ts +0 -48
  208. package/src/view/components/layout/ContainerLayout.ts +0 -50
  209. package/src/view/components/layout/FrameLayout.test.ts +0 -24
  210. package/src/view/components/layout/FrameLayout.ts +0 -25
  211. package/src/view/components/ui/BigButton.test.ts +0 -28
  212. package/src/view/components/ui/BigButton.ts +0 -31
  213. package/src/view/components/ui/Button.test.ts +0 -30
  214. package/src/view/components/ui/Button.ts +0 -30
  215. package/src/view/components/ui/Canvas.test.ts +0 -32
  216. package/src/view/components/ui/Canvas.ts +0 -34
  217. package/src/view/components/ui/SmallButton.test.ts +0 -48
  218. package/src/view/components/ui/SmallButton.ts +0 -32
  219. package/src/view/theme/applyColors.test.ts +0 -47
  220. package/src/view/theme/applyColors.ts +0 -38
  221. package/src/view/theme/dimensions.test.ts +0 -34
  222. package/src/view/theme/dimensions.ts +0 -53
  223. package/tsconfig.json +0 -16
  224. package/vitest.config.ts +0 -14
  225. package/webpack.config.js +0 -133
package/src/core/Game.ts DELETED
@@ -1,307 +0,0 @@
1
- import p5 from 'p5';
2
- import type GameView from '../view/GameView';
3
- import GameControl from './module/control/GameControl';
4
- import GameGrid from './module/grid/GameGrid';
5
- import GameRenderer from './module/renderer/GameRenderer';
6
- import GameState from './module/state/GameState';
7
- import GameText from './module/text/GameText';
8
- import GameTime from './module/time/GameTime';
9
- import GameSound from './module/sound/GameSound';
10
- import GameScore from './module/score/GameScore';
11
-
12
- import { Initializable } from './types/Interfaces';
13
- import { ControlEventType, ControlKey, GameModules, StateProperty } from './types/Types';
14
- import GameHudGrid from './module/grid/GameHudGrid';
15
- import InterfaceIdentifierHelper from './helpers/InterfaceIdentifierHelper';
16
- import InitialStateSnapshot from './InitialStateSnapshot';
17
- import GameSession from './module/session/GameSession';
18
-
19
- /**
20
- * Base abstract class for the game.
21
- *
22
- * It manages the game loop, initialization of core modules, and integration with p5.js.
23
- * All game logic should be implemented in subclasses by overriding `processTick` and `processFrame`.
24
- */
25
- export default abstract class Game implements Initializable {
26
- protected _p: p5;
27
- protected _view: GameView;
28
-
29
- private _modules: GameModules = undefined as unknown as GameModules;
30
-
31
- private _initialStateSnapshot = new InitialStateSnapshot();
32
-
33
- private _gameId: string = 'unknown';
34
-
35
- private _switchHandler: (newGame: Game) => void = undefined as unknown as (newGame: Game) => void;
36
-
37
- /**
38
- * Gets the game ID
39
- */
40
- get gameId(): string {
41
- return this._gameId;
42
- }
43
-
44
- /**
45
- * Sets the game ID
46
- */
47
- set gameId(id: string) {
48
- this._gameId = id;
49
- }
50
-
51
- /**
52
- * Registers the callback to be used when a game requests to switch to another game.
53
- * This is typically called by the engine's main loop (index.ts).
54
- * @param handler The callback function.
55
- */
56
- setSwitchHandler(handler: (newGame: Game) => void) {
57
- this._switchHandler = handler;
58
- }
59
-
60
- /**
61
- * Propagates the switch handler to the new game.
62
- * @param game Game instance that has the switch handler.
63
- */
64
- propagateSwitchHandler(game: Game) {
65
- this.setSwitchHandler(game._switchHandler);
66
- }
67
-
68
- /**
69
- * Creates an instance of the Game.
70
- *
71
- * @param {p5} p - The p5 instance.
72
- * @param {GameView} view - The view strategy associated with this game.
73
- */
74
- constructor(p: p5, view: GameView) {
75
- this._p = p;
76
- this._view = view;
77
- this._initialStateSnapshot.captureBaseProperties(this);
78
- }
79
-
80
- /**
81
- * Gets the game view.
82
- *
83
- * @returns {GameView} The game view instance.
84
- */
85
- get view(): GameView {
86
- return this._view;
87
- }
88
-
89
- /**
90
- * Switches execution to a new game instance.
91
- * Use this instead of global window methods.
92
- *
93
- * @param {Game} newGame - The new game instance to load.
94
- */
95
- switchGame(newGame: Game): void {
96
- this.destroy(); // Clean up current game
97
- if (this._switchHandler) {
98
- this._switchHandler(newGame);
99
- } else {
100
- console.error('Game switch handler not registered. Cannot switch game.');
101
- }
102
- }
103
-
104
- /**
105
- * Gets the game modules.
106
- *
107
- * @returns {GameModules} The collection of initialized game modules.
108
- */
109
- get modules(): GameModules {
110
- return this._modules;
111
- }
112
-
113
- /**
114
- * Sets up the game, initializing all modules and viewing components.
115
- * Called automatically by the engine key sequence.
116
- */
117
- setup() {
118
- this._view.build();
119
-
120
- this._modules = {
121
- renderer: new GameRenderer(this._p),
122
- grid: new GameGrid(),
123
- hudGrid: new GameHudGrid(),
124
- text: new GameText(this._p),
125
- state: new GameState(),
126
- control: new GameControl(),
127
- time: new GameTime(),
128
- sound: new GameSound(),
129
- score: new GameScore(),
130
- session: new GameSession(),
131
- };
132
-
133
- Object.values(this._modules).forEach(module => {
134
- if (InterfaceIdentifierHelper.isInitializable(module)) {
135
- module.setup();
136
- }
137
- });
138
-
139
- Object.values(this._modules).forEach(module => {
140
- if (InterfaceIdentifierHelper.isStateSyncable(module)) {
141
- module.syncState(this._modules.state);
142
- }
143
- });
144
-
145
- Object.values(this._modules).forEach(module => {
146
- if (InterfaceIdentifierHelper.isSerializable(module)) {
147
- this._modules.session.register(module);
148
- }
149
- });
150
-
151
- const { text, control, renderer, session } = this._modules;
152
-
153
- session.gameId = this.gameId;
154
- session.setShowModalFunction(this._view.showSessionModal.bind(this._view));
155
-
156
- control.setModules(this._modules);
157
-
158
- text.setRendererMetrics(renderer.rendererMetrics);
159
-
160
- this.setupGame();
161
- this._initialStateSnapshot.captureInitialState(this);
162
-
163
- this._subscribeSystemControls();
164
-
165
- this._view.bindControls(control);
166
- }
167
-
168
- /**
169
- * Main draw loop, called by p5.js.
170
- * Handles time updates, logic ticks, and rendering.
171
- */
172
- draw() {
173
- if (!this._modules) return;
174
-
175
- const { renderer, grid, time, state } = this._modules;
176
-
177
- renderer.render(grid.getGrid(), this._modules);
178
- if (state.isOn()) {
179
- if (!state.isStarted()) {
180
- this.drawTitleScreen();
181
- } else if (state.isPlaying()) {
182
- time.update(this._p.deltaTime);
183
- // Update time accumulator
184
-
185
- // Process Logic Tick
186
- if (time.shouldTick()) {
187
- this.update(this._p.deltaTime);
188
-
189
- this._modules.session.saveSession();
190
- }
191
-
192
- this.render();
193
- } else if (state.isPaused()) {
194
- this.render();
195
- }
196
-
197
- if (state.isGameOver()) {
198
- this.drawGameOverScreen();
199
- }
200
- }
201
- }
202
-
203
- /**
204
- * Destroys the game instance, cleaning up all event listeners and stopping the loop.
205
- * Call this before switching to another game or when the game is no longer needed.
206
- */
207
- destroy() {
208
- this._p.noLoop();
209
-
210
- if (this._modules) {
211
- this._modules.control.unbindControls();
212
- this._modules.sound.stopAll();
213
- }
214
- }
215
-
216
- get p() {
217
- return this._p;
218
- }
219
-
220
- /**
221
- * Abstract method for processing game logic.
222
- * Called every tick, but ONLY when the game is in the 'playing' state.
223
- *
224
- * @param {number} deltaTime - Time elapsed since last tick.
225
- */
226
- abstract update(deltaTime: number): void;
227
-
228
- /**
229
- * Abstract method for processing visual frames.
230
- * Called every frame (depending on frameInterval).
231
- */
232
- abstract render(): void;
233
-
234
- /**
235
- * Abstract method for setting up the game specific logic.
236
- * Called after the game modules are initialized.
237
- */
238
- abstract setupGame(): void;
239
-
240
- /**
241
- * Abstract method for drawing the Title Screen (Welcome).
242
- * Called when the game is ON but not yet STARTED.
243
- */
244
- abstract drawTitleScreen(): void;
245
-
246
- /**
247
- * Abstract method for drawing the Game Over Screen.
248
- * Called when the game is in GAME OVER state.
249
- */
250
- abstract drawGameOverScreen(): void;
251
-
252
- private _subscribeSystemControls(): void {
253
- const { control, state, grid } = this._modules;
254
-
255
- control.subscribe(ControlKey.POWER, ControlEventType.PRESSED, () => {
256
- if (state.isOn()) {
257
- state.turnOff();
258
- this.modules.sound.stopAll();
259
- } else {
260
- state.turnOn();
261
- }
262
- });
263
- control.subscribe(ControlKey.SOUND, ControlEventType.PRESSED, () => state.toggleMuted());
264
- control.subscribe(ControlKey.COLOR, ControlEventType.PRESSED, () => state.toggleColorEnabled());
265
-
266
- control.subscribe(ControlKey.RESET, ControlEventType.PRESSED, () => {
267
- grid.resetGrid();
268
- this.modules.score.resetScore();
269
- this.modules.score.resetLevel();
270
- this.modules.time.reset();
271
- this._modules.session.clearSession();
272
- state.resetGame();
273
- this._initialStateSnapshot.restoreInitialState(this);
274
- });
275
-
276
- control.subscribe(ControlKey.EXIT, ControlEventType.PRESSED, () => {
277
- this._modules.session.clearSession();
278
- });
279
-
280
- control.subscribe(ControlKey.START_PAUSE, ControlEventType.PRESSED, () => {
281
- if (!state.isStarted()) {
282
- state.startGame();
283
- } else if (state.isPlaying()) {
284
- state.pause();
285
- } else if (state.isPaused()) {
286
- state.resume();
287
- } else if (state.isGameOver()) {
288
- grid.resetGrid();
289
- this.modules.score.resetScore();
290
- this.modules.score.resetLevel();
291
- this.modules.time.reset();
292
- this.modules.session.clearSession();
293
- this._initialStateSnapshot.restoreInitialState(this);
294
- state.resetGameOver();
295
- }
296
- });
297
-
298
- state.subscribe(StateProperty.ON, isOn => {
299
- if (!isOn) {
300
- grid.resetGrid();
301
- this.modules.score.resetScore();
302
- this.modules.score.resetLevel();
303
- this.modules.time.reset();
304
- }
305
- });
306
- }
307
- }
@@ -1,51 +0,0 @@
1
- import { describe, it, expect, vi } from 'vitest';
2
- import InitialStateSnapshot from './InitialStateSnapshot';
3
-
4
- describe('InitialStateSnapshot', () => {
5
- it('should ignore base properties and capture custom client properties using structuredClone', () => {
6
- // [ARRANGE]
7
- const snapshot = new InitialStateSnapshot();
8
- const instance: Record<string, unknown> = {
9
- _baseProp: 'base',
10
- setupGame: () => {},
11
- };
12
-
13
- // [ACT]
14
- snapshot.captureBaseProperties(instance);
15
- instance.customNumber = 42;
16
- instance.customArray = [1, 2, 3];
17
- snapshot.captureInitialState(instance);
18
-
19
- instance.customNumber = 100;
20
- (instance.customArray as number[]).push(4);
21
-
22
- snapshot.restoreInitialState(instance);
23
-
24
- // [ASSERT]
25
- expect(instance.customNumber).toBe(42);
26
- expect(instance.customArray).toEqual([1, 2, 3]);
27
- expect(instance._baseProp).toBe('base');
28
- });
29
-
30
- it('should fallback to reference if structuredClone fails', () => {
31
- // [ARRANGE]
32
- const snapshot = new InitialStateSnapshot();
33
- const instance: Record<string, unknown> = { _base: true };
34
- snapshot.captureBaseProperties(instance);
35
-
36
- // Object containing a function throws DataCloneError in structuredClone
37
- const uncloneableObj: Record<string, unknown> = { func: () => {} };
38
- instance.uncloneable = uncloneableObj;
39
-
40
- const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
41
-
42
- // [ACT]
43
- snapshot.captureInitialState(instance);
44
-
45
- // [ASSERT]
46
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Failed to clone property uncloneable:'), expect.any(Error));
47
-
48
- // Cleanup spy
49
- consoleSpy.mockRestore();
50
- });
51
- });
@@ -1,46 +0,0 @@
1
- export default class InitialStateSnapshot {
2
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
3
- private _initialState: Map<string, any> = new Map();
4
- private _baseProperties: string[] = [];
5
-
6
- /**
7
- * Captures the base properties of the instance before any custom client properties are added.
8
- * @param instance The object instance to extract keys from.
9
- */
10
- captureBaseProperties(instance: object): void {
11
- this._baseProperties = Object.keys(instance);
12
- }
13
-
14
- /**
15
- * Stores the initial state of custom client properties.
16
- * @param instance The object instance containing custom properties.
17
- */
18
- captureInitialState(instance: object): void {
19
- console.log('capturing initial state for snapshot');
20
- Object.entries(instance).forEach(([key, value]) => {
21
- if (!this._baseProperties.includes(key) && typeof value !== 'function') {
22
- let initialValue = value;
23
- try {
24
- initialValue = structuredClone(value);
25
- console.log('capturing property', key, initialValue);
26
- } catch (e) {
27
- console.error(`Failed to clone property ${key}:`, e);
28
- }
29
- this._initialState.set(key, initialValue);
30
- }
31
- });
32
- }
33
-
34
- /**
35
- * Restores the captured custom properties back to the instance.
36
- * @param instance The object instance to restore properties onto.
37
- */
38
- restoreInitialState(instance: object): void {
39
- console.log('restoring initial snapshot');
40
- this._initialState.forEach((value, key) => {
41
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
42
- (instance as any)[key] = value;
43
- console.log('restoring property', key, value);
44
- });
45
- }
46
- }
@@ -1,33 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import CellHelper from './CellHelper';
3
- import { Color } from '../types/enums';
4
-
5
- describe('CellHelper', () => {
6
- describe('emptyCell', () => {
7
- it('should create an empty cell with value 0 and default color at the given coordinate', () => {
8
- // [ARRANGE]
9
- const coordinate = { x: 10, y: 20 };
10
-
11
- // [ACT]
12
- const result = CellHelper.emptyCell(coordinate);
13
-
14
- // [ASSERT]
15
- expect(result).toEqual({
16
- value: 0,
17
- color: Color.DEFAULT,
18
- coordinate: { x: 10, y: 20 },
19
- });
20
- });
21
-
22
- it('should maintain the reference to the coordinates provided', () => {
23
- // [ARRANGE]
24
- const coordinate = { x: 5, y: 5 };
25
-
26
- // [ACT]
27
- const result = CellHelper.emptyCell(coordinate);
28
-
29
- // [ASSERT]
30
- expect(result.coordinate).toBe(coordinate);
31
- });
32
- });
33
- });
@@ -1,21 +0,0 @@
1
- import { Color } from '../types/enums';
2
- import { Cell, Coordinate } from '../types/Types';
3
-
4
- /**
5
- * Utility class for creating and managing grid cells.
6
- */
7
- export default class CellHelper {
8
- /**
9
- * Creates a new empty cell at the specified coordinate.
10
- *
11
- * @param {Coordinate} coordinate - The location of the new cell.
12
- * @returns {Cell} A new cell object initialized with value 0 and default color.
13
- */
14
- static emptyCell(coordinate: Coordinate): Cell {
15
- return {
16
- value: 0,
17
- color: Color.DEFAULT,
18
- coordinate,
19
- };
20
- }
21
- }
@@ -1,116 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
- import ControlInputHandlerHelper from './ControlInputHandlerHelper';
3
- import { ControlKey, ControlEventType } from '../types/Types';
4
- import { Control } from '../types/modules';
5
-
6
- // [ARRANGE] Mock configs
7
- vi.mock('../../config/configs', () => ({
8
- default: {
9
- buttonHold: {
10
- holdDelayMs: 200,
11
- holdIntervalMs: 50,
12
- },
13
- },
14
- }));
15
-
16
- describe('ControlInputHandlerHelper', () => {
17
- let handler: ControlInputHandlerHelper;
18
- let mockControl: Control;
19
-
20
- beforeEach(() => {
21
- vi.useFakeTimers();
22
- mockControl = {
23
- notify: vi.fn(),
24
- } as unknown as Control;
25
- handler = new ControlInputHandlerHelper(mockControl);
26
- });
27
-
28
- afterEach(() => {
29
- vi.restoreAllMocks();
30
- });
31
-
32
- describe('handlePress', () => {
33
- it('should notify PRESSED immediately when key is pressed', () => {
34
- // [ACT]
35
- handler.handlePress(ControlKey.LEFT);
36
-
37
- // [ASSERT]
38
- expect(mockControl.notify).toHaveBeenCalledWith(ControlKey.LEFT, ControlEventType.PRESSED);
39
- });
40
-
41
- it('should not notify PRESSED if the same key is already active', () => {
42
- // [ARRANGE]
43
- handler.handlePress(ControlKey.LEFT);
44
- vi.mocked(mockControl.notify).mockClear();
45
-
46
- // [ACT]
47
- handler.handlePress(ControlKey.LEFT);
48
-
49
- // [ASSERT]
50
- expect(mockControl.notify).not.toHaveBeenCalled();
51
- });
52
-
53
- it('should start notifying HELD after the hold delay', () => {
54
- // [ACT]
55
- handler.handlePress(ControlKey.LEFT);
56
-
57
- // Fast-forward past delay
58
- vi.advanceTimersByTime(200); // holdDelayMs
59
-
60
- // Fast-forward through one interval
61
- vi.advanceTimersByTime(50); // holdIntervalMs
62
-
63
- // [ASSERT]
64
- expect(mockControl.notify).toHaveBeenCalledWith(ControlKey.LEFT, ControlEventType.HELD);
65
- });
66
-
67
- it('should continue notifying HELD on every interval', () => {
68
- // [ACT]
69
- handler.handlePress(ControlKey.LEFT);
70
- vi.advanceTimersByTime(200); // skip delay
71
-
72
- vi.advanceTimersByTime(150); // 3 intervals
73
-
74
- // [ASSERT]
75
- // 1 (PRESSED) + 3 (HELD) = 4 notifications
76
- expect(mockControl.notify).toHaveBeenCalledTimes(4);
77
- expect(mockControl.notify).toHaveBeenLastCalledWith(ControlKey.LEFT, ControlEventType.HELD);
78
- });
79
- });
80
-
81
- describe('handleRelease', () => {
82
- it('should stop notifications and cleanup when key is released', () => {
83
- // [ARRANGE]
84
- handler.handlePress(ControlKey.LEFT);
85
- vi.advanceTimersByTime(200); // delay
86
- vi.advanceTimersByTime(50); // 1 held
87
- expect(mockControl.notify).toHaveBeenCalledTimes(2);
88
-
89
- // [ACT]
90
- handler.handleRelease(ControlKey.LEFT);
91
- vi.advanceTimersByTime(100); // advance time more
92
-
93
- // [ASSERT]
94
- expect(mockControl.notify).toHaveBeenCalledTimes(2); // Still 2
95
- });
96
-
97
- it('should handle release for a key that was not pressed gracefully', () => {
98
- // [ACT & ASSERT]
99
- expect(() => handler.handleRelease(ControlKey.RIGHT)).not.toThrow();
100
- });
101
-
102
- it('should cancel delay timer if released before it completes', () => {
103
- // [ARRANGE]
104
- handler.handlePress(ControlKey.LEFT);
105
-
106
- // [ACT]
107
- vi.advanceTimersByTime(100); // Half-way through delay
108
- handler.handleRelease(ControlKey.LEFT);
109
- vi.advanceTimersByTime(200); // Complete what would have been the delay
110
-
111
- // [ASSERT]
112
- expect(mockControl.notify).toHaveBeenCalledTimes(1); // Only PRESSED
113
- expect(mockControl.notify).not.toHaveBeenCalledWith(ControlKey.LEFT, ControlEventType.HELD);
114
- });
115
- });
116
- });
@@ -1,68 +0,0 @@
1
- import { ControlEventType, ControlKey } from '../types/Types';
2
- import { Control } from '../types/modules';
3
- import configs from '../../config/configs';
4
-
5
- /**
6
- * Helper class that standardizes input handling logic.
7
- * It manages the distinction between single 'press' events and continuous 'hold' events
8
- * for both keyboard and UI button inputs.
9
- */
10
- export default class ControlInputHandlerHelper {
11
- private _control: Control;
12
- private _activeKeys: Map<ControlKey, { delay: NodeJS.Timeout; hold: NodeJS.Timeout }> = new Map();
13
-
14
- /**
15
- * Creates an instance of the input handler.
16
- *
17
- * @param {Control} control - The control module instance to notify.
18
- */
19
- constructor(control: Control) {
20
- this._control = control;
21
- }
22
-
23
- /**
24
- * Processes a key down or button press action.
25
- * Triggers an immediate {@link ControlEventType.PRESSED} event, and schedules
26
- * a {@link ControlEventType.HELD} loop if the key remains active.
27
- *
28
- * @param {ControlKey} key - The identity of the control key being pressed.
29
- */
30
- handlePress(key: ControlKey): void {
31
- if (this._activeKeys.has(key)) return; // Prevent double handling
32
-
33
- // 1. Notify Pressed
34
- this._control.notify(key, ControlEventType.PRESSED);
35
-
36
- // 2. Schedule Hold
37
- const delayTimer = setTimeout(() => {
38
- const holdTimer = setInterval(() => {
39
- this._control.notify(key, ControlEventType.HELD);
40
- }, configs.buttonHold.holdIntervalMs);
41
-
42
- // Update map with hold timer
43
- const timers = this._activeKeys.get(key);
44
- if (timers) {
45
- timers.hold = holdTimer;
46
- }
47
- }, configs.buttonHold.holdDelayMs);
48
-
49
- this._activeKeys.set(key, { delay: delayTimer, hold: null });
50
- }
51
-
52
- /**
53
- * Processes a key up or button release action.
54
- * Cancels any pending hold timers and cleans up the active key state.
55
- *
56
- * @param {ControlKey} key - The identity of the control key being released.
57
- */
58
- handleRelease(key: ControlKey): void {
59
- const timers = this._activeKeys.get(key);
60
- if (timers) {
61
- clearTimeout(timers.delay);
62
- if (timers.hold) {
63
- clearInterval(timers.hold);
64
- }
65
- this._activeKeys.delete(key);
66
- }
67
- }
68
- }