MZ Plugin help wih center align custom windows

Long time reader, first time caller.
I have the following plugin to create a sort of "Opponent Select" screen.


JavaScript:
/*:
 * @target MZ
 * @plugindesc Custom Choices with Extra Windows Plugin
 * @help This plugin allows you to create custom choice windows with extra windows that display variable values.
 *
 * @param Choices
 * @type text[]
 * @desc List of choices to display.
 * @default ["Choice 1", "Choice 2", "Choice 3"]
 *
 * @param Columns
 * @type number
 * @min 1
 * @desc Number of columns in the choice window.
 * @default 8
 *
 * @param Window Width
 * @type number
 * @desc Width of the choice window.
 * @default 600
 *
 * @param Window Height
 * @type number
 * @desc Height of the choice window.
 * @default 350
 *
 * @param Transparent Alpha
 * @type number
 * @min 0
 * @max 255
 * @desc Alpha value for transparent choices (0-255).
 * @default 128
 *
 * @param Text Opacity
 * @type number
 * @min 0
 * @max 255
 * @desc Opacity of the choice name text (0-255).
 * @default 255
 *
 * @param ExtraWindows
 * @type struct<ExtraWindow>[]
 * @desc List of extra windows to display.
 * @default []
 */

/*~struct~ExtraWindow:
 * @param x
 * @type number
 * @desc X position of the extra window.
 * @default 0
 *
 * @param y
 * @type number
 * @desc Y position of the extra window.
 * @default 0
 *
 * @param width
 * @type number
 * @desc Width of the extra window.
 * @default 200
 *
 * @param height
 * @type number
 * @desc Height of the extra window.
 * @default 100
 *
 * @param content
 * @type string
 * @desc Content to display in the extra window.
 * @default "Attack: \\V[605]"
 *
 * @param opacity
 * @type number
 * @min 0
 * @max 255
 * @desc Opacity level of the extra window (0-255).
 * @default 255
 */

