brick-engine-js 1.0.1 → 1.0.3

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 (131) 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 +8 -1
  13. package/public/docs/GAME_DEVELOPER_GUIDE.html +1 -1
  14. package/public/docs/brick-engine-guide.html +1 -1
  15. package/public/docs/getting-started.html +1 -1
  16. package/public/docs/jsdoc_standard.html +1 -1
  17. package/public/docs/publishing.html +1 -1
  18. package/public/docs/reference/interfaces/modules/Session.html +1 -1
  19. package/public/docs/reference/modules/GameMenu.html +1 -1
  20. package/public/docs/reference/modules/GameSession.html +1 -1
  21. package/public/docs/reference/modules/InitialStateSnapshot.html +1 -1
  22. package/public/docs/reference/modules/SessionModal.html +1 -1
  23. package/public/docs/testing_best_practices.html +1 -1
  24. package/.env.local.example +0 -2
  25. package/.github/workflows/publish.yml +0 -73
  26. package/.prettierignore +0 -2
  27. package/.prettierrc.json +0 -8
  28. package/eslint.config.mjs +0 -29
  29. package/scripts/generate-diagrams.sh +0 -20
  30. package/scripts/generate-docs.js +0 -111
  31. package/src/client-game.d.ts +0 -1
  32. package/src/config/configs.test.ts +0 -20
  33. package/src/config/configs.ts +0 -197
  34. package/src/config/env.test.ts +0 -59
  35. package/src/config/env.ts +0 -7
  36. package/src/config/styles.ts +0 -5
  37. package/src/core/Game.test.ts +0 -167
  38. package/src/core/Game.ts +0 -307
  39. package/src/core/InitialStateSnapshot.test.ts +0 -51
  40. package/src/core/InitialStateSnapshot.ts +0 -46
  41. package/src/core/helpers/CellHelper.test.ts +0 -33
  42. package/src/core/helpers/CellHelper.ts +0 -21
  43. package/src/core/helpers/ControlInputHandlerHelper.test.ts +0 -116
  44. package/src/core/helpers/ControlInputHandlerHelper.ts +0 -68
  45. package/src/core/helpers/CoordinateHelper.test.ts +0 -113
  46. package/src/core/helpers/CoordinateHelper.ts +0 -82
  47. package/src/core/helpers/InterfaceIdentifierHelper.test.ts +0 -122
  48. package/src/core/helpers/InterfaceIdentifierHelper.ts +0 -43
  49. package/src/core/helpers/RelativeValuesHelper.test.ts +0 -47
  50. package/src/core/helpers/RelativeValuesHelper.ts +0 -29
  51. package/src/core/module/control/GameControl.test.ts +0 -82
  52. package/src/core/module/control/GameControl.ts +0 -142
  53. package/src/core/module/control/GameControlKeyBinding.test.ts +0 -59
  54. package/src/core/module/control/GameControlKeyBinding.ts +0 -92
  55. package/src/core/module/grid/GameGrid.test.ts +0 -83
  56. package/src/core/module/grid/GameGrid.ts +0 -610
  57. package/src/core/module/grid/GameHudGrid.test.ts +0 -22
  58. package/src/core/module/grid/GameHudGrid.ts +0 -40
  59. package/src/core/module/grid/engines/GridAnalysisEngine.test.ts +0 -157
  60. package/src/core/module/grid/engines/GridAnalysisEngine.ts +0 -124
  61. package/src/core/module/grid/engines/GridLineEngine.test.ts +0 -132
  62. package/src/core/module/grid/engines/GridLineEngine.ts +0 -165
  63. package/src/core/module/grid/engines/GridMovementEngine.test.ts +0 -125
  64. package/src/core/module/grid/engines/GridMovementEngine.ts +0 -113
  65. package/src/core/module/grid/engines/GridRegionEngine.test.ts +0 -136
  66. package/src/core/module/grid/engines/GridRegionEngine.ts +0 -52
  67. package/src/core/module/grid/engines/GridTransformEngine.test.ts +0 -98
  68. package/src/core/module/grid/engines/GridTransformEngine.ts +0 -70
  69. package/src/core/module/renderer/DisplayRenderer.test.ts +0 -86
  70. package/src/core/module/renderer/DisplayRenderer.ts +0 -152
  71. package/src/core/module/renderer/GameRenderer.test.ts +0 -103
  72. package/src/core/module/renderer/GameRenderer.ts +0 -144
  73. package/src/core/module/renderer/HudRenderer.test.ts +0 -108
  74. package/src/core/module/renderer/HudRenderer.ts +0 -203
  75. package/src/core/module/score/GameScore.test.ts +0 -71
  76. package/src/core/module/score/GameScore.ts +0 -188
  77. package/src/core/module/session/GameSession.test.ts +0 -176
  78. package/src/core/module/session/GameSession.ts +0 -103
  79. package/src/core/module/sound/GameSound.test.ts +0 -117
  80. package/src/core/module/sound/GameSound.ts +0 -229
  81. package/src/core/module/state/GameState.test.ts +0 -101
  82. package/src/core/module/state/GameState.ts +0 -339
  83. package/src/core/module/text/GameText.test.ts +0 -87
  84. package/src/core/module/text/GameText.ts +0 -150
  85. package/src/core/module/time/GameTime.test.ts +0 -86
  86. package/src/core/module/time/GameTime.ts +0 -144
  87. package/src/core/types/Interfaces.ts +0 -59
  88. package/src/core/types/Types.ts +0 -124
  89. package/src/core/types/enums.ts +0 -113
  90. package/src/core/types/modules.ts +0 -841
  91. package/src/index.test.ts +0 -15
  92. package/src/index.ts +0 -9
  93. package/src/main.test.ts +0 -137
  94. package/src/main.ts +0 -77
  95. package/src/menu/GameMenu.test.ts +0 -157
  96. package/src/menu/GameMenu.ts +0 -124
  97. package/src/menu/GameMenuSingleton.test.ts +0 -26
  98. package/src/menu/GameMenuSingleton.ts +0 -13
  99. package/src/menu/GameRepository.test.ts +0 -46
  100. package/src/menu/GameRepository.ts +0 -47
  101. package/src/menu/manager/GameManager.test.ts +0 -68
  102. package/src/menu/manager/GameManager.ts +0 -50
  103. package/src/types/global.d.ts +0 -8
  104. package/src/types/interfaces.ts +0 -5
  105. package/src/view/Debugger.test.ts +0 -152
  106. package/src/view/Debugger.ts +0 -124
  107. package/src/view/GameView.test.ts +0 -95
  108. package/src/view/GameView.ts +0 -244
  109. package/src/view/SessionModal.test.ts +0 -141
  110. package/src/view/SessionModal.ts +0 -73
  111. package/src/view/components/layout/ButtonLayout.test.ts +0 -28
  112. package/src/view/components/layout/ButtonLayout.ts +0 -63
  113. package/src/view/components/layout/ContainerLayout.test.ts +0 -48
  114. package/src/view/components/layout/ContainerLayout.ts +0 -50
  115. package/src/view/components/layout/FrameLayout.test.ts +0 -24
  116. package/src/view/components/layout/FrameLayout.ts +0 -25
  117. package/src/view/components/ui/BigButton.test.ts +0 -28
  118. package/src/view/components/ui/BigButton.ts +0 -31
  119. package/src/view/components/ui/Button.test.ts +0 -30
  120. package/src/view/components/ui/Button.ts +0 -30
  121. package/src/view/components/ui/Canvas.test.ts +0 -32
  122. package/src/view/components/ui/Canvas.ts +0 -34
  123. package/src/view/components/ui/SmallButton.test.ts +0 -48
  124. package/src/view/components/ui/SmallButton.ts +0 -32
  125. package/src/view/theme/applyColors.test.ts +0 -47
  126. package/src/view/theme/applyColors.ts +0 -38
  127. package/src/view/theme/dimensions.test.ts +0 -34
  128. package/src/view/theme/dimensions.ts +0 -53
  129. package/tsconfig.json +0 -16
  130. package/vitest.config.ts +0 -14
  131. package/webpack.config.js +0 -133
