Witch Bank [WIP]

Discussion and information relevant to creating special missions, new ships, skins etc.

Moderators: winston, another_commander

Post Reply
User avatar
Wildeblood
---- E L I T E ----
---- E L I T E ----
Posts: 2650
Joined: Sat Jun 11, 2011 6:07 am
Location: Nova Hollandia
Contact:

Witch Bank [WIP]

Post by Wildeblood »

This is what I've been doing the last few days while the BB has been offline. It's currently "broken", but only just. Four out of the five banking mission screens appear, and they function as expected. I feel like I'm getting close. Anyway, in case you never hear from me again, this is where I got up to. Ask phkb to finish it, if there's any desire for an add-on like this. If anyone wants to try it, you need to provide Images/"witch_bank_background.png" or there'll be an exception when it tries to create the mission screen.

Code: Select all

"use strict";

// worldScripts.WitchBank

this.name = "WitchBank";

    this.playerWillSaveGame = function () {
        if (this.WitchBank_transactionLog) {
            missionVariables.WitchBank_transactionLog = JSON.stringify(this.WitchBank_transactionLog);
        } else {
            delete missionVariables.WitchBank_transactionLog;
        }
    };

this._firstRun = function () {
    if (player.ship.awardEquipment("EQ_WB_WALLET")) {             // Dummy equipment to represent wallet
        missionVariables.WitchBank_cashAtBank = 0;                // Default starting value
        missionVariables.WitchBank_cashInWallet = player.credits; // Initial wallet balance equals total credits
    } else {
        log(this.name, "Error: EQ_WB_WALLET could not be awarded to player ship.");
    }
};

this.startUp = function () {
    if (!missionVariables.WitchBank_cashAtBank || 
        !missionVariables.WitchBank_cashInWallet) {
        this._firstRun();
    }
    // Initialize transaction log
    this.WitchBank_transactionLog = JSON.parse(missionVariables.WitchBank_transactionLog) || [];
    delete this.startUp;
};

/* ====================================================================================
		equipmentDamaged & equipmentRepaired for EQ_WB_WALLET

    The EQ_WB_WALLET equipment doesn't do anything, except exist.
    Damage probability and cost-to-repair can be set in equipment.plist
    and handled natively by Oolite.
======================================================================================= */

// The equipmentDamaged handler is called when equipment gets damaged.
this.equipmentDamaged = function (equipment) {
    if (equipment === "EQ_WB_WALLET") {
        player.credits = missionVariables.WitchBank_cashAtBank;
        missionVariables.WitchBank_trappedInDamagedWallet = missionVariables.WitchBank_cashInWallet;
        missionVariables.WitchBank_cashInWallet = 0;
        player.consoleMessage("Your wallet has been damaged. " + missionVariables.WitchBank_trappedInDamagedWallet + " credits are inaccessible.", 6);
        log(this.name, "Wallet damaged. Trapped credits: " + missionVariables.WitchBank_trappedInDamagedWallet);
    }
};

// The equipmentRepaired handler is called when equipment gets repaired.
this.equipmentRepaired = function (equipment) {
    if (equipment === "EQ_WB_WALLET") {
        if (missionVariables.WitchBank_trappedInDamagedWallet > 0) {
            missionVariables.WitchBank_cashInWallet = missionVariables.WitchBank_trappedInDamagedWallet;
            player.credits = missionVariables.WitchBank_cashAtBank + missionVariables.WitchBank_cashInWallet;
            player.consoleMessage("Your wallet has been repaired. " + missionVariables.WitchBank_cashInWallet + " credits are restored.", 6);
            missionVariables.WitchBank_trappedInDamagedWallet = 0;
            log(this.name, "Wallet repaired. Restored credits: " + missionVariables.WitchBank_cashInWallet);
        } else {
            player.consoleMessage("No trapped credits to restore.", 6);
        }
    }
};

/* ====================================================================================
            SETTING THE STATION INTERFACE
======================================================================================= */

this.startUpComplete = function () {
    if (player.ship.docked) {
        this._applyInterface(player.ship.dockedStation);
    }
    delete this.startUpComplete;
};

this.shipDockedWithStation = function (station) {
    this._applyInterface(station);
};

this._applyInterface = function (station) {
    if (station.isMainStation) {
        station.setInterface("witch_bank", {
            title: "Witch Bank",
            category: expandDescription("[interfaces-category-organisations]"),
            summary: "Witch Bank is the trusted name in interstellar banking. Current balance: " + missionVariables.WitchBank_cashAtBank + " credits.",
            callback: this._showBankingScreen.bind(this)
        });
    }
};

