
# Slot Game Kit CLI

This CLI provides tools to simplify the development and building of HTML5 games. It is based on Webpack and offers pre-configured commands for development, building, and testing projects.

## Installation

1. Install the package via npm:
   ```bash
   npm install @popiplay/slot-game-kit --save-dev
   ```

2. Ensure Webpack and its dependencies are installed in your project:
   ```bash
   npm install webpack webpack-cli webpack-dev-server --save-dev
   ```

## Commands

The CLI provides the following commands:

### 1. **Start Development**

Launches the development server (using `webpack-dev-server`) and automatically updates the project when files are changed.

```bash
npx slotgamekit watch
```

Or add it to your project's `package.json`:

```json
"scripts": {
  "watch": "slotgamekit watch"
}
```

Run:
```bash
npm run watch
```

---

### 2. **Build for Development**

Creates a build in development mode using `webpack.dev.js`. Suitable for local testing.

```bash
npx slotgamekit dev
```

Or add it to your project's `package.json`:

```json
"scripts": {
  "dev": "slotgamekit dev"
}
```

Run:
```bash
npm run dev
```

---

### 3. **Build for Production**

Creates an optimized build for production using `webpack.prod.js`.

```bash
npx slotgamekit prod
```

Or add it to your project's `package.json`:

```json
"scripts": {
  "prod": "slotgamekit prod"
}
```

Run:
```bash
npm run prod
```

---

### 4. **Build for Staging**

Creates a build for testing in staging environments using `webpack.staging.js`.

```bash
npx slotgamekit staging
```

Or add it to your project's `package.json`:

```json
"scripts": {
  "staging": "slotgamekit staging"
}
```

Run:
```bash
npm run staging
```

---

## Webpack Configuration

### Supported Configurations:
1. `webpack.common.js` – shared settings.
2. `webpack.dev.js` – development configuration.
3. `webpack.prod.js` – production configuration.
4. `webpack.staging.js` – staging configuration.

## Feature multipliers

The CLI ships with a default set of feature multipliers (`bonusBuy`, `freespinBuy`, `bonusChance`).
When backend pricing is unavailable for Bonus Chance the runtime keeps the multiplier at `1` so the
stake displayed to players remains unchanged while the feature is temporarily disabled.

Call `Model.resolveFeatureStake(bet)` whenever the UI needs to present the wager with Bonus Chance
enabled—the helper automatically applies the active multiplier so Wild Spin toggles stay in sync.

All configurations are located in the `bundler/` folder inside the package.

### Optional line configuration

Cluster and ways titles are no longer required to ship a `lines` array in the init payload or machine configuration. When both values are missing the runtime now boots with an empty definition and keeps `Mode.lines` consistent. Provide a line matrix only for payline-based games.

---

## Additional Settings

### Babel
The `.babelrc` configuration file is provided with the package. Make sure it is used in your project.

### Browserslist
The `.browserslistrc` file defines browser support and is also included in the package.

To use it, specify its path via the environment variable:

```bash
BROWSERSLIST_CONFIG=node_modules/@popiplay/slot-game-kit/.browserslistrc
```

---

## Overview

The project is organized into the following key folders:

-   **`activities/`**: Manages a queue of activities to be executed sequentially. Activities are added to the queue and automatically processed when the runner is idle. Each activity should be an object with a `name` property and an asynchronous `execute` method.
    Besides the main `ActivityRunner` and `Activity` classes implementing this functionality, there are also commands for pausing and resuming the game clock, displaying error popups, and similar actions.

-   **`constants/`**: Contains fixed values used throughout the project to enhance readability and maintainability. These include viewport and renderer settings, and scene names.

-   **`controllers/`**: Houses the `BaseGameController`, which is intended to be extended by the game-specific controller. This class is designed to handle all user interactions, such as opening the game rules or paytable, and launching the buy bonus screen. Additionally, it includes methods responsible for displaying big win, max win, and similar in-game screens or animations.

-   **`devtools/`**:

-   **`errors/`**: Contains the `ErrorProcessor`, used by controllers to display corresponding error popups.

-   **`extensions/`**: Includes PixiJS extensions that add features beyond the core library. The `extensions` object from PixiJS manages these additions. Specific extensions include:
    -   `AudioSpriteLoader`: A simple loader plugin for audio sprite files.
    -   `BasePathInjector`: Modifies asset paths by adding the `baseAssetsUrl` fetched from the backend.
    -   `GlobalPointerEvents`: A class representing the global events system, emitting pointer events through `Locator.events`.
    -   `loadHtml`: A simple loader plugin for loading rules content from HTML files.

-   **`fairyScenes/`**:

-   **`game/`**: Contains the `BaseGame` class, which is intended to be extended by the game-specific class. It is responsible for creating scenes, models, and the controller. The `start` method initiates the game clock, and the `update` and `resize` methods handle rendering and adjusting the game's dimensions.

-   **`helpers/`**: Contains simple `scaleToFit` methods used to resize text to fit within given bounds.