(() => {
    const parameters = PluginManager.parameters('CustomChoices');
    let choices = JSON.parse(parameters['Choices']);
    const columns = Number(parameters['Columns'] || 8);
    const windowWidth = Number(parameters['Window Width'] || 600);
    const windowHeight = Number(parameters['Window Height'] || 350);
    const transparentAlpha = Number(parameters['Transparent Alpha'] || 128); // Default to semi-transparent
    const extraWindows = JSON.parse(parameters['ExtraWindows'] || '[]').map(e => JSON.parse(e));

    // Extend the Window_Command to create a custom choice window
    class Window_CustomChoices extends Window_Command {
        initialize(rect) {
            super.initialize(rect);
            this._lastVariable899Value = $gameVariables.value(899);
            this.setupVariableChangeListener();
            this._extraWindows = []; // Initialize _extraWindows array
            this.openness = 0;
            this.deactivate();
        }

        setupVariableChangeListener() {
            $gameVariables.onChange(899, this.onVariable899Change.bind(this));
        }

        onVariable899Change(newValue) {
            if (newValue !== this._lastVariable899Value) {
                this._lastVariable899Value = newValue;
                console.log(`Variable 899 changed to: ${newValue}`);

                // Update enemy stats and log their values
                if (this.updateEnemyStats()) {
                    console.log("Enemy stats updated.");
                }

                if (this.logEnemyStats()) {
                    console.log("Enemy stats logged.");
                }

                if (this.refreshExtraWindows()) {
                    console.log("Extra windows refreshed.");
                }
            }
        }

        logEnemyStats() {
            console.log(`Variable 605 (Attack): ${$gameVariables.value(605)}`);
            console.log(`Variable 606 (Defense): ${$gameVariables.value(606)}`);
            console.log(`Variable 607 (Agility): ${$gameVariables.value(607)}`);
            console.log(`Variable 608 (Magic Attack): ${$gameVariables.value(608)}`);
            console.log(`Variable 609 (Magic Defense): ${$gameVariables.value(609)}`);
            console.log(`Variable 848 (Enemy Name): ${$gameVariables.value(848)}`);
        }

        refreshExtraWindows() {
            if (this._extraWindows) { // Check if _extraWindows is defined
                this._extraWindows.forEach(window => {
                    window.refreshContent();
                });
                return true; // Indicate that extra windows were refreshed
            } else {
                console.log("_extraWindows is not defined.");
                return false; // Indicate that no extra windows were refreshed
            }
        }

        makeCommandList() {
            choices.forEach((choice, index) => {
                if (choice.trim() === '\\blocksquare') {
                    this.addCommand(' ', 'choice', false); // Add a non-selectable space
                } else {
                    this.addCommand(choice, 'choice', true, index + 1); // Add selectable choices
                }
            });
        }

        maxCols() {
            return columns;
        }

        windowWidth() {
            return windowWidth;
        }

        windowHeight() {
            return windowHeight;
        }
itemRect(index) {
    const rect = super.itemRect(index);
    const commandName = this.commandName(index);

    // Increase height by 5 pixels to create a gap
    rect.height += 48;

    const col = index % this.maxCols(); // Calculate column index
    const row = Math.floor(index / this.maxCols()); // Calculate row index

    // Calculate the width of each item box based on the number of columns
    const itemWidth = Math.floor(this.contents.width / this.maxCols());

    // Calculate x and y positions
    rect.x = col * itemWidth; // Adjust horizontal spacing as needed (here, 12 pixels between columns)
    rect.y = row * rect.height; // Create 5-pixel gap between rows

    // Set the width of the item box to be the same as calculated item width
    rect.width = itemWidth;

    if (commandName === ' ') {
        return new Rectangle(rect.x, rect.y, 0, 0); // Make "\blocksquare" choice transparent
    }

    return rect;
}


drawItem(index) {
    const rect = this.itemRect(index);
    const commandName = this.commandName(index);
    this.resetTextColor();
    this.changePaintOpacity(this.isCommandEnabled(index));

    if (commandName !== null) {
        if (commandName === ' ') {
            const alpha = transparentAlpha / 255;
            const color = 'rgba(0, 0, 0, ' + alpha + ')';
            this.contents.fillRect(rect.x, rect.y, rect.width, rect.height, color);
        } else {
            const faceFilename = `${index}`; // Adjust based on your naming convention

            const faceBitmap = ImageManager.loadBitmap('img/pictures/select/faces/', faceFilename, 0, true);

            if (faceBitmap.isReady()) {
                // Calculate the scaling factor to fit the picture width to the rect width
                const scaleX = rect.width / faceBitmap.width;
                const scaledWidth = rect.width;
                const scaledHeight = faceBitmap.height * scaleX;
                const pictureX = rect.x;
                const pictureY = rect.y;

                this.contents.blt(faceBitmap, 0, 0, faceBitmap.width, faceBitmap.height, pictureX, pictureY, scaledWidth, scaledHeight);

                // Draw choice text
                const textHeight = this.lineHeight();
                const text = commandName;
                const textWidth = this.textWidth(text);
                const offsetX = (rect.width - textWidth) / 2;
                const offsetY = rect.y + scaledHeight + 5; // Offset to position below the image
                
                // Set text opacity
                const textOpacity = parameters['Text Opacity'] || 255;
                this.contents.paintOpacity = textOpacity;
                
                this.contents.drawText(text, rect.x + offsetX, offsetY, rect.width, textHeight, 'center');
                
                // Reset paint opacity
                this.contents.paintOpacity = 255;
            } else if (faceBitmap.isError()) {
                console.error(`Failed to load image for index ${index} (${faceFilename})`);
            } else {
                faceBitmap.addLoadListener(() => {
                    if (faceBitmap.isError()) {
                        console.error(`Failed to load image for index ${index} (${faceFilename})`);
                    } else {
                        // Calculate the scaling factor to fit the picture width to the rect width
                        const scaleX = rect.width / faceBitmap.width;
                        const scaledWidth = rect.width;
                        const scaledHeight = faceBitmap.height * scaleX;
                        const pictureX = rect.x;
                        const pictureY = rect.y;

                        this.contents.blt(faceBitmap, 0, 0, faceBitmap.width, faceBitmap.height, pictureX, pictureY, scaledWidth, scaledHeight);

                        // Draw choice text
                        const textHeight = this.lineHeight();
                        const text = commandName;
                        const textWidth = this.textWidth(text);
                        const offsetX = (rect.width - textWidth) / 2;
                        const offsetY = rect.y + scaledHeight + 5; // Offset to position below the image

                        // Set text opacity
                        const textOpacity = parameters['Text Opacity'] || 255;
                        this.contents.paintOpacity = textOpacity;
                        
                        this.contents.drawText(text, rect.x + offsetX, offsetY, rect.width, textHeight, 'center');
                        
                        // Reset paint opacity
                        this.contents.paintOpacity = 255;
                    }
                });
            }
        }
    }
}


        // Override select method to update variable 899
        select(index) {
            super.select(index);
            $gameVariables.setValue(899, index);
            console.log(`Variable 899 set to: ${index}`);
            this.updateEnemyStats(); // Update enemy stats when choice is selected
            this.refreshExtraWindows();
            SceneManager._scene.updatePictures(); // Update the pictures
        }

        updateEnemyStats() {
            const selectedIndex = $gameVariables.value(899); // Get selected index
            if (selectedIndex > 0) {
                const choiceName = choices[selectedIndex].trim(); // Adjust for zero-based index
                const enemy = this.findEnemyByName(choiceName); // Find enemy by name

                if (enemy) {
                    $gameVariables.setValue(605, enemy.params[2]); // Attack stat
                    $gameVariables.setValue(606, enemy.params[3]); // Defense stat
                    $gameVariables.setValue(607, enemy.params[6]); // Agility stat
                    $gameVariables.setValue(608, enemy.params[4]); // Magic attack stat
                    $gameVariables.setValue(609, enemy.params[5]); // Magic defense stat
            $gameVariables.setValue(848, enemy.name); // Enemy name
                    console.log(`Variable 605 (Attack): ${$gameVariables.value(605)}`);
                    console.log(`Variable 606 (Defense): ${$gameVariables.value(606)}`);
                    console.log(`Variable 607 (Agility): ${$gameVariables.value(607)}`);
                    console.log(`Variable 608 (Magic Attack): ${$gameVariables.value(608)}`);
                    console.log(`Variable 609 (Magic Defense): ${$gameVariables.value(609)}`);
            console.log(`Variable 848 (Enemy Name): ${$gameVariables.value(848)}`);
                } else {
                    console.log(`Enemy with name '${choiceName}' not found.`);
                }
            }
        }

        findEnemyByName(name) {
            const enemies = $dataEnemies;
            for (let i = 1; i < enemies.length; i++) {
                const enemy = enemies[i];
                if (enemy && enemy.name === name) {
                    return enemy;
                }
            }
            return null;
        }

        // Override cursorRight to skip over non-selectable items
        cursorRight(wrap) {
            const index = this.index();
            let newIndex = index;
            do {
                newIndex++;
                if (newIndex >= this.maxItems()) {
                    if (wrap) {
                        newIndex = 0;
                    } else {
                        newIndex = index;
                        break;
                    }
                }
            } while (!this.isCommandEnabled(newIndex));
            this.select(newIndex);
        }

        // Override cursorLeft to skip over non-selectable items
        cursorLeft(wrap) {
            const index = this.index();
            let newIndex = index;
            do {
                newIndex--;
                if (newIndex < 0) {
                    if (wrap) {
                        newIndex = this.maxItems() - 1;
                    } else {
                        newIndex = index;
                        break;
                    }
                }
            } while (!this.isCommandEnabled(newIndex));
            this.select(newIndex);
        }

        // Override cursorDown to skip over non-selectable items
        cursorDown(wrap) {
            const index = this.index();
            let newIndex = index;
            do {
                newIndex += this.maxCols();
                if (newIndex >= this.maxItems()) {
                    if (wrap) {
                        newIndex %= this.maxItems();
                    } else {
                        newIndex = index;
                        break;
                    }
                }
            } while (!this.isCommandEnabled(newIndex));
            this.select(newIndex);
        }

        // Override cursorUp to skip over non-selectable items
        cursorUp(wrap) {
            const index = this.index();
            let newIndex = index;
            do {
                newIndex -= this.maxCols();
                if (newIndex < 0) {
                    if (wrap) {
                        newIndex += this.maxItems();
                    } else {
                        newIndex = index;
                        break;
                    }
                }
            } while (!this.isCommandEnabled(newIndex));
            this.select(newIndex);
        }
    }


class Window_Extra extends Window_Base {
    initialize(rect, content) {
        super.initialize(rect);
        this._content = content;
        this.refreshContent(); // Initial content refresh
    }

    refreshContent() {
        this.contents.clear(); // Clear previous contents before drawing new content

        // Parse and convert the content
        const parsedContent = this.parseContent(this._content);
        const processedContent = this.convertEscapeCharacters(parsedContent);

        // Measure the width of the processed content text
        const textWidth = this.textWidthEx(processedContent);

        // Calculate the x-coordinate to center align the text based on the window width
        const centerX = (this.contents.width - textWidth) / 2;

        // Log centerX calculation to console
        console.log(`CenterX Calculation:
            Window Width: ${this.contents.width},
            Text Width: ${textWidth},
            CenterX: ${centerX}`);

        this.drawTextEx(processedContent, centerX, 0); // Use centerX for centering text
    }

    parseContent(content) {
        // Replace variable placeholders with their actual values
        return content.replace(/\\V\[(\d+)\]/gi, (_, varId) => {
            const value = $gameVariables.value(Number(varId));
            return value !== undefined ? String(value) : '';
        });
    }

    convertEscapeCharacters(text) {
        // Convert escape characters to their actual values
        text = text.replace(/\\/g, '\x1b');
        text = text.replace(/\x1b\x1b/g, '\\');
        text = text.replace(/\x1bV\[(\d+)\]/gi, (_, varId) => {
            const value = $gameVariables.value(Number(varId));
            return value !== undefined ? String(value) : '';
        });
        text = text.replace(/\x1bN\[(\d+)\]/gi, (_, actorId) => {
            const actor = $gameActors.actor(Number(actorId));
            return actor ? actor.name() : '';
        });
        text = text.replace(/\x1bP\[(\d+)\]/gi, (_, partyIndex) => {
            const actor = $gameParty.members()[Number(partyIndex) - 1];
            return actor ? actor.name() : '';
        });
        text = text.replace(/\x1bG/gi, TextManager.currencyUnit);
        // Add more escape code conversions if needed
        return text;
    }

    textWidthEx(text) {
        // Create a temporary Bitmap object to measure the text width
        const bitmap = new Bitmap();
        bitmap.fontFace = this.contents.fontFace;
        bitmap.fontSize = this.contents.fontSize;
        bitmap.fontBold = this.contents.fontBold;
        bitmap.fontItalic = this.contents.fontItalic;

        // Remove all escape codes for width measurement
        const cleanedText = text.replace(/\x1b\[\d+\]/g, '')
                                .replace(/\x1b[\{\}]/g, '')
                                .replace(/\x1b[A-Z]+\[\d*\]/gi, '')
                                .replace(/\x1b[A-Z]/gi, '');

        // Measure the width of the cleaned text
        const width = bitmap.measureTextWidth(cleanedText);

        // Log the text width for debugging
        console.log(`Measured text width: ${width} for text: ${cleanedText}`);

        return width;
    }
}




    // Add a new Scene to handle custom choices
    class Scene_CustomChoices extends Scene_MenuBase {
create() {
    super.create();


    // Create windows in the desired order
    const picturesWindow = this.createPictures(); // Bottom layer

    const nameplateWindow = this.createNameplate(); // Layer above pictures

    const extraWindowsWindow = this.createExtraWindows(); // Layer above nameplate

    const customChoicesWindow = this.createCustomChoicesWindow(); // Top layer

    // Add windows to the scene
    if (picturesWindow) this.addChild(picturesWindow);

    if (nameplateWindow) this.addChild(nameplateWindow);

    if (extraWindowsWindow) this.addChild(extraWindowsWindow);

    if (customChoicesWindow) this.addChild(customChoicesWindow);
}


        createBackground() {
            // Do not call super.createBackground to avoid dimming
            this._backgroundSprite = new Sprite();
            this._backgroundSprite.bitmap = SceneManager.backgroundBitmap();
            this.addChild(this._backgroundSprite);
        }

createPictures() {
    // Create window for picture 2 (swap with picture 1)
    const rect2 = this.picture2WindowRect();
    this._pictureWindow2 = new Window_Base(rect2);
    this.addChild(this._pictureWindow2);

    // Create window for picture 1 (swap with picture 2)
    const rect1 = this.picture1WindowRect();
    this._pictureWindow1 = new Window_Base(rect1);
    this.addChild(this._pictureWindow1);

    // Draw pictures with transparency
    this.drawPictureInWindow(null, this._pictureWindow2, true);
    this.drawPictureInWindow(null, this._pictureWindow1, true);

    // Update and position pictures within windows
    this.updatePictures();
    this.positionPictures();
}

updatePictures() {
    const variableValue = $gameVariables.value(899);

    // Determine variableMod based on the value of variableValue
    let variableMod;
    if ([2, 64].includes(variableValue)) {
        variableMod = "cpw1";
    } else if ([10, 23, 36, 52].includes(variableValue)) {
        variableMod = "cpw2";
    } else if ([7, 12, 13, 14, 16, 27, 40, 44, 54].includes(variableValue)) {
        variableMod = "cpw3";
    } else if ([20, 28, 37, 46, 50, 57].includes(variableValue)) {
        variableMod = "cpw4";
    } else if ([3, 9, 15, 35, 58].includes(variableValue)) {
        variableMod = "redacted";
    } else if ([4, 25, 34, 47, 51, 56].includes(variableValue)) {
        variableMod = "nats";
    } else if ([5, 22, 53, 55, 18].includes(variableValue)) {
        variableMod = "rcp";
    } else if ([6, 8, 33, 38, 39].includes(variableValue)) {
        variableMod = "unified1";
    } else if ([17, 24, 29, 41, 43, 49].includes(variableValue)) {
        variableMod = "unified2";
    } else if ([26, 42, 45, 30].includes(variableValue)) {
        variableMod = "gc1";
    } else if ([11, 21, 31, 32, 48, 59, 63, 65, 66].includes(variableValue)) {
        variableMod = "world";
    } else {
        variableMod = "cpw1"; // Fallback if no match
    }

    // File paths for the primary images
    const folderPath1 = 'img/pictures/select/';
    const filename1 = `${variableValue}`;
    const bitmap1 = ImageManager.loadBitmap(folderPath1, filename1, 0, true);

    const folderPath2 = 'img/pictures/select/';
    const filename2 = '0';
    const bitmap2 = ImageManager.loadBitmap(folderPath2, filename2, 0, true);

    // File paths for the secondary images (background images)
    const backgroundFolderPath1 = 'img/pictures/select/flags/L/';
    const backgroundFilename1 = 'cpw2';
    const backgroundBitmap1 = ImageManager.loadBitmap(backgroundFolderPath1, backgroundFilename1, 0, true);

    const backgroundFolderPath2 = 'img/pictures/select/flags/R/';
    const backgroundBitmap2 = ImageManager.loadBitmap(backgroundFolderPath2, variableMod, 0, true);

    // Handle bitmap loading and drawing for picture window 1
    bitmap1.addLoadListener(() => {
        if (bitmap1.isError()) {
            const defaultBitmap1 = ImageManager.loadBitmap(folderPath1, '0', 0, true);
            defaultBitmap1.addLoadListener(() => {
                backgroundBitmap2.addLoadListener(() => {
                    this.drawPictureInWindow(backgroundBitmap2, this._pictureWindow1, true);
                    this.drawPictureInWindow(defaultBitmap1, this._pictureWindow1, false);
                    this.positionPictures(); // Ensure positions are updated after loading
                });
            });
        } else {
            backgroundBitmap2.addLoadListener(() => {
                this.drawPictureInWindow(backgroundBitmap2, this._pictureWindow1, true);
                this.drawPictureInWindow(bitmap1, this._pictureWindow1, false);
                this.positionPictures(); // Ensure positions are updated after loading
            });
        }
    });

    // Handle bitmap loading and drawing for picture window 2
    bitmap2.addLoadListener(() => {
        backgroundBitmap1.addLoadListener(() => {
            this.drawPictureInWindow(backgroundBitmap1, this._pictureWindow2, true);
            this.drawPictureInWindow(bitmap2, this._pictureWindow2, false);
            this.positionPictures(); // Ensure positions are updated after loading
        });
    });
}

positionPictures() {
    const windowWidth = 720;
    const totalWidth = windowWidth * 2; // Two windows side by side

    if (this._pictureWindow2) {
        this._pictureWindow2.x = (Graphics.boxWidth - totalWidth) / 2;
        this._pictureWindow2.y = 40;
    }

    if (this._pictureWindow1) {
        this._pictureWindow1.x = this._pictureWindow2.x + windowWidth;
        this._pictureWindow1.y = 40;
    }
}

drawPictureInWindow(bitmap, window, isBackground) {
    if (window && bitmap) {
        if (isBackground) {
            // Clear the contents and draw the background image
            window.contents.clear();
        }
        window.opacity = 0;

        // Calculate new dimensions for 95% scaling
        const scaledWidth = bitmap.width * 0.95;
        const scaledHeight = bitmap.height * 0.95;

        // Calculate position to center the scaled bitmap within the window
        const offsetX = (window.contentsWidth() - scaledWidth) / 2;
        const offsetY = (window.contentsHeight() - scaledHeight) / 2;

        // Draw the bitmap with scaling and centered position
        window.contents.blt(bitmap, 0, 0, bitmap.width, bitmap.height, offsetX, offsetY, scaledWidth, scaledHeight);
    }
}

picture1WindowRect() {
    const windowWidth = 720;
    const windowHeight = 720;
    const wx = (Graphics.boxWidth - windowWidth * 2) / 2; // Center horizontally
    const wy = 40; // Fixed y position
    return new Rectangle(wx, wy, windowWidth, windowHeight);
}

picture2WindowRect() {
    const windowWidth = 720;
    const windowHeight = 720;
    const wx = (Graphics.boxWidth + windowWidth * 2) / 2; // Center horizontally
    const wy = 40; // Fixed y position
    return new Rectangle(wx, wy, windowWidth, windowHeight);
}



        createCustomChoicesWindow() {
            const rect = this.customChoicesWindowRect();
            this._customChoicesWindow = new Window_CustomChoices(rect);
            this._customChoicesWindow.setHandler('ok', this.onChoiceOk.bind(this));
            this._customChoicesWindow.setHandler('cancel', this.popScene.bind(this));
            this.addChild(this._customChoicesWindow);
            this._customChoicesWindow.open();
            this._customChoicesWindow.activate();

            // Initialize enemy stats based on initial selection if any
            this._customChoicesWindow.updateEnemyStats();
        }

        customChoicesWindowRect() {
            const wx = (Graphics.boxWidth - windowWidth) / 2;
            const wy = Graphics.boxHeight - windowHeight - 60; // Position at the bottom
            return new Rectangle(wx, wy, windowWidth, windowHeight);
        }

createNameplate() {
    const nameplateWidth = 1600;
    const nameplateHeight = 170;

    // Calculate the position for the nameplate window
    const nameplateX = Math.floor((Graphics.boxWidth - nameplateWidth) / 2);
    const nameplateY = this.customChoicesWindowRect().y - nameplateHeight - 10;

    // Create a new Window_Base for the nameplate
    const nameplateWindow = new Window_Base(new Rectangle(nameplateX, nameplateY, nameplateWidth, nameplateHeight));

    // Set opacity to 0 for full transparency
    nameplateWindow.opacity = 0;

    // Load the nameplate bitmap
    const bitmap = ImageManager.loadBitmap('img/pictures/select/', 'nameplate', 0, true);

    // When the bitmap finishes loading, draw it inside the nameplate window
    bitmap.addLoadListener(() => {
        nameplateWindow.contents.clear();

        // Determine scaling to fit the bitmap horizontally across the window
        const scaleX = (nameplateWidth - 20) / bitmap.width;
        const scaleY = nameplateHeight / bitmap.height;

        // We want to stretch the image to fit horizontally across the window
        const scaledWidth = nameplateWidth - 20;  // Full width minus some padding
        const scaledHeight = bitmap.height * scaleX;  // Adjust height proportionally

        // Center the bitmap vertically if it doesn't fit perfectly
        const offsetX = 10;  // Slight padding on the sides
        const offsetY = (nameplateHeight - scaledHeight) / 2;

        // Draw the bitmap with stretching and centered position
        nameplateWindow.contents.blt(bitmap, 0, 0, bitmap.width, bitmap.height, offsetX, offsetY, scaledWidth, scaledHeight);
    });

    // Add the nameplate window as a child to this scene or parent window
    this.addChild(nameplateWindow);

}




        createExtraWindows() {
            this._extraWindows = [];
            extraWindows.forEach((extraWindow) => {
                const rect = new Rectangle(
                    Number(extraWindow.x),
                    Number(extraWindow.y),
                    Number(extraWindow.width),
                    Number(extraWindow.height)
                );
                const window = new Window_Extra(rect, extraWindow.content); // Pass content to the window

        window.opacity = Number(extraWindow.opacity); // Set opacity from parameter

                window.refreshContent(); // Refresh content initially
                this._extraWindows.push(window); // Push the window instance into _extraWindows array
                this.addChild(window); // Add the window to the scene
            });
        }


        updateExtraWindows() {
            this._extraWindows.forEach(window => {

                window.refreshContent();
            });
        }

        onChoiceOk() {
            const index = this._customChoicesWindow.index();
            if (index >= 0 && choices[index].trim() !== '\\blocksquare') {
                $gameVariables.setValue(900, index + 1); // Store the choice index in variable 900
            }
            this.popScene();
        }

        update() {
            super.update();
            this.updateExtraWindows(); // Update extra windows on every frame
        }
    }

    // Plugin command to call the custom choice scene
    PluginManager.registerCommand('CustomChoices', 'ShowCustomChoices', () => {
        SceneManager.push(Scene_CustomChoices);
    });
})();