/* ====================================================================================
            SHOW BANKING SCREEN
======================================================================================= */

this._pendingTransaction = null; // "deposit", "auto_deposit" or "withdrawal" - anything else is ignored

this._showBankingScreen = function (caller, to) {
    // If _pendingTransaction is set, process the caller as an amount
    if (this._pendingTransaction) {
        // Check if caller is a positive integer
        var amount = parseInt(caller, 10);
        if (!isNaN(amount) && amount > 0) {
            // Process the transaction
            this._performTransaction(this._pendingTransaction, amount);

            // Reset the pending transaction flag
            this._pendingTransaction = null;

            // Update text on interfaces screen with new balance
            this._applyInterface(player.ship.dockedStation);
        } else {
            player.consoleMessage("Invalid amount entered.", 6);
            this._pendingTransaction = null; // Reset on invalid input
        }
    }

    // Compose the default starting screen message
    var message = "Welcome to Witch Bank, the trusted name in interstellar banking. Your current balances are: " +
                  missionVariables.WitchBank_cashAtBank + " credits in bank, " +
                  missionVariables.WitchBank_cashInWallet + " credits in wallet.\n\n" +
                  "Recent Transactions:\n" +
                  this._getTransactionLog();

    var optionsMenu = {
        "1_DEPOSIT": "Make a DEPOSIT",
        "2_WITHDRAWAL": "Make a WITHDRAWAL",
        "3_AUTOBANK": "AUTOBANK service",
        "4_blank": "",
        "9_EXIT": "EXIT secure banking"
    };

    var parameters = {
        screenID: "BANKING_SCREEN",
        allowInterrupt: true,
        exitScreen: "GUI_SCREEN_INTERFACES",
        background: { name: "witch_bank_background.png", height: 480 },
        title: "Witch Bank",
        message: message,
        choices: optionsMenu
    };

    if (to) {
        parameters.exitScreen = to;
    }

    // Adjust parameters for deposit/withdrawal screens
    switch (caller) {
        case "deposit":
            this._pendingTransaction = "deposit";
            parameters.music = "dt_anticipating_deposit.ogg";
            parameters.title = "Wallet to Witch Bank";
            parameters.message = "Enter the amount you wish to deposit:";
            parameters.textEntry = true; // Replaces "choices" menu with a text entry field
            break;

        case "withdrawal":
            this._pendingTransaction = "withdrawal";
            parameters.music = "dt_anticipating_withdrawal.ogg";
            parameters.title = "Witch Bank to Wallet";
            parameters.message = "Enter the amount you wish to withdraw:";
            parameters.textEntry = true; // Replaces "choices" menu with a text entry field
            break;

        case "autobank":
            parameters.music = "dt_automatic_banking.ogg";
            parameters.title = "Automatic Banking Service";
            parameters.message = "AutoBank is a convenient service that automatically deposits your trading profits into your bank account, ensuring your earnings are safely stored and ready to earn interest. By enabling AutoBank, you’ll no longer need to manually transfer credits after each trade—simply focus on maximizing your profits, and let us handle the rest. This service is perfect for traders who want to streamline their operations while taking full advantage of our interest-bearing accounts. Enable AutoBank today and experience hassle-free financial management!";
            parameters.choices = {
                "1_DEPOSIT": "Make a DEPOSIT",
                "2_WITHDRAWAL": "Make a WITHDRAWAL",
                "3_AUTOBANK_TOGGLE": "Toggle AUTOBANK on or off",
                "4_blank": "",
                "9_EXIT": "EXIT secure banking"
            };
            break;

        default:
            // No changes to the starting screen
            break;
    }

    // Run the banking screen
    mission.runScreen(parameters, this._handleBankingChoice.bind(this));
};

/* ====================================================================================
            HANDLE BANKING CHOICE
======================================================================================= */

this._handleBankingChoice = function (choice) {
    switch (choice) {
        case "9_EXIT":
            return; // Exit the banking screen

        case "1_DEPOSIT":
            this._showBankingScreen("deposit");
            break;

        case "2_WITHDRAWAL":
            this._showBankingScreen("withdrawal");
            break;

        case "3_AUTOBANK_TOGGLE":
            this._toggleAutoBankProfits();
            // no break
        case "3_AUTOBANK":
            this._showBankingScreen("autobank");
            break;

        default:
            // Redisplay the banking screen
            this._showBankingScreen(choice);
            break;
    }
};

