### Project Build and Development Commands (Bash) Source: https://github.com/johnlikescarrot/blockblast/blob/main/AGENTS.md Standard commands for managing the project's dependencies and execution environments. Includes installing packages, starting a development server with hot reloading, and building the project for production deployment. ```bash # Install dependencies npm install # Start development server with hot reload npm start # Build for production (outputs to dist/ folder) npm run build ``` -------------------------------- ### Implement Internationalization (i18n) System in JavaScript Source: https://github.com/johnlikescarrot/blockblast/blob/main/AGENTS.md This code shows the setup and usage of an Internationalization (i18n) system for multi-language support. It covers initializing the I18nManager, setting the preferred language (which is persisted to localStorage), and translating text keys. It requires the I18nManager and SUPPORTED_LOCALES to be imported from './scripts/components/i18n.js'. ```javascript import { I18nManager, SUPPORTED_LOCALES } from './scripts/components/i18n.js'; // Supported languages console.log(SUPPORTED_LOCALES); // ["en", "es"] // Initialize i18n manager const i18n = new I18nManager(scene); i18n.init(); // Get current language console.log(i18n.language); // "en" or "es" // Set language (persisted to localStorage) i18n.setLanguage('es'); // Translate keys const pauseText = i18n.t('PAUSE'); // "Pausa" in Spanish const scoreText = i18n.t('SCORE'); // "Puntuacion" in Spanish const tutorialText = i18n.t('TUTORIAL'); // "Tutorial" in Spanish const gameOverText = i18n.t('GAME_OVER'); // "Fin de Partida" in Spanish // Available translation keys const translationKeys = [ 'SCORE', 'PAUSE', 'OPTIONS', 'CREDITS', 'TUTORIAL', 'GAME_OVER', 'TIME', 'RECORD', 'MUSIC', 'SOUND', 'FULLSCREEN', 'LANGUAGE', 'RESTART', 'ARE_YOU_SURE_RESTART', 'PROGRAMMING', 'ART_ANIMATION', 'MARKETING_UI', 'MUSIC_SOUND', 'DIRECTION', 'EXECUTIVE_PRODUCER' ]; ``` -------------------------------- ### JavaScript Drag and Drop for Piece Placement Source: https://context7.com/johnlikescarrot/blockblast/llms.txt Handles touch and mouse input for placing game pieces. It manages drag start, drag, and drag end events, including visual feedback like piece preview, pointer following, and screen shake on successful placement. Dependencies include scene input events and custom functions like CanPutPiece and InsertPiece. ```javascript scene.input.on('dragstart', function(pointer, gameObject) { if (!isPaused) { audioManager.preview.play(); gameObject.parentContainer.visible = false; currentPiece = optionsPieces[parseInt(gameObject.parentContainer.name)]; pointerContainer.visible = true; canCheck = true; } }); scene.input.on('drag', (pointer, gameObject, dragX, dragY) => { if (!isPaused) { pointerContainer.x = pointer.worldX - 2 * squareSize; pointerContainer.y = pointer.worldY - 2 * squareSize; } }); scene.input.on('dragend', function(pointer, gameObject) { if (!isPaused) { canCheck = false; pointerContainer.visible = false; if (CanPutPiece(currentPiece.shape, pointerX, pointerY, boardMatrix)) { InsertPiece(currentPiece, pointerX, pointerY); // Screen shake for feedback cameras.main.shake(100, 0.002); } else { // Return piece to original position gameObject.parentContainer.visible = true; optionsBools[parseInt(gameObject.parentContainer.name)] = true; } } }); ``` -------------------------------- ### Initialize BlockBlast Game with Options (JavaScript) Source: https://github.com/johnlikescarrot/blockblast/blob/main/AGENTS.md Demonstrates how to initialize the BlockBlast game using the global Parchados.run() API. It accepts various configuration options for customizing game behavior, including callbacks for game events, initial high score, and sponsor/season identifiers. The `onGameEnd` callback provides RSA-encrypted data for secure score submission. ```javascript // Basic game initialization window.Parchados.run(); // Advanced initialization with all options window.Parchados.run({ highScore: 50000, // Previous high score to display sponsor: true, // Enable sponsor branding seasonId: 12, // Season identifier for leaderboards gameId: 456, // Game instance identifier onGameStart: (evt) => { console.log('Game started:', evt); // evt contains: { state: 'game_start', name: 'blockblast' } }, onGameEnd: (encryptedData) => { // encryptedData is RSA-encrypted JSON containing score and IDs console.log('Game ended with encrypted payload'); fetch('/api/submit-score', { method: 'POST', body: JSON.stringify({ data: encryptedData }) }); }, onDataSend: (data) => { // Custom data handler for analytics console.log('Game data:', data); } }); ``` -------------------------------- ### Game Initialization API Source: https://github.com/johnlikescarrot/blockblast/blob/main/AGENTS.md The main entry point for running the BlockBlast game. It accepts configuration options and callbacks for customizing game behavior and integrating with external platforms. ```APIDOC ## Game Initialization API ### Description The main entry point for running the game. Accepts configuration options including callbacks for game events, initial high score, and sponsor/season identifiers for integration with external platforms. ### Method Global JavaScript function call ### Endpoint `window.Parchados.run(options)` ### Parameters #### Query Parameters None #### Request Body `options` (object) - Optional. An object containing configuration settings and callbacks. - **highScore** (number) - Optional - Previous high score to display. - **sponsor** (boolean) - Optional - Enable sponsor branding. - **seasonId** (number) - Optional - Season identifier for leaderboards. - **gameId** (number) - Optional - Game instance identifier. - **onGameStart** (function) - Optional - Callback function executed when the game starts. Receives an event object `{ state: 'game_start', name: 'blockblast' }`. - **onGameEnd** (function) - Optional - Callback function executed when the game ends. Receives RSA-encrypted JSON data containing score and IDs. - **onDataSend** (function) - Optional - Callback function for custom data handling, typically for analytics. Receives game data as an argument. ### Request Example ```javascript window.Parchados.run({ highScore: 50000, sponsor: true, seasonId: 12, gameId: 456, onGameStart: (evt) => { console.log('Game started:', evt); }, onGameEnd: (encryptedData) => { console.log('Game ended with encrypted payload'); fetch('/api/submit-score', { method: 'POST', body: JSON.stringify({ data: encryptedData }) }); }, onDataSend: (data) => { console.log('Game data:', data); } }); ``` ### Response This function does not return a value directly. It initializes and runs the game. #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### Game Initialization API Source: https://github.com/johnlikescarrot/blockblast/blob/main/README.md The main entry point for running the BlockBlast game. This API allows host applications to customize game behavior through configuration options and callbacks. ```APIDOC ## Game Initialization API ### Description The main entry point for running the game. Accepts configuration options including callbacks for game events, initial high score, and sponsor/season identifiers for integration with external platforms. ### Method Global JavaScript function call ### Endpoint `window.Parchados.run(options)` ### Parameters #### Query Parameters None #### Request Body `options` (object) - Optional configuration object. - **highScore** (number) - Optional - Previous high score to display. - **sponsor** (boolean) - Optional - Enable sponsor branding. - **seasonId** (number) - Optional - Season identifier for leaderboards. - **gameId** (number) - Optional - Game instance identifier. - **onGameStart** (function) - Optional - Callback function executed when the game starts. Receives an event object: `{ state: 'game_start', name: 'blockblast' }`. - **onGameEnd** (function) - Optional - Callback function executed when the game ends. Receives an RSA-encrypted JSON payload containing score and IDs. - **onDataSend** (function) - Optional - Callback function for custom data handling, typically for analytics. Receives game data. ### Request Example ```javascript window.Parchados.run({ highScore: 50000, sponsor: true, seasonId: 12, gameId: 456, onGameStart: (evt) => { console.log('Game started:', evt); }, onGameEnd: (encryptedData) => { console.log('Game ended with encrypted payload'); fetch('/api/submit-score', { method: 'POST', body: JSON.stringify({ data: encryptedData }) }); }, onDataSend: (data) => { console.log('Game data:', data); } }); ``` ### Response This function does not return a value directly. It initializes and runs the game. #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Configure Phaser 3 Game with Scenes and Plugins (JavaScript) Source: https://github.com/johnlikescarrot/blockblast/blob/main/AGENTS.md Sets up the Phaser 3 game instance with a specific configuration, including the game type, canvas dimensions, scaling mode, and a list of scenes to be loaded. It also integrates global and scene plugins like WebFontLoaderPlugin and UIPlugin for enhanced functionality. The game configuration includes metadata for high scores and event callbacks. ```javascript // Scene hierarchy and initialization order import { BootScene } from "./scripts/scenes/BootScene.js"; import { UIScene } from "./scripts/scenes/UIScene.js"; import { MenuScene } from "./scripts/scenes/MenuScene.js"; import { MainScene } from "./scripts/scenes/MainScene.js"; import WebFontLoaderPlugin from 'phaser3-rex-plugins/plugins/webfontloader-plugin.js'; import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js'; const gameOptions = { type: Phaser.AUTO, parent: 'phaser-div', width: 1080, height: 1080, scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH, }, scene: [BootScene, UIScene, MenuScene, MainScene], fps: { target: 60 }, plugins: { global: [{ key: 'rexWebFontLoader', plugin: WebFontLoaderPlugin, start: true }], scene: [{ key: 'rexUI', plugin: UIPlugin, mapping: 'rexUI' }] } }; const game = new Phaser.Game(gameOptions); game.config.metadata = { highScore: 0, sponsor: false, seasonId: 0, gameId: 0, onGameStart: () => {}, onGameEnd: () => {}, onDataSend: () => {} }; ``` -------------------------------- ### Configure Resource Paths for Development and Production (JavaScript) Source: https://github.com/johnlikescarrot/blockblast/blob/main/AGENTS.md A static utility class to manage asset paths, dynamically switching between development and production environments. It uses environment variables to determine the correct base path for loading images, atlases, and audio files. ```javascript import { ResourceLoader } from './scripts/components/resourceLoader.js'; // Configure resource loading const prodRoute = 'https://static.pchujoy.com/public/games-assets/parchados'; class ResourceLoader { static isProd = process.env.NODE_ENV === 'production'; static ReturnPath() { return this.isProd ? prodRoute : './src'; } static ReturnLocalePath(lang) { const safeLang = this.supportedLocales.has(lang) ? lang : 'en'; return `./scripts/locales/${safeLang}.json`; } } // Usage in asset loading this.load.image('table', ResourceLoader.ReturnPath() + '/images/parchados_chess.png'); this.load.atlas('piece', ResourceLoader.ReturnPath() + '/images/blockblast_piece/sprites.png', ResourceLoader.ReturnPath() + '/images/blockblast_piece/sprites.json' ); this.load.audio('mainTheme', [ ResourceLoader.ReturnPath() + '/audios/title.ogg', ResourceLoader.ReturnPath() + '/audios/title.m4a' ]); ``` -------------------------------- ### Initialize and Control Audio Manager in JavaScript Source: https://github.com/johnlikescarrot/blockblast/blob/main/AGENTS.md This code demonstrates the initialization and usage of the AudioManager class for handling background music and sound effects. It includes loading assets, setting volume, controlling playback, and playing specific sound effects. It requires the AudioManager class to be imported from './scripts/components/audioManager.js'. ```javascript import { AudioManager } from './scripts/components/audioManager.js'; // Initialize audio manager in UIScene const audioManager = new AudioManager(scene); audioManager.load(); audioManager.init(); // Available sound effects const sfxKeys = [ 'alarma', 'destruccion', 'preview', 'soltar', 'aviso', 'bomba', 'reduccion', 'puntos', 'tapete', 'ui_click', 'ui_page' ]; // Control audio playback audioManager.menuMusic.play(); audioManager.gameplayMusic.play(); audioManager.setAudioVolume(0.5); // 0 to 1 range audioManager.pauseMusic(); audioManager.resumeMusic(); // Play sound effect audioManager.bomba.play(); audioManager.destruccion.play(); ``` -------------------------------- ### Configure Phaser 3 Game Instance and Scenes (JavaScript) Source: https://context7.com/johnlikescarrot/blockblast/llms.txt Sets up the Phaser 3 game configuration, including canvas type, parent element, dimensions, scaling, and target FPS. It defines the order of scenes to be loaded: BootScene, UIScene, MenuScene, and MainScene. It also configures global and scene plugins, such as WebFontLoader and a UI plugin, and initializes game metadata. ```javascript import { BootScene } from "./scripts/scenes/BootScene.js"; import { UIScene } from "./scripts/scenes/UIScene.js"; import { MenuScene } from "./scripts/scenes/MenuScene.js"; import { MainScene } from "./scripts/scenes/MainScene.js"; import WebFontLoaderPlugin from 'phaser3-rex-plugins/plugins/webfontloader-plugin.js'; import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js'; const gameOptions = { type: Phaser.AUTO, parent: 'phaser-div', width: 1080, height: 1080, scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH, }, scene: [BootScene, UIScene, MenuScene, MainScene], fps: { target: 60 }, plugins: { global: [{ key: 'rexWebFontLoader', plugin: WebFontLoaderPlugin, start: true }], scene: [{ key: 'rexUI', plugin: UIPlugin, mapping: 'rexUI' }] } }; const game = new Phaser.Game(gameOptions); game.config.metadata = { highScore: 0, sponsor: false, seasonId: 0, gameId: 0, onGameStart: () => {}, onGameEnd: () => {}, onDataSend: () => {} }; ``` -------------------------------- ### Resource Loader Configuration in JavaScript Source: https://context7.com/johnlikescarrot/blockblast/llms.txt A static utility class for managing asset paths, adapting to development and production environments. It provides methods to return CDN paths for production assets and locale file paths. Dependencies include 'process.env' for environment detection. ```javascript import { ResourceLoader } from './scripts/components/resourceLoader.js'; // ResourceLoader automatically detects environment class ResourceLoader { static isProd = process.env.NODE_ENV === 'production'; static supportedLocales = new Set(['en', 'es']); static ReturnPath() { // Returns CDN route for production assets return 'https://static.pchujoy.com/public/games-assets/parchados'; } static ReturnLocalePath(lang) { const safeLang = this.supportedLocales.has(lang) ? lang : 'en'; return `./scripts/locales/${safeLang}.json`; } } // Usage in asset loading (BootScene/MainScene) this.load.image('table', ResourceLoader.ReturnPath() + '/images/parchados_chess.png'); this.load.atlas('piece', ResourceLoader.ReturnPath() + '/images/blockblast_piece/sprites.png', ResourceLoader.ReturnPath() + '/images/blockblast_piece/sprites.json' ); this.load.audio('mainTheme', [ ResourceLoader.ReturnPath() + '/audios/title.ogg', ResourceLoader.ReturnPath() + '/audios/title.m4a' ]); // Load locale files SUPPORTED_LOCALES.forEach(locale => { this.load.json(`locale_${locale}`, ResourceLoader.ReturnLocalePath(locale)); }); ``` -------------------------------- ### Manage UI Panels with Panel System in JavaScript Source: https://github.com/johnlikescarrot/blockblast/blob/main/AGENTS.md This snippet illustrates how to use the Panel class to create, show, and hide various UI elements such as pause menus, options, credits, score displays, and tutorials. It assumes the Panel class is imported from './scripts/components/panel.js' and requires a 'scene' context for initialization. ```javascript import { Panel } from './scripts/components/panel.js'; // Create and show UI panels const panel = new Panel(scene); panel.create(1080); panel.createPausePanel(1080); panel.createOptionsPanel(1080); panel.createCreditsPanel(1080); panel.createScorePanel(1080); panel.createInstructionsPanel(1080); // Show/hide panels panel.showPause(); panel.hidePause(); panel.showOptions(); panel.hideOptions(); panel.showCredits(); panel.hideCredits(); panel.showInstructions(() => { console.log('Tutorial closed'); }); panel.hideInstructions(); // Display game over score const finalScore = 150000; const highScore = 200000; panel.showScore(finalScore, highScore); panel.hideScore(); ``` -------------------------------- ### Initialize BlockBlast on DOM Load (JavaScript) Source: https://github.com/johnlikescarrot/blockblast/blob/main/index.html This snippet demonstrates how to initialize the BlockBlast application once the HTML document has been fully loaded and parsed. It attaches an event listener to the 'DOMContentLoaded' event, which then calls the 'run' method of the 'Parchados' object. No external dependencies are explicitly mentioned for this initialization step. ```javascript document.addEventListener("DOMContentLoaded", function () { window.Parchados.run(); }); ``` -------------------------------- ### Handle Drag and Drop Piece Placement (JavaScript) Source: https://github.com/johnlikescarrot/blockblast/blob/main/AGENTS.md Manages touch and mouse input for placing game pieces on the board. It provides visual feedback during dragging, checks for valid placement, and handles piece insertion or return to original position. ```javascript // Enable drag on piece containers scene.input.on('dragstart', function(pointer, gameObject) { if (!isPaused) { audioManager.preview.play(); gameObject.parentContainer.visible = false; currentPiece = optionsPieces[parseInt(gameObject.parentContainer.name)]; pointerContainer.visible = true; } }); scene.input.on('drag', (pointer, gameObject, dragX, dragY) => { if (!isPaused) { pointerContainer.x = pointer.worldX - 2 * squareSize; pointerContainer.y = pointer.worldY - 2 * squareSize; } }); scene.input.on('dragend', function(pointer, gameObject) { if (!isPaused) { pointerContainer.visible = false; if (CanPutPiece(currentPiece.shape, pointerX, pointerY, boardMatrix)) { InsertPiece(currentPiece, pointerX, pointerY); } else { // Return piece to original position gameObject.parentContainer.visible = true; } } }); ``` -------------------------------- ### Scene Management System Source: https://github.com/johnlikescarrot/blockblast/blob/main/AGENTS.md Details the Phaser scene hierarchy and initialization order used within the BlockBlast game, including the core scenes and plugin configurations. ```APIDOC ## Scene Management System ### Description The game uses Phaser's scene system with four main scenes that handle different game states: BootScene, UIScene, MenuScene, and MainScene. This section outlines the scene hierarchy and initialization order, along with the Phaser game configuration. ### Method Phaser Game Initialization ### Endpoint `new Phaser.Game(gameOptions)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body `gameOptions` (object) - Configuration object for the Phaser game instance. - **type** (number) - Phaser game type (e.g., `Phaser.AUTO`). - **parent** (string) - The ID of the HTML element to contain the game canvas. - **width** (number) - The width of the game canvas. - **height** (number) - The height of the game canvas. - **scale** (object) - Configuration for scaling the game. - **mode** (number) - Scaling mode (e.g., `Phaser.Scale.FIT`). - **autoCenter** (number) - Auto-centering mode (e.g., `Phaser.Scale.CENTER_BOTH`). - **scene** (array) - An array of scene classes to be included in the game, in initialization order. - **fps** (object) - Frames per second configuration. - **target** (number) - Target FPS. - **plugins** (object) - Configuration for Phaser plugins. - **global** (array) - Global plugins. - **key** (string) - Plugin key. - **plugin** (object) - Plugin class. - **start** (boolean) - Whether to start the plugin immediately. - **scene** (array) - Scene-specific plugins. - **key** (string) - Plugin key. - **plugin** (object) - Plugin class. - **mapping** (string) - Property name to access the plugin in the scene. ### Request Example ```javascript const gameOptions = { type: Phaser.AUTO, parent: 'phaser-div', width: 1080, height: 1080, scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH, }, scene: [BootScene, UIScene, MenuScene, MainScene], fps: { target: 60 }, plugins: { global: [{ key: 'rexWebFontLoader', plugin: WebFontLoaderPlugin, start: true }], scene: [{ key: 'rexUI', plugin: UIPlugin, mapping: 'rexUI' }] } }; const game = new Phaser.Game(gameOptions); game.config.metadata = { highScore: 0, sponsor: false, seasonId: 0, gameId: 0, onGameStart: () => {}, onGameEnd: () => {}, onDataSend: () => {} }; ``` ### Response This code initializes a Phaser game instance. The `game` object is returned, which can be used to interact with the game instance. #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### Internationalization (i18n) System in JavaScript Source: https://context7.com/johnlikescarrot/blockblast/llms.txt Manages multi-language support for the game, including initializing the i18n manager, setting language preferences, and translating text keys. It persists language choices to localStorage. Dependencies include './scripts/components/i18n.js'. ```javascript import { I18nManager, SUPPORTED_LOCALES } from './scripts/components/i18n.js'; // Supported languages console.log(SUPPORTED_LOCALES); // ["en", "es"] // Initialize i18n manager const i18n = new I18nManager(scene); i18n.init(); // Get current language console.log(i18n.language); // "en" or "es" // Set language (persisted to localStorage) i18n.setLanguage('es'); // Translate keys const pauseText = i18n.t('PAUSE'); // "PAUSA" in Spanish const scoreText = i18n.t('SCORE'); // "PUNTUACION" in Spanish const tutorialText = i18n.t('TUTORIAL'); // "TUTORIAL" const gameOverText = i18n.t('GAME_OVER'); // "FIN DE PARTIDA" in Spanish // Available translation keys const translationKeys = [ 'SCORE', 'PAUSE', 'OPTIONS', 'CREDITS', 'TUTORIAL', 'GAME_OVER', 'TIME', 'RECORD', 'MUSIC', 'SOUND', 'FULLSCREEN', 'LANGUAGE', 'RESTART', 'ARE_YOU_SURE_RESTART', 'PROGRAMMING', 'ART_ANIMATION', 'MARKETING_UI', 'MUSIC_SOUND', 'DIRECTION', 'EXECUTIVE_PRODUCER', 'TUTORIAL_PAGE_1_TEXT_1', 'TUTORIAL_PAGE_1_TEXT_2', 'TUTORIAL_PAGE_2_TEXT_1', 'TUTORIAL_PAGE_2_TEXT_2', 'TUTORIAL_PAGE_3_TEXT_1' ]; ``` -------------------------------- ### Implement Power-Up Logic in JavaScript Source: https://context7.com/johnlikescarrot/blockblast/llms.txt This snippet demonstrates the implementation of three power-up types: Bomb, Reducer, and Rotate. It includes functions for handling the bomb's area destruction, the reducer's piece conversion, and a utility to add random power-ups to pieces. Dependencies include the boardMatrix and piece data structures. ```javascript // Power-up types const powerUpsList = ["bomb", "reduct", "rotate"]; // Bomb power-up: destroys 3x3 area around activation point function BombBreakingLines(fila, columna, boardMatrix) { for (let i = -1; i <= 1; i++) { for (let j = -1; j <= 1; j++) { const nuevaFila = fila + i; const nuevaColumna = columna + j; if (nuevaFila >= 0 && nuevaFila < 8 && nuevaColumna >= 0 && nuevaColumna < 8) { if (!(i === 0 && j === 0)) { // Skip center boardMatrix[nuevaFila][nuevaColumna] = 0; } } } } } // Reducer power-up: convert remaining pieces to 1x1 squares function ConverterPowerUp(optionsBools, optionsPieces) { const singleSquareShape = "0000000000001000000000000"; for (let k = 0; k < 3; k++) { if (optionsBools[k]) { optionsPieces[k] = { color: optionsPieces[k].color, shape: singleSquareShape }; } } } // Convert piece to include random power-up function convertirPowerUp(shape) { let array = shape.split(''); let posiciones_1 = array.map((c, i) => c !== '0' ? i : -1).filter(i => i >= 0); if (posiciones_1.length === 0) return shape; let posicion_aleatoria = posiciones_1[Math.floor(Math.random() * posiciones_1.length)]; let powerUpType = Math.floor(Math.random() * 2) + 1; // 1=bomb, 2=reduct array[posicion_aleatoria] = powerUpType; return array.join(''); } ``` -------------------------------- ### Scene Management System Source: https://github.com/johnlikescarrot/blockblast/blob/main/README.md Overview of the Phaser 3 scene management system used in BlockBlast, detailing the main scenes and their roles in the game's lifecycle. ```APIDOC ## Scene Management System ### Description The game utilizes Phaser's scene system, comprising four primary scenes that manage different aspects of the game state and user experience. ### Method Phaser Game Configuration ### Endpoint N/A (Internal game structure) ### Parameters N/A ### Request Example ```javascript const gameOptions = { type: Phaser.AUTO, parent: 'phaser-div', width: 1080, height: 1080, scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH, }, scene: [ "./scripts/scenes/BootScene.js", "./scripts/scenes/UIScene.js", "./scripts/scenes/MenuScene.js", "./scripts/scenes/MainScene.js" ], fps: { target: 60 }, plugins: { global: [{ key: 'rexWebFontLoader', plugin: WebFontLoaderPlugin, start: true }], scene: [{ key: 'rexUI', plugin: UIPlugin, mapping: 'rexUI' }] } }; const game = new Phaser.Game(gameOptions); ``` ### Response N/A #### Success Response (200) N/A #### Response Example N/A ### Scenes Overview - **BootScene**: Responsible for loading initial game assets. - **UIScene**: Manages the game's user interface overlays and audio settings. - **MenuScene**: Presents the main menu to the player. - **MainScene**: Contains the core gameplay logic and mechanics. ``` -------------------------------- ### Timer System Implementation in JavaScript Source: https://context7.com/johnlikescarrot/blockblast/llms.txt Implements a time-based gameplay mechanic where the available time decreases each turn, increasing difficulty. It utilizes a UI slider for visual feedback and tweens for the countdown animation, with a game over trigger upon time expiration. Dependencies include a scene object with rexUI and tweens plugins, and an audioManager. ```javascript // Timer configuration const minTimePerTurn = 5; // Minimum seconds per turn const maxTimePerTurn = 25; // Starting seconds per turn // Create timer slider using rexUI plugin const timeSlider = scene.rexUI.add.slider({ x: centerX, y: centerY, width: 700, height: 50, orientation: 'x', value: 1, track: scene.add.sprite(0, 0, 'timerBar', 'Delineado cronometro.png'), indicator: scene.add.sprite(0, 0, 'timerBar', 'verde.png'), thumb: scene.add.sprite(0, 0, 'timerBar', 'Reloj.png'), input: 'none' }).layout(); // Animate timer countdown const sliderTween = scene.tweens.add({ targets: timeSlider, duration: maxTimePerTurn * 1000, value: { getStart: () => 1, getEnd: () => 0 }, onUpdate: (tween, target) => { let value = target.value; let indicator = target.getElement('indicator'); // Update indicator width let indicatorWidth = value * 600; indicator.resize(indicatorWidth, 40); if (value <= 0.3) { // Flash warning colors indicator.setFrame('rojo.png'); audioManager.alarma.play(); } }, onComplete: () => { console.log('Time expired!'); StartGameOver(); } }); ``` -------------------------------- ### Implement Time-Based Gameplay Mechanic (JavaScript) Source: https://github.com/johnlikescarrot/blockblast/blob/main/README.md A timer system that decreases available time per turn, increasing game difficulty. It utilizes a UI slider for visual feedback and tweens for animation. Dependencies include a 'scene' object with 'rexUI' and 'tweens' plugins, an 'audioManager', and a 'StartGameOver' function. The timer has configurable minimum and maximum durations per turn. ```javascript // Timer configuration const minTimePerTurn = 5; // Minimum seconds per turn const maxTimePerTurn = 25; // Starting seconds per turn // Create timer slider using rexUI plugin const timeSlider = scene.rexUI.add.slider({ x: centerX, y: centerY, width: 700, height: 50, orientation: 'x', value: 1, track: scene.add.sprite(0, 0, 'timerBar', 'Delineado cronometro.png'), indicator: scene.add.sprite(0, 0, 'timerBar', 'verde.png'), thumb: scene.add.sprite(0, 0, 'timerBar', 'Reloj.png'), input: 'none' }).layout(); // Animate timer countdown const sliderTween = scene.tweens.add({ targets: timeSlider, duration: maxTimePerTurn * 1000, value: { getStart: () => 1, getEnd: () => 0 }, onUpdate: (tween, target) => { let value = target.value; if (value <= 0.3) { // Flash warning colors target.getElement('indicator').setFrame('rojo.png'); audioManager.alarma.play(); } }, onComplete: () => { console.log('Time expired!'); StartGameOver(); } }); ``` -------------------------------- ### Implement Bomb and Reducer Power-ups in JavaScript Source: https://github.com/johnlikescarrot/blockblast/blob/main/AGENTS.md This snippet demonstrates the implementation of 'Bomb' and 'Reducer' power-ups within the game. The Bomb power-up destroys a 3x3 area, while the Reducer power-up converts pieces into 1x1 squares. It assumes a game board represented by a 2D array. ```javascript const powerUpsList = ["bomb", "reduct", "rotate"]; // Bomb power-up: destroys 3x3 area around activation point function BombBreakingLines(fila, columna, boardMatrix) { for (let i = -1; i <= 1; i++) { for (let j = -1; j <= 1; j++) { const nuevaFila = fila + i; const nuevaColumna = columna + j; if (nuevaFila >= 0 && nuevaFila < 8 && nuevaColumna >= 0 && nuevaColumna < 8) { if (!(i === 0 && j === 0)) { // Skip center boardMatrix[nuevaFila][nuevaColumna] = 0; } } } } } // Reducer power-up: convert remaining pieces to 1x1 squares function ConverterPowerUp(optionsBools, optionsPieces) { const singleSquareShape = "0000000000001000000000000"; for (let k = 0; k < 3; k++) { if (optionsBools[k]) { optionsPieces[k] = { color: optionsPieces[k].color, shape: singleSquareShape }; } } } ``` -------------------------------- ### Calculate Combo Bonus for Cleared Lines Source: https://context7.com/johnlikescarrot/blockblast/llms.txt Calculates a combo bonus based on the number of lines cleared simultaneously. It uses the triangular number formula to determine the bonus, with a multiplier of 1000. ```javascript // Calculate combo bonus (triangular number formula) function CalculateComboBonus(linesCleared) { let bonus = 0; for (let i = 1; i <= linesCleared; i++) { bonus += i; } return bonus * 1000; // 1 line = 1000, 2 lines = 3000, 3 lines = 6000 } // Example usage const lines = [0, 3, 10]; // Row 0, Row 3, Column 2 (10-8=2) const comboBonus = CalculateComboBonus(3); // Returns 6000 ``` -------------------------------- ### Calculate Combo Bonus for Cleared Lines - JavaScript Source: https://github.com/johnlikescarrot/blockblast/blob/main/README.md Calculates a bonus score based on the number of lines cleared simultaneously. The bonus increases exponentially with each additional line cleared, encouraging players to set up multi-line clears for higher scores. ```javascript // Calculate combo bonus function CalculateComboBonus(linesCleared) { let bonus = 0; for (let i = 1; i <= linesCleared; i++) { bonus += i; } return bonus * 1000; // 1 line = 1000, 2 lines = 3000, 3 lines = 6000, etc. } // Example: clearing 3 lines simultaneously const lines = [0, 3, 10]; // Row 0, Row 3, Column 2 (10-8=2) const comboBonus = CalculateComboBonus(3); // Returns 6000 ``` -------------------------------- ### Detect and Clear Lines with Combo Bonus (JavaScript) Source: https://github.com/johnlikescarrot/blockblast/blob/main/AGENTS.md Identifies completed rows and columns on the game board after a piece is placed. It calculates a combo bonus based on the number of lines cleared simultaneously, awarding points for each cleared line. ```javascript // Check for complete lines after piece placement function ShowBreakingLines(boardSize, lineCounterX, lineCounterY, lineCounterXadd, lineCounterYadd) { const linesToClear = []; for (let i = 0; i < boardSize; i++) { // Check horizontal lines if (lineCounterXadd[i] + lineCounterX[i] === boardSize) { linesToClear.push(i); } // Check vertical lines (offset by 8 to distinguish) if (lineCounterYadd[i] + lineCounterY[i] === boardSize) { linesToClear.push(i + 8); } } return linesToClear; } // Calculate combo bonus function CalculateComboBonus(linesCleared) { let bonus = 0; for (let i = 1; i <= linesCleared; i++) { bonus += i; } return bonus * 1000; // 1 line = 1000, 2 lines = 3000, 3 lines = 6000, etc. } // Example: clearing 3 lines simultaneously const lines = [0, 3, 10]; // Row 0, Row 3, Column 2 (10-8=2) const comboBonus = CalculateComboBonus(3); // Returns 6000 ``` -------------------------------- ### Implement Countdown Timer with Visual Feedback (JavaScript) Source: https://github.com/johnlikescarrot/blockblast/blob/main/AGENTS.md A time-based gameplay mechanic that decreases available time as the game progresses. It uses a UI slider to visualize the countdown and changes indicator color to warn players as time runs out, triggering a game over sequence upon completion. ```javascript // Timer configuration const minTimePerTurn = 5; const maxTimePerTurn = 25; // Create timer slider using rexUI plugin const timeSlider = scene.rexUI.add.slider({ x: centerX, y: centerY, width: 700, height: 50, orientation: 'x', value: 1, track: scene.add.sprite(0, 0, 'timerBar', 'Delineado cronometro.png'), indicator: scene.add.sprite(0, 0, 'timerBar', 'verde.png'), thumb: scene.add.sprite(0, 0, 'timerBar', 'Reloj.png'), input: 'none' }).layout(); // Animate timer countdown const sliderTween = scene.tweens.add({ targets: timeSlider, duration: maxTimePerTurn * 1000, value: { getStart: () => 1, getEnd: () => 0 }, onUpdate: (tween, target) => { let value = target.value; if (value <= 0.3) { // Flash warning colors target.getElement('indicator').setFrame('rojo.png'); audioManager.alarma.play(); } }, onComplete: () => { console.log('Time expired!'); StartGameOver(); } }); ``` -------------------------------- ### Generate Random Tetromino Piece with Color (JavaScript) Source: https://github.com/johnlikescarrot/blockblast/blob/main/AGENTS.md Generates a random tetromino-style piece from a predefined list of shapes. Each piece is represented as a 5x5 binary string. The function assigns a random color to the piece, modifying the shape string to reflect the chosen color. ```javascript // Piece shape definitions (5x5 grid as 25-character string) const piecesList = [ "0010000100001000010000100", // Vertical line (5 blocks) "0000000100001000010000000", // Vertical line (3 blocks) "0000000000111110000000000", // Horizontal line (5 blocks) "0000001110011100111000000", // 3x3 square "0000001100011000000000000", // 2x2 square "0000000100011100000000000", // T-shape inverted "0000001000010000110000000", // L-shape "0000001000010000110000000", // S-shape "0000001000010000111000000", // Large L-shape ]; // Generate a random piece with random color function GeneratePiece() { const colorsList = [ "blockblast_piece_shadow.png", "blockblast_piece_a.png", "blockblast_piece_b.png", "blockblast_piece_c.png", // ... up to 14 colors ]; const randomShape = piecesList[Math.floor(Math.random() * piecesList.length)]; const randomColorIndex = Math.floor(Math.random() * (colorsList.length - 1)) + 1; const colorChar = String.fromCharCode(97 + randomColorIndex); // Replace '1' with color character let coloredShape = ""; for (let i = 0; i < 25; i++) { coloredShape += randomShape[i] === "1" ? colorChar : "0"; } return { color: colorsList[randomColorIndex], shape: coloredShape }; } ``` -------------------------------- ### Insert Piece onto Board and Update State - JavaScript Source: https://github.com/johnlikescarrot/blockblast/blob/main/README.md Places a validated piece onto the game board at the specified coordinates. This function updates the board matrix, increments line counters for rows and columns, and calculates the score awarded for placing the piece. ```javascript // Place piece on board and update state function InsertPiece(piece, x, y) { let scorePoints = 0; for (let i = 0; i < 5; i++) { for (let j = 0; j < 5; j++) { if (piece.shape.charAt((5 * i) + j) !== '0') { boardMatrix[j + x][i + y] = 1; lineCounterX[i + y] += 1; lineCounterY[j + x] += 1; scorePoints += 10; } } } return scorePoints; } ``` -------------------------------- ### Detect and Clear Complete Lines - JavaScript Source: https://github.com/johnlikescarrot/blockblast/blob/main/README.md Identifies completed rows and columns on the game board after a piece has been placed. It uses line counters to determine which lines are full and returns a list of lines to be cleared. This system is crucial for scoring and game progression. ```javascript // Check for complete lines after piece placement function ShowBreakingLines(boardSize, lineCounterX, lineCounterY, lineCounterXadd, lineCounterYadd) { const linesToClear = []; for (let i = 0; i < boardSize; i++) { // Check horizontal lines if (lineCounterXadd[i] + lineCounterX[i] === boardSize) { linesToClear.push(i); } // Check vertical lines (offset by 8 to distinguish) if (lineCounterYadd[i] + lineCounterY[i] === boardSize) { linesToClear.push(i + 8); } } return linesToClear; } ``` -------------------------------- ### Validate Piece Placement on Board (JavaScript) Source: https://github.com/johnlikescarrot/blockblast/blob/main/AGENTS.md Checks if a given tetromino piece can be placed at a specific (x, y) coordinate on the 8x8 game board. It verifies that the piece stays within the board boundaries and does not overlap with any existing pieces. ```javascript // Check if piece can be placed at position (x, y) function CanPutPiece(pieceShape, x, y, boardMatrix) { const PIECE_DIMENSION = 5; for (let i = 0; i < PIECE_DIMENSION; i++) { for (let j = 0; j < PIECE_DIMENSION; j++) { if (pieceShape.charAt((PIECE_DIMENSION * i) + j) !== '0') { // Check bounds if (i + y > boardMatrix.length - 1 || j + x > boardMatrix[0].length - 1 || i + y < 0 || j + x < 0) { return false; } // Check collision with existing pieces if (boardMatrix[j + x][i + y] !== 0) { return false; } } } } return true; } // Place piece on board and update state function InsertPiece(piece, x, y) { let scorePoints = 0; for (let i = 0; i < 5; i++) { for (let j = 0; j < 5; j++) { if (piece.shape.charAt((5 * i) + j) !== '0') { boardMatrix[j + x][i + y] = 1; lineCounterX[i + y] += 1; lineCounterY[j + x] += 1; scorePoints += 10; } } } return scorePoints; } ``` -------------------------------- ### Validate Piece Placement on Board - JavaScript Source: https://github.com/johnlikescarrot/blockblast/blob/main/README.md Checks if a given tetromino piece can be placed at a specific (x, y) coordinate on the 8x8 game board. It verifies that the piece stays within the board boundaries and does not overlap with any existing pieces. ```javascript // Check if piece can be placed at position (x, y) function CanPutPiece(pieceShape, x, y, boardMatrix) { const PIECE_DIMENSION = 5; for (let i = 0; i < PIECE_DIMENSION; i++) { for (let j = 0; j < PIECE_DIMENSION; j++) { if (pieceShape.charAt((PIECE_DIMENSION * i) + j) !== '0') { // Check bounds if (i + y > boardMatrix.length - 1 || j + x > boardMatrix[0].length - 1 || i + y < 0 || j + x < 0) { return false; } // Check collision with existing pieces if (boardMatrix[j + x][i + y] !== 0) { return false; } } } } return true; } ```