Functionally, it works perfectly. Except for some reason all the windows seem to be getting drawn slightly left of where they are supposed to, so nothing is quite aligned properly. On top of that, the pictures being drawn within the windows seem to be either not scaling properly, or drawing slightly to the right of where they are supposed to, as the right edges of them seem to be getting cut off (This picture issue, suprisingly, is not happening with the "ChoiceWindow". Only the window align issue is affecting the "ChoiceWindow")

I can't for the life of me figure out the issue. Admittedly, my javascript knowledge is limited to what I've been able to pick up from trial and error.

What am I missing?
My game's resolution is 1920x1056 if that helps. And all console logs seem to be coming back with the accurate data. I am not getting an errors or missing data in the console logs either.

Thanks in advance.
const wx = (Graphics.boxWidth - windowWidth * 2) / 2; // Center horizontally
What's the reason for that *2 in there? If you'd like to calculate the x coordinate that makes in centred, it should just be (Graphics.boxWidth - windowWidth) / 2.
When I work with aligments of all sort of things, I also got some problems like that. One thing that helped me figure out, was make sure all width, height, x, and y of everything was an integer number. 200, 300, 800 and not, 200.7, 353.017628346, etc...

A thing that I saw on your code is this:
1718916327631.png

Why 95% ? Maybe this is an issue?
Thanks for the replies.