/* ====================================================================================
            PERFORM TRANSACTION
======================================================================================= */

this._performTransaction = function (transactionType, amount) {
    var transaction = "";
    switch (transactionType) {
        case "auto_deposit":
        case "deposit":
            // Transfer credits from wallet to bank
            if (amount > 0 && amount <= missionVariables.WitchBank_cashInWallet) {
                missionVariables.WitchBank_cashAtBank += amount;
                missionVariables.WitchBank_cashInWallet -= amount;
                player.consoleMessage("Deposited " + amount + " credits.", 6);
                log(this.name, "Deposited " + amount + " credits. New balances: Bank=" +
                    missionVariables.WitchBank_cashAtBank + ", Wallet=" +
                    missionVariables.WitchBank_cashInWallet);

                // Log the transaction
                if (transactionType === "deposit") {
                    transaction = "Deposited " + amount + " credits.";
                } else {
                    transaction = "Autobanked " + amount + " credits.";
                }
            } else {
                player.consoleMessage("Invalid deposit amount.", 6);
            }
            break;

        case "withdrawal":
            // Transfer credits from bank to wallet
            if (amount > 0 && amount <= missionVariables.WitchBank_cashAtBank) {
                missionVariables.WitchBank_cashAtBank -= amount;
                missionVariables.WitchBank_cashInWallet += amount;
                player.consoleMessage("Withdrew " + amount + " credits.", 6);
                log(this.name, "Withdrew " + amount + " credits. New balances: Bank=" +
                    missionVariables.WitchBank_cashAtBank + ", Wallet=" +
                    missionVariables.WitchBank_cashInWallet);

                // Log the transaction
                transaction = "Withdrew " + amount + " credits.";
            } else {
                player.consoleMessage("Invalid withdrawal amount.", 6);
            }
            break;

        default:
            player.consoleMessage("Invalid banking operation.", 6);
            break;
    }

    // Add the transaction to the log
    if (transaction) {
        this._logTransaction(transaction);
    }
};

/* ====================================================================================
            TRANSACTION LOGGING FUNCTIONS
======================================================================================= */

this._logTransaction = function (transaction) {
    // Add the transaction to the log
    var timestamp = clock.days + " days, " + clock.seconds + " seconds";
    this.WitchBank_transactionLog.unshift(timestamp + ": " + transaction);

    // Limit the log to the last 10 transactions
    if (this.WitchBank_transactionLog.length > 10) {
        this.WitchBank_transactionLog.pop();
    }
};

this._getTransactionLog = function () {
    if (this.WitchBank_transactionLog.length === 0) {
        return "No recent transactions.";
    }

    // Join the log entries into a single string
    return this.WitchBank_transactionLog.join("\n");
};

/* ====================================================================================
            FUNCTIONS TO AUTO-BANK PROFITS FROM TRADING
======================================================================================= */

this._toggleAutoBankProfits = function () {
    this._autoBankProfits = !this._autoBankProfits;
    player.consoleMessage("Auto-banking of profits is now " + (this._autoBankProfits ? "enabled" : "disabled") + ".", 6);
};

/* Only customers using auto-bank earn interest.
   Will need a day counter to call _applyInterest once every 30 days
   Will need to keep track of lowest _cashAtBank throughout the month.
*/

this._interestPaymentFrequency = 30; // Interest paid once every 30 days
this._daysSinceInterestPaid = 0;
this._lowestBalance = missionVariables.WitchBank_cashAtBank;

this.dayChanged = function (newday) {
    this._daysSinceInterestPaid++;
    
    // Update the lowest balance for the month
    if (missionVariables.WitchBank_cashAtBank < this._lowestBalance) {
        this._lowestBalance = Math.max(missionVariables.WitchBank_cashAtBank, 0);
    }

    // Check if interest should be applied
    if (this._autoBankProfits === true) {
        if (this._daysSinceInterestPaid >= this._interestPaymentFrequency) {
            this._applyInterest(this._lowestBalance);

            // Reset for the new month
            this._daysSinceInterestPaid = 0;
            this._lowestBalance = missionVariables.WitchBank_cashAtBank;
        }
    }
};