-   **`models/`**: Defines the data representation of various elements within the game world. Models store the state and properties of game objects, characters, environments, and game rules, independent of their visual rendering or behavior. Specific models include:
    -   `AutoGameModel`: Manages auto-spin functionality, including spin limits, balance tracking, and stop conditions.
    -   `BalanceModel`: Manages the player's in-game balance, handling updates, validation, and affordability checks. Its `add`
        method now accepts zero so callers can record settled rounds without mutating the balance.
    -   `BetModel`: Manages available bet options, allowing for increasing, decreasing, and setting specific bet values, with support for locking betting actions.
    -   `EndRoundModel`: Determines the next game state after a round ends (e.g., big win, max win, free spins trigger, bonus exit).
    -   `Model`: Base class for models, providing methods for initialization and loading data from the backend using `Locator.network` and `ModelDataInitializer`.
        -   Space-bar spin preferences persist through `Locator.storage`, mirroring the legacy runtime so toggles survive reloads.
    -   `ModelDataInitializer`: Used by the `Model` class to parse raw data received from the backend.
    -   `PaytableModel`: Represents a collection of paytables.
    -   `VolumeModel`: Controls the volume levels for sound and music, including muting.
    -   `Currency`: Provides formatting utilities for currency values.
    -   `Lines`: Represents a collection of line configurations. The model now accepts empty definitions so cluster and ways games can omit lines entirely without breaking initialization.
    -   `ModeStack`: Manages a stack of game modes for handling nested game states.

-   **`scene/`**: Contains the `Scene` class, which serves as the base class for all scenes within the game.

-   **`services/`**: Contains classes that provide various services accessible through the `Locator` service locator:
    -   `Locator`: A service locator class providing access to all registered services.
    -   `audio`:
        -   `AudioSprites`: Responsible for playing sounds, accessible via `Locator.audio.play()`.
        -   `LogAudio`: A simple audio logger.
    -   `clock`:
        -   `Clock`: Represents the game ticker, driven by `requestAnimationFrame`.
        -   `DevClock`: Extends the `Clock` class for development purposes.
    -   `events`:
        -   `Events`: Extends `EventEmitter` from the `eventemitter3` library, used for inter-component communication.
    -   `locales`:
        -   Handles loading translation files and retrieving translations for given string IDs (e.g., `Locator.locales.get("total_win")`).
    -   `manifest`:
        -   `ManifestService`: Merges PixiJS manifests and can prepend a `basePath` and append `defaultSearchParams` to every remote manifest source, mirroring the `Assets.init` configuration.
    -   `network`:
        -   `LocalNetwork`: A class for handling network requests, with `createRequest` calling the `fetch` API.
        -   `ReplayNetwork`: Replays recorded backend responses from a static `replayUrl` for deterministic sessions.
    -   `renderer`:
        -   `Renderer2D`: Extends PixiJS's `Renderer`, created in the main game file (`index.js`) and used for rendering the game (`Locator.renderer.render()`).
    -   `scenes`:
        -   `Scenes`: A class representing a collection of scenes, implementing the `IScenes` interface.
    -   `storage`:
        -   `StorageService`: Uses `localStorage` to read and write flags (e.g., `Locator.storage.set('introHasBeenShown', true)`). `localStorage` is a persistent client-side storage API for key/value pairs within the user's browser.
    -   `user`:
        -   `DevUser`:
    -   `viewport`:
        -   `Viewport`: Extends PixiJS's `Container` (also known as `Viewport`), responsible for holding all game elements and managing game resizing.

-   **`types/`**: Contains TypeScript definition files (e.g., `ViewportOptions`).

-   **`utils/`**: Contains reusable helper functions and utility classes for common tasks like data manipulation, formatting, and mathematical operations. `waitForEventOnce` is used throughout the project to block the execution flow until a specific event occurs.

-   **`viewmodels/`**: Contains classes that prepare and manage data for the views:
    -   `BuyBonusViewModel`: Manages data and logic for the buy bonus/buy free spins feature, coercing undefined bonus toggle values to disabled, clearing cached bet lists whenever the bonus chance toggle changes, and re-evaluating availability with `resolveFeatureStake` so the `BetPicker` reflects the latest stakes and balance guardrails.
    -   `GameplayViewModel`: Provides various getters from the game models that are important for gameplay, such as currency, round start/end status, and turbo mode activation.

## Usage
This section provides guidance on how to integrate and use the various components and features of the framework within your game project.

### Devtools Feature: Back Panel
The `BackPanel` creates a customizable back panel with user and service controls
that can be added dynamically.
 - Manages user controls for server URL, shared player, custom player, and user switching with options stored in local storage.
 - Provides functionality for managing audio settings and inspecting sounds in a web application.
 - Creates a user interface for controlling the timescale and pause functionality of a clock.
 *- Adds cheat controls to a pane and allows for testing cheats by making POST requests to a specified URL.* WIP?



To utilize the `BackPanel` in your game project, you need to instantiate its primary class and integrate it into your game logic.

**Instantiation:**
```javascript
// In your game project's index.js file
import {BackPanel} from "@popiplay/slot-game-kit";
const backPanel = new BackPanel();
backPanel.addUserControls();
// after Locator.provide() calls add this line
backPanel.addOtherControls();
```
You can toggle the visibility of the back panel by pressing H or h on your keyboard.

## Support

If you have any questions or issues using this CLI, refer to the documentation or create an issue in the package's repository.