The line "const wx = (Graphics.boxWidth - windowWidth * 2) / 2; // Center horizontally" from picture1WindowRect() goes along with the line " const wx = (Graphics.boxWidth + windowWidth * 2) / 2; // Center horizontally from picture2WindowRect() so those two are side by side centered horizontally.

I did have a look at this to double check however, and even removing the "*2" the windows still appeared just left of their supposed center alignment.

The lines:
// Calculate new dimensions for 95% scaling
const scaledWidth = bitmap.width * 0.95;
const scaledHeight = bitmap.height * 0.95;

Were done like that because putting it at 100 seems to be cutting of a bit from the right side of the pictures (*Those windows are 720x720, at 100% the pictures inside are 720x720).
This made me think it's a padding issue which brought me to...

I have sort of figure out a workaround but i'm worried it's gonna cause issues later down the line.

I now THINK it's some sort of padding issue, as my workaround involved basically adding "+8" to each window's individual x-values and it seems to have fixed it. But if that is the case, I'm unsure as to why there is padding to begin with, when:
a.) i've set default padding to "0" in my game.
b.) the windows are being drawn in a custom scene, so the x=values of the window should be defined by the edge of the GraphicsBox right?

I suppose you guys see it and experience all the time, but I am only recently learning how continously frustrating it is when you figure out all these elaborate code and functions and smash them out easy, only to get stuck on one tiny little thing like center alignment for what seems like an age.
Those windows are 720x720, at 100% the pictures inside are 720x720
The contents area of a window is smaller than the window itself. Are you perhaps adjusting the padding after the contents area has already been created? This would cause it to be smaller than intended.

And in general I'd recommend against dynamically scaling a picture like this, since it tends to look rather ugly. Just scale it in a graphics editor and render it at 100% in-game.

a.) i've set default padding to "0" in my game.
How exactly did you do that? I suspect whatever you've done here is slightly messing with things.

Just to confirm some things:
- If you draw a window at x=0, does its left edge touch the left edge of the screen?
- If you draw it at x=Graphics.width-windowWidth, does its right edge touch the right edge of the screen?

Original thread: https://forums.rpgmakerweb.com/threads/plugin-help-wih-center-align-custom-windows.169643/