this._applyInterest = function (balance) {
    var interestRate = 0.01; // 1% per month
    var interest = Math.floor(balance * interestRate);
    missionVariables.WitchBank_cashAtBank += interest;

    // Notify the player
    player.consoleMessage("You earned " + interest + " credits in interest.", 6);

    // Log the transaction
    log(this.name, "Applied interest: " + interest + " credits. New balance: " +
        missionVariables.WitchBank_cashAtBank);
};

/* ====================================================================================
    The two trading screens are "GUI_SCREEN_MARKET" AND "GUI_SCREEN_MARKETINFO"
    Ignore screen changes between those two.

    When the player enters the trading screens, record player.credits .

    When the player leaves the trading screens, compare player.credits to previous recorded.

    If player.credits <= this.previousCredits (lost money trading), then do nothing

    If player.credits > this.previousCredits (made a profit trading), then send profit to bank:

    this._pendingTransaction = "auto_deposit";
    this._showBankingScreen(profit, to); // If _pendingTransaction is set, process the caller as an amount
    
======================================================================================= */

// Player has entered the market screens.
      this.guiScreenChanged = function (to, from) {
          if ( (to === "GUI_SCREEN_MARKET" &&
              from !== "GUI_SCREEN_MARKETINFO") ||
              (to === "GUI_SCREEN_MARKETINFO" &&
              from !== "GUI_SCREEN_MARKET") ) {
          


              this.previousCredits = player.credits;
          }
      };

// The playerBoughtCargo handler is called when cargo is bought at the market screens.
this.playerBoughtCargo = function (commodity, units, price) {
     // Your code here
     // price is price per unit in tenths of a credit.
}

// The playerSoldCargo handler is called when cargo is sold at the market screens.
this.playerSoldCargo = function (commodity, units, price) {
     // Your code here
     // price is price per unit in tenths of a credit.
}

// Player is leaving the market screens.
      this.guiScreenWillChange = function (to, from) {
          if ( (to !== "GUI_SCREEN_MARKET" &&
              from === "GUI_SCREEN_MARKETINFO") ||
              (to !== "GUI_SCREEN_MARKETINFO" &&
              from === "GUI_SCREEN_MARKET") ) {
              if (player.credits <= this.previousCredits) { // no profit to bank
                  delete this.previousCredits;

              } else { // made a profit trading, so send profit to bank
                  var profit = player.credits - this.previousCredits;
                  this._pendingTransaction = "auto_deposit";
                  this._showBankingScreen(profit, to);
               // this._showBankingScreen.bind(this)
              }
         }
     };
Last edited by Wildeblood on Tue Apr 08, 2025 7:19 pm, edited 2 times in total.
"There are large, white swans, and there are small, black swans," he explained, "But there are no medium-sized swans, and there are no grey swans. The non-existence of grey swans mitigates against belief in Mr Darwin's theory."
User avatar
Cholmondely
Archivist
Archivist
Posts: 5785
Joined: Tue Jul 07, 2020 11:00 am
Location: The Delightful Domains of His Most Britannic Majesty (industrial? agricultural? mainly anything?)
Contact:

Re: Witch Bank [WIP]

Post by Cholmondely »

Wildeblood wrote: Tue Apr 08, 2025 3:35 pm
This is what I've been doing the last few days while the BB has been offline.
Any chance of a more immersive name? Or even choice of names?

We currently have the Bank of Ensoreus, Ooyds Bank of Teorge, The Alliances Bank of Ensoreus & Onrira, Pangloss 'n 'Griff, and the Royal Bank of Beanen (G2). These are from the YAH oxps I broke open to catalogue.


And two OXPs: Littlebear's Order of the Black Monks of Saint Herod & Ocz's Lave First Finance Corp


Reference: more competition in the banking sector (2009)

Image
Image
Image
Image
Comments wanted:
Missing OXPs? What do you think is missing?
Lore: The economics of ship building How many built for Aronar?
Lore: The Space Traders Flight Training Manual: Cowell & MgRath Do you agree with Redspear?
User avatar
Wildeblood
---- E L I T E ----
---- E L I T E ----
Posts: 2650
Joined: Sat Jun 11, 2011 6:07 am
Location: Nova Hollandia
Contact:

Re: Witch Bank [WIP]

Post by Wildeblood »