@@ -1,103 +0,0 @@
1
- import { Serializable } from '../../types/Interfaces';
2
- import { StateProperty } from '../../types/enums';
3
- import { Session, State } from '../../types/modules';
4
-
5
- export default class GameSession implements Session {
6
- _state: State;
7
- gameId: string;
8
-
9
- private _isModalClosed: boolean = false;
10
- private _showSessionModal: (onConfirm: () => void, onCancel: () => void) => void;
11
- private _serializables: Serializable[] = [];
12
-
13
- register(serializable: Serializable): void {
14
- this._serializables.push(serializable);
15
- }
16
-
17
- saveSession(): void {
18
- if (!this._isModalClosed || this._isGameMenuInstance()) return;
19
-
20
- this._serializables.forEach(serializable => {
21
- localStorage.setItem(this._key(serializable.serialId), serializable.serialize());
22
- });
23
- }
24
-
25
- clearSession(): void {
26
- this._serializables.forEach(serializable => {
27
- localStorage.removeItem(this._key(serializable.serialId));
28
- });
29
- }
30
-
31
- setShowModalFunction(showModal: (onConfirm: () => void, onCancel: () => void) => void): void {
32
- this._showSessionModal = showModal;
33
- }
34
-
35
- private _isGameMenuInstance(): boolean {
36
- return this.gameId === 'game-menu';
37
- }
38
-
39
- private _hasSession(): boolean {
40
- return this._serializables.every(serializable => localStorage.getItem(this._key(serializable.serialId)) !== null);
41
- }
42
-
43
- private _loadSession(): void {
44
- this._serializables.forEach(serializable => {
45
- const data = localStorage.getItem(this._key(serializable.serialId));
46
- if (data) {
47
- serializable.deserialize(data);
48
- }
49
- });
50
- }
51
- private _destroySession(): void {
52
- this._serializables.forEach(serializable => {
53
- localStorage.removeItem(this._key(serializable.serialId));
54
- });
55
- }
56
-
57
- syncState(state: State): void {
58
- state.subscribe(StateProperty.PLAYING, isPlaying => {
59
- if (isPlaying && this._isModalClosed === false) {
60
- if (!this._hasSession() || this._isGameMenuInstance()) {
61
- this._isModalClosed = true;
62
- return;
63
- }
64
-
65
- this._showSessionModal(
66
- () => {
67
- if (this._hasSession() && !this._isGameMenuInstance()) {
68
- this._loadSession();
69
- }
70
- this._isModalClosed = true;
71
- },
72
- () => {
73
- this._destroySession();
74
- this._isModalClosed = true;
75
- },
76
- );
77
- }
78
- });
79
-
80
- state.subscribe(StateProperty.GAME_OVER, isGameOver => {
81
- if (isGameOver) {
82
- this._destroySession();
83
- }
84
- });
85
-
86
- state.subscribe(StateProperty.ON, isOn => {
87
- if (!isOn) {
88
- this._isModalClosed = false;
89
- }
90
- });
91
- }
92
-
93
- getDebugData(): Record<string, string | number | boolean> {
94
- return {
95
- gameId: this.gameId,
96
- serializables: this._serializables.map(serializable => serializable.serialId).join(', '),
97
- };
98
- }
99
-
100
- private _key(key: string): string {
101
- return `${this.gameId}::${key}`;
102
- }
103
- }
@@ -1,117 +0,0 @@
1
- /** @vitest-environment jsdom */
2
- import { describe, it, expect, vi, beforeEach } from 'vitest';
3
- import GameSound from './GameSound';
4
- import { State } from '../../types/modules';
5
- import { Sound } from '../../types/enums';
6
-
7
- describe('GameSound', () => {
8
- let gameSound: GameSound;
9
- let mockState: State;
10
- let mockAudioContext: {
11
- createGain: () => void;
12
- createBufferSource: () => void;
13
- destination: Record<string, unknown>;
14
- currentTime: number;
15
- resume: () => Promise<void>;
16
- decodeAudioData: () => Promise<Record<string, unknown>>;
17
- state: string;
18
- };
19
- let mockGainNode: {
20
- connect: () => void;
21
- gain: {
22
- setValueAtTime: (value: number, time: number) => void;
23
- };
24
- };
25
-
26
- beforeEach(() => {
27
- // [ARRANGE] Mock GainNode
28
- mockGainNode = {
29
- connect: vi.fn(),
30
- gain: {
31
- setValueAtTime: vi.fn(),
32
- },
33
- };
34
-
35
- // [ARRANGE] Mock AudioContext
36
- mockAudioContext = {
37
- createGain: vi.fn().mockReturnValue(mockGainNode),
38
- createBufferSource: vi.fn().mockReturnValue({
39
- connect: vi.fn(),
40
- start: vi.fn(),
41
- stop: vi.fn(),
42
- buffer: null,
43
- onended: null,
44
- }),
45
- destination: {},
46
- currentTime: 0,
47
- resume: vi.fn().mockResolvedValue(undefined),
48
- decodeAudioData: vi.fn().mockResolvedValue({}),
49
- state: 'running',
50
- };
51
-
52
- // We use vi.fn because jsdom window doesn't have AudioContext
53
- vi.stubGlobal(
54
- 'AudioContext',
55
- vi.fn().mockImplementation(function () {
56
- return mockAudioContext as unknown as AudioContext;
57
- }),
58
- );
59
- vi.stubGlobal(
60
- 'fetch',
61
- vi.fn().mockResolvedValue({
62
- arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(0)),
63
- }),
64
- );
65
-
66
- mockState = {
67
- isMuted: vi.fn().mockReturnValue(false),
68
- subscribe: vi.fn(),
69
- toggleMuted: vi.fn(),
70
- } as unknown as State;
71
-
72
- gameSound = new GameSound();
73
- gameSound.syncState(mockState);
74
- });
75
-
76
- describe('setup', () => {
77
- it('should initialize AudioContext and GainNode', () => {
78
- // [ACT]
79
- gameSound.setup();
80
-
81
- // [ASSERT]
82
- expect(mockAudioContext.createGain).toHaveBeenCalled();
83
- expect(mockGainNode.connect).toHaveBeenCalledWith(mockAudioContext.destination);
84
- });
85
- });
86
-
87
- describe('toggleMute', () => {
88
- it('should call state.toggleMuted and update gain', () => {
89
- // [ARRANGE]
90
- gameSound.setup();
91
-
92
- // [ACT]
93
- gameSound.toggleMute();
94
-
95
- // [ASSERT]
96
- expect(mockState.toggleMuted).toHaveBeenCalled();
97
- expect(mockGainNode.gain.setValueAtTime).toHaveBeenCalled();
98
- });
99
- });
100
-
101
- describe('play', () => {
102
- it('should resume context if suspended and play sound', async () => {
103
- // [ARRANGE]
104
- mockAudioContext.state = 'suspended';
105
- gameSound.setup();
106
-
107
- (gameSound as unknown as { _buffers: Map<Sound, AudioBuffer> })['_buffers'].set(Sound.SPAWN, {} as AudioBuffer);
108
-
109
- // [ACT]
110
- await gameSound.play(Sound.SPAWN);
111
-
112
- // [ASSERT]
113
- expect(mockAudioContext.resume).toHaveBeenCalled();
114
- expect(mockAudioContext.createBufferSource).toHaveBeenCalled();
115
- });
116
- });
117
- });
@@ -1,229 +0,0 @@
1
- import configs from '../../../config/configs';
2
- import { Sound, StateProperty } from '../../types/enums';
3
- import { Debuggable, StateSyncable } from '../../types/Interfaces';
4
- import { SoundModule, State } from '../../types/modules';
5
-
6
- /**
7
- * Manages audio playback and sound effects.
8
- * Handles the Web Audio API context, loading sound buffers, and managing volume/muting.
9
- */
10
- export default class GameSound implements SoundModule, StateSyncable, Debuggable {
11
- muted: boolean;
12
-
13
- /**
14
- * The AudioContext is the primary "audio engine" for the browser.
15
- * It manages all sound creation and playback.
16
- */
17
- private _audioContext: AudioContext;
18
-
19
- /**
20
- * The GainNode controls the volume (gain) of the audio.
21
- * All sounds pass through this node before reaching the destination (speakers).
22
- */
23
- private _gainNode: GainNode;
24
-
25
- /**
26
- * Stores loaded sound buffers in memory.
27
- * AudioBuffer contains the decoded audio data ready for playback.
28
- */
29
- private _buffers: Map<Sound, AudioBuffer> = new Map();
30
-
31
- /**
32
- * Tracks currently playing sound sources.
33
- * Required to stop specific sounds (like background music or loops).
34
- */
35
- private _activeSources: Map<Sound, AudioBufferSourceNode[]> = new Map();
36
-
37
- private _volume: number = 1.0;
38
-
39
- _state: State;
40
-
41
- /**
42
- * Initializes the sound system.
43
- * Creates the AudioContext, sets up the master gain node, and starts loading sounds.
44
- */
45
- setup() {
46
- const { volume } = configs.game.sound;
47
- this._volume = volume;
48
-
49
- // Initialize AudioContext.
50
- // The 'webkit' prefix is for compatibility with older browsers (e.g., older Safari).
51
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
52
- const AudioContextClass = window.AudioContext || (window as any).webkitAudioContext;
53
- this._audioContext = new AudioContextClass({ latencyHint: 'interactive' });
54
-
55
- // Create the master volume node (GainNode).
56
- this._gainNode = this._audioContext.createGain();
57
-
58
- // Connect the GainNode to the "destination" (device audio output).
59
- // Flow: Sound Source -> GainNode -> Destination (Speakers)
60
- this._gainNode.connect(this._audioContext.destination);
61
-
62
- this._updateGain();
63
- this._loadAll();
64
- }
65
-
66
- /**
67
- * Plays a specific sound effect.
68
- * Creates a new source node for each playback instance.
69
- *
70
- * @param {Sound} sound - The sound identifier/URL to play.
71
- * @returns {Promise<void>}
72
- */
73
- async play(sound: Sound): Promise<void> {
74
- // Browsers block automatic audio until user interaction.
75
- // If suspended, try to wake up the AudioContext.
76
- if (this._audioContext.state === 'suspended') {
77
- this._audioContext.resume();
78
- }
79
-
80
- const buffer = this._buffers.get(sound);
81
- if (!buffer) {
82
- console.warn(`Sound buffer not found for: ${sound}`);
83
- return;
84
- }
85
-
86
- // To play a sound, we create a "source" (SourceNode).
87
- // Each sound played needs a new SourceNode. They are disposable (fire-and-forget).
88
- const source = this._audioContext.createBufferSource();
89
- source.buffer = buffer;
90
-
91
- // Connect the source to our master volume control.
92
- source.connect(this._gainNode);
93
-
94
- // Track the active source so we can stop it if necessary.
95
- if (!this._activeSources.has(sound)) {
96
- this._activeSources.set(sound, []);
97
- }
98
- const sources = this._activeSources.get(sound)!;
99
- sources.push(source);
100
-
101
- // When the sound finishes playing, remove from active list to free memory.
102
- source.onended = () => {
103
- const index = sources.indexOf(source);
104
- if (index > -1) {
105
- sources.splice(index, 1);
106
- }
107
- };
108
-
109
- // Start playback immediately (0).
110
- source.start(0);
111
- }
112
-
113
- /**
114
- * Stops all instances of a specific sound.
115
- *
116
- * @param {Sound} sound - The sound to stop.
117
- * @returns {Promise<void>}
118
- */
119
- async stop(sound: Sound): Promise<void> {
120
- const sources = this._activeSources.get(sound);
121
- if (sources) {
122
- sources.forEach(source => {
123
- try {
124
- // Stop playback immediately.
125
- source.stop();
126
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
127
- } catch (e) {
128
- // Ignore errors if already stopped.
129
- }
130
- });
131
- sources.length = 0;
132
- }
133
- }
134
-
135
- /**
136
- * Stops all currently playing sounds.
137
- *
138
- * @returns {Promise<void>}
139
- */
140
- async stopAll(): Promise<void> {
141
- const activeSounds = Array.from(this._activeSources.keys());
142
- for (const sound of activeSounds) {
143
- await this.stop(sound);
144
- }
145
- }
146
-
147
- /**
148
- * Updates the master volume based on the muted state.
149
- */
150
- private _updateGain() {
151
- // setValueAtTime is the safe way to change audio parameters in Web Audio API.
152
- // If muted, volume is 0. Otherwise, use configured volume.
153
- const isMuted = this._state ? this._state.isMuted() : false;
154
-
155
- if (!this._gainNode) {
156
- return;
157
- }
158
-
159
- if (isMuted) {
160
- this._gainNode.gain.setValueAtTime(0, this._audioContext.currentTime);
161
- } else {
162
- this._gainNode.gain.setValueAtTime(this._volume, this._audioContext.currentTime);
163
- }
164
- }
165
-
166
- /**
167
- * Loads all sound assets defined in the Sound enum.
168
- * Fetches, buffers, and decodes the audio data.
169
- */
170
- private async _loadAll() {
171
- // Load all sounds defined in the Sound Enum.
172
- // Fetch -> ArrayBuffer -> Decode -> AudioBuffer
173
- const loadPromises = Object.values(Sound).map(async soundUrl => {
174
- try {
175
- const response = await fetch(soundUrl);
176
- const arrayBuffer = await response.arrayBuffer();
177
- // Decoding is heavy, so we do this at the start (loading).
178
- const audioBuffer = await this._audioContext.decodeAudioData(arrayBuffer);
179
- this._buffers.set(soundUrl as Sound, audioBuffer);
180
- } catch (error) {
181
- console.error(`Failed to load sound: ${soundUrl}`, error);
182
- }
183
- });
184
-
185
- await Promise.all(loadPromises);
186
- }
187
-
188
- /**
189
- * Toggles the mute state of the game.
190
- * Updates the state module and the audio gain.
191
- */
192
- toggleMute(): void {
193
- this._state.toggleMuted();
194
- this._updateGain();
195
- }
196
-
197
- /**
198
- * Receives the shared game state module.
199
- * Subscribes to mute state changes.
200
- *
201
- * @param {State} state - The game state module.
202
- */
203
- syncState(state: State): void {
204
- this._state = state;
205
- state.subscribe(StateProperty.MUTED, () => {
206
- this._updateGain();
207
- });
208
-
209
- // Ensure the initial state is applied when synced
210
- this._updateGain();
211
- }
212
-
213
- /**
214
- * Retrieves debug information about the audio system.
215
- *
216
- * @returns {Record<string, string | number | boolean>} The debug data.
217
- */
218
- getDebugData(): Record<string, string | number | boolean> {
219
- let activeSourcesCount = 0;
220
- this._activeSources.forEach(sources => (activeSourcesCount += sources.length));
221
-
222
- return {
223
- muted: this._state ? this._state.isMuted() : false,
224
- volume: this._volume,
225
- active_sources: activeSourcesCount,
226
- loaded_buffers: this._buffers.size,
227
- };
228
- }
229
- }
@@ -1,101 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import GameState from './GameState';
3
- import { StateProperty } from '../../types/Types';
4
-
5
- describe('GameState', () => {
6
- let state: GameState;
7
-
8
- beforeEach(() => {
9
- // [ARRANGE] Mock localStorage
10
- vi.stubGlobal('localStorage', {
11
- getItem: vi.fn().mockReturnValue(null),
12
- setItem: vi.fn(),
13
- removeItem: vi.fn(),
14
- clear: vi.fn(),
15
- });
16
-
17
- state = new GameState();
18
- });
19
-
20
- describe('setup', () => {
21
- it('should initialize with default values', () => {
22
- // [ACT]
23
- state.setup();
24
-
25
- // [ASSERT]
26
- expect(state.isOn()).toBe(false);
27
- expect(state.isColorEnabled()).toBe(true);
28
- });
29
- });
30
-
31
- describe('State Transitions', () => {
32
- beforeEach(() => {
33
- state.setup();
34
- });
35
-
36
- it('should change ON state and notify subscribers', () => {
37
- // [ARRANGE]
38
- const callback = vi.fn();
39
- state.subscribe(StateProperty.ON, callback);
40
-
41
- // [ACT]
42
- state.turnOn();
43
-
44
- // [ASSERT]
45
- expect(state.isOn()).toBe(true);
46
- expect(callback).toHaveBeenCalledWith(true);
47
- });
48
-
49
- it('should not allow starting game if machine is off', () => {
50
- // [ACT]
51
- state.startGame();
52
-
53
- // [ASSERT]
54
- expect(state.isStarted()).toBe(false);
55
- });
56
-
57
- it('should allow starting game if machine is on', () => {
58
- // [ARRANGE]
59
- state.turnOn();
60
-
61
- // [ACT]
62
- state.startGame();
63
-
64
- // [ASSERT]
65
- expect(state.isStarted()).toBe(true);
66
- expect(state.isPlaying()).toBe(true);
67
- });
68
-
69
- it('should handle pause and resume', () => {
70
- // [ARRANGE]
71
- state.turnOn();
72
- state.startGame();
73
- expect(state.isPlaying()).toBe(true);
74
-
75
- // [ACT - Pause]
76
- state.pause();
77
- // [ASSERT]
78
- expect(state.isPlaying()).toBe(false);
79
- expect(state.isPaused()).toBe(true);
80
-
81
- // [ACT - Resume]
82
- state.resume();
83
- // [ASSERT]
84
- expect(state.isPlaying()).toBe(true);
85
- expect(state.isPaused()).toBe(false);
86
- });
87
- });
88
-
89
- describe('Persistence', () => {
90
- it('should save to localStorage when a persisted property changes', () => {
91
- // [ARRANGE]
92
- state.setup();
93
-
94
- // [ACT]
95
- state.setColorEnabled(false);
96
-
97
- // [ASSERT]
98
- expect(localStorage.setItem).toHaveBeenCalledWith('colorEnabled', 'false');
99
- });
100
- });
101
- });