Cholmondely wrote: Tue Apr 08, 2025 5:36 pm
We currently have the Bank of Ensoreus, Ooyds Bank of Teorge, The Alliances Bank of Ensoreus & Onrira, Pangloss 'n 'Griff, and the Royal Bank of Beanen (G2). These are from the YAH oxps I broke open to catalogue.
Do they actually do anything? I thought they were just ads in the constore/YAH package of spam? Please don't tell me I've been wasting my time re-inventing the wheel?
"There are large, white swans, and there are small, black swans," he explained, "But there are no medium-sized swans, and there are no grey swans. The non-existence of grey swans mitigates against belief in Mr Darwin's theory."
User avatar
Wildeblood
---- E L I T E ----
---- E L I T E ----
Posts: 2650
Joined: Sat Jun 11, 2011 6:07 am
Location: Nova Hollandia
Contact:

Re: Witch Bank [WIP]

Post by Wildeblood »

Cholmondely wrote: Tue Apr 08, 2025 5:36 pm
Any chance of a more immersive name?
No. Ask phkb to explain the name to you.
Cholmondely wrote: Tue Apr 08, 2025 5:36 pm
Or even choice of names?
Maybe.

Maybe the first person to provide a decent background image will get to decide the branding.
Last edited by Wildeblood on Tue Apr 08, 2025 5:45 pm, edited 1 time in total.
"There are large, white swans, and there are small, black swans," he explained, "But there are no medium-sized swans, and there are no grey swans. The non-existence of grey swans mitigates against belief in Mr Darwin's theory."
User avatar
Cholmondely
Archivist
Archivist
Posts: 5785
Joined: Tue Jul 07, 2020 11:00 am
Location: The Delightful Domains of His Most Britannic Majesty (industrial? agricultural? mainly anything?)
Contact:

Re: Witch Bank [WIP]

Post by Cholmondely »

Wildeblood wrote: Tue Apr 08, 2025 5:40 pm
Do they actually do anything? I thought they were just ads in the constore/YAH package of spam? Please don't tell me I've been wasting my time re-inventing the wheel?
As of yet, no. Sadly.
Comments wanted:
Missing OXPs? What do you think is missing?
Lore: The economics of ship building How many built for Aronar?
Lore: The Space Traders Flight Training Manual: Cowell & MgRath Do you agree with Redspear?
User avatar
phkb
Impressively Grand Sub-Admiral
Impressively Grand Sub-Admiral
Posts: 4984
Joined: Tue Jan 21, 2014 10:37 pm
Location: Writing more OXPs, because the world needs more OXPs.

Re: Witch Bank [WIP]

Post by phkb »

Wildeblood wrote: Tue Apr 08, 2025 3:35 pm
Ask phkb to finish it
:wink:

Syntax error on line 235.
This line:

Code: Select all

                if (transactionType) === "deposit" {
should be

Code: Select all

                if (transactionType === "deposit") {
Wildeblood wrote: Tue Apr 08, 2025 5:43 pm
Ask phkb to explain the name to you.
Err... ok...
"Which bank?" was the tag line of an ad campaign back in the... err... a long time ago, for the Commonwealth Bank. Actually, switching (see what I did there?) it to "Witch Bank" is both funny and appropriate (ie. witchspace, etc).
User avatar
Wildeblood
---- E L I T E ----
---- E L I T E ----
Posts: 2650
Joined: Sat Jun 11, 2011 6:07 am
Location: Nova Hollandia
Contact:

Re: Witch Bank [WIP]

Post by Wildeblood »

phkb wrote: Tue Apr 08, 2025 6:59 pm
Syntax error on line 235.
Wildeblood wrote: Tue Apr 08, 2025 5:43 pm
Ask phkb to explain the name to you.
Err... ok...
"Which bank?" was the tag line of an ad campaign back in the... err... a long time ago, for the Commonwealth Bank. Actually, switching (see what I did there?) it to "Witch Bank" is both funny and appropriate (ie. witchspace, etc).
I was just coming to fix line 235, good grief, you're quick.

I was sure I'd saved it after fixing that, or before adding that, or whatever. I was sure I'd copy/pasted one that didn't have that. I dunno. Are you up early or late? :shock:
"There are large, white swans, and there are small, black swans," he explained, "But there are no medium-sized swans, and there are no grey swans. The non-existence of grey swans mitigates against belief in Mr Darwin's theory."
User avatar
phkb
Impressively Grand Sub-Admiral
Impressively Grand Sub-Admiral
Posts: 4984
Joined: Tue Jan 21, 2014 10:37 pm
Location: Writing more OXPs, because the world needs more OXPs.

Re: Witch Bank [WIP]

Post by phkb »

Early. Very, very early.
Post Reply