MISC: tiny corp code style improvement (#586)

This commit is contained in:
Aleksei Bezrodnov 2023-06-10 01:34:35 +02:00 committed by GitHub
parent 8f312ba616
commit 174f10d1f5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 87 additions and 63 deletions

@ -1,7 +1,11 @@
import { isInteger } from "lodash";
import { Player } from "@player"; import { Player } from "@player";
import { CorpResearchName, CorpSmartSupplyOption } from "@nsdefs";
import { MaterialInfo } from "./MaterialInfo"; import { MaterialInfo } from "./MaterialInfo";
import { Corporation } from "./Corporation"; import { Corporation } from "./Corporation";
import { IndustryResearchTrees, IndustriesData } from "./IndustryData"; import { IndustryResearchTrees, IndustriesData } from "./data/IndustryData";
import { Division } from "./Division"; import { Division } from "./Division";
import * as corpConstants from "./data/Constants"; import * as corpConstants from "./data/Constants";
import { OfficeSpace } from "./OfficeSpace"; import { OfficeSpace } from "./OfficeSpace";
@ -13,8 +17,6 @@ import { ResearchMap } from "./ResearchMap";
import { isRelevantMaterial } from "./ui/Helpers"; import { isRelevantMaterial } from "./ui/Helpers";
import { CityName } from "../Enums"; import { CityName } from "../Enums";
import { getRandomInt } from "../utils/helpers/getRandomInt"; import { getRandomInt } from "../utils/helpers/getRandomInt";
import { CorpResearchName } from "@nsdefs";
import { isInteger } from "lodash";
import { getRecordValues } from "../Types/Record"; import { getRecordValues } from "../Types/Record";
export function NewDivision(corporation: Corporation, industry: IndustryType, name: string): void { export function NewDivision(corporation: Corporation, industry: IndustryType, name: string): void {
@ -206,6 +208,7 @@ export function SellProduct(product: Product, city: CityName, amt: string, price
if (temp == null || isNaN(parseFloat(temp))) { if (temp == null || isNaN(parseFloat(temp))) {
throw new Error("Invalid value or expression for sell quantity field"); throw new Error("Invalid value or expression for sell quantity field");
} }
if (all) { if (all) {
for (const cityName of Object.values(CityName)) { for (const cityName of Object.values(CityName)) {
product.cityData[cityName].desiredSellAmount = qty; //Use sanitized input product.cityData[cityName].desiredSellAmount = qty; //Use sanitized input
@ -242,10 +245,7 @@ export function SetSmartSupply(warehouse: Warehouse, smartSupply: boolean): void
warehouse.smartSupplyEnabled = smartSupply; warehouse.smartSupplyEnabled = smartSupply;
} }
export function SetSmartSupplyOption(warehouse: Warehouse, material: Material, useOption: string): void { export function SetSmartSupplyOption(warehouse: Warehouse, material: Material, useOption: CorpSmartSupplyOption): void {
if (!corpConstants.smartSupplyUseOptions.includes(useOption)) {
throw new Error(`Invalid Smart Supply option '${useOption}'`);
}
warehouse.smartSupplyOptions[material.name] = useOption; warehouse.smartSupplyOptions[material.name] = useOption;
} }

@ -36,8 +36,10 @@ export class Corporation {
revenue = 0; revenue = 0;
expenses = 0; expenses = 0;
fundingRound = 0; fundingRound = 0;
public = false; //Publicly traded /** Publicly traded */
totalShares = corpConstants.initialShares; // Total existing shares public = false;
/** Total existing shares */
totalShares = corpConstants.initialShares;
numShares = corpConstants.initialShares; // Total shares owned by player numShares = corpConstants.initialShares; // Total shares owned by player
shareSalesUntilPriceUpdate = corpConstants.sharesPerPriceUpdate; shareSalesUntilPriceUpdate = corpConstants.sharesPerPriceUpdate;
shareSaleCooldown = 0; // Game cycles until player can sell shares again shareSaleCooldown = 0; // Game cycles until player can sell shares again
@ -64,7 +66,7 @@ export class Corporation {
state = new CorporationState(); state = new CorporationState();
constructor(params: IParams = {}) { constructor(params: IParams = {}) {
this.name = params.name ? params.name : "The Corporation"; this.name = params.name || "The Corporation";
this.seedFunded = params.seedFunded ?? false; this.seedFunded = params.seedFunded ?? false;
} }
@ -73,14 +75,14 @@ export class Corporation {
console.error("Trying to add invalid amount of funds. Report to a developer."); console.error("Trying to add invalid amount of funds. Report to a developer.");
return; return;
} }
this.funds = this.funds + amt; this.funds += amt;
} }
getState(): CorpStateName { getState(): CorpStateName {
return this.state.getState(); return this.state.getState();
} }
storeCycles(numCycles = 1): void { storeCycles(numCycles: number): void {
this.storedCycles += numCycles; this.storedCycles += numCycles;
} }

@ -1,6 +1,6 @@
import { constructorsForReviver, Generic_toJSON, Generic_fromJSON, IReviverValue } from "../utils/JSONReviver"; import { constructorsForReviver, Generic_toJSON, Generic_fromJSON, IReviverValue } from "../utils/JSONReviver";
import { CityName } from "../Enums"; import { CityName } from "../Enums";
import { IndustryResearchTrees, IndustriesData } from "./IndustryData"; import { IndustryResearchTrees, IndustriesData } from "./data/IndustryData";
import * as corpConstants from "./data/Constants"; import * as corpConstants from "./data/Constants";
import { CorpEmployeeJob, IndustryType } from "./data/Enums"; import { CorpEmployeeJob, IndustryType } from "./data/Enums";
import { getRandomInt } from "../utils/helpers/getRandomInt"; import { getRandomInt } from "../utils/helpers/getRandomInt";

@ -1,7 +1,7 @@
import { CorpEmployeeJob } from "./data/Enums"; import { CorpEmployeeJob } from "./data/Enums";
import { IndustriesData } from "./data/IndustryData";
import { MaterialInfo } from "./MaterialInfo"; import { MaterialInfo } from "./MaterialInfo";
import { Division } from "./Division"; import { Division } from "./Division";
import { IndustriesData } from "./IndustryData";
import { Generic_fromJSON, Generic_toJSON, IReviverValue, constructorsForReviver } from "../utils/JSONReviver"; import { Generic_fromJSON, Generic_toJSON, IReviverValue, constructorsForReviver } from "../utils/JSONReviver";
import { getRandomInt } from "../utils/helpers/getRandomInt"; import { getRandomInt } from "../utils/helpers/getRandomInt";

@ -1,3 +1,6 @@
import { Player } from "@player";
import { CorpMaterialName, CorpSmartSupplyOption } from "@nsdefs";
import { Material } from "./Material"; import { Material } from "./Material";
import { Corporation } from "./Corporation"; import { Corporation } from "./Corporation";
import { Division } from "./Division"; import { Division } from "./Division";
@ -7,7 +10,6 @@ import { CityName } from "../Enums";
import { materialNames } from "./data/Constants"; import { materialNames } from "./data/Constants";
import { createFullRecordFromEntries, getRecordEntries } from "../Types/Record"; import { createFullRecordFromEntries, getRecordEntries } from "../Types/Record";
import { CorpUnlockName } from "./data/Enums"; import { CorpUnlockName } from "./data/Enums";
import { Player } from "@player";
interface IConstructorParams { interface IConstructorParams {
division: Division; division: Division;
@ -35,7 +37,9 @@ export class Warehouse {
smartSupplyEnabled = false; smartSupplyEnabled = false;
// Decide if smart supply should use the amount of materials imported into account when deciding on the amount to buy. // Decide if smart supply should use the amount of materials imported into account when deciding on the amount to buy.
smartSupplyOptions = createFullRecordFromEntries(materialNames.map((matName) => [matName, "leftovers"])); smartSupplyOptions = createFullRecordFromEntries<CorpMaterialName, CorpSmartSupplyOption>(
materialNames.map((matName) => [matName, "leftovers"]),
);
// Stores the amount of product to be produced. Used for Smart Supply unlock. // Stores the amount of product to be produced. Used for Smart Supply unlock.
// The production tracked by smart supply is always based on the previous cycle, // The production tracked by smart supply is always based on the previous cycle,

@ -3,6 +3,7 @@ import {
CorpIndustryName, CorpIndustryName,
CorpMaterialName, CorpMaterialName,
CorpResearchName, CorpResearchName,
CorpSmartSupplyOption,
CorpStateName, CorpStateName,
CorpUnlockName, CorpUnlockName,
CorpUpgradeName, CorpUpgradeName,
@ -121,8 +122,8 @@ export const stateNames: CorpStateName[] = ["START", "PURCHASE", "PRODUCTION", "
valuationLength = 10, valuationLength = 10,
/** Minimum decay value for employee morale/energy */ /** Minimum decay value for employee morale/energy */
minEmployeeDecay = 10, minEmployeeDecay = 10,
/**smart supply ot */ /** smart supply options */
smartSupplyUseOptions = ["leftovers", "imports", "none"], smartSupplyOptions: CorpSmartSupplyOption[] = ["leftovers", "imports", "none"],
PurchaseMultipliers = { PurchaseMultipliers = {
x1: 1 as PositiveInteger, x1: 1 as PositiveInteger,
x5: 5 as PositiveInteger, x5: 5 as PositiveInteger,

@ -1,10 +1,8 @@
import React from "react";
import { Corporation } from "./Corporation";
import { getBaseResearchTreeCopy, getProductIndustryResearchTreeCopy } from "./data/BaseResearchTree";
import { MoneyCost } from "./ui/MoneyCost";
import { CorpIndustryData } from "@nsdefs"; import { CorpIndustryData } from "@nsdefs";
import { IndustryType } from "./data/Enums";
import { createFullRecordFromEntries } from "../Types/Record"; import { createFullRecordFromEntries } from "../../Types/Record";
import { IndustryType } from "./Enums";
import { getBaseResearchTreeCopy, getProductIndustryResearchTreeCopy } from "./BaseResearchTree";
export const IndustriesData: Record<IndustryType, CorpIndustryData> = { export const IndustriesData: Record<IndustryType, CorpIndustryData> = {
[IndustryType.Agriculture]: { [IndustryType.Agriculture]: {
@ -293,28 +291,6 @@ export const IndustriesData: Record<IndustryType, CorpIndustryData> = {
export const IndustryStartingCosts = {}; export const IndustryStartingCosts = {};
// Map of description for each industry
export const IndustryDescriptions = (industry: IndustryType, corp: Corporation) => {
const data = IndustriesData[industry];
return (
<>
{data.description}
<br />
<br />
Required Materials: {Object.keys(data.requiredMaterials).toString().replace(/,/gi, ", ")}
<br />
Produces Materials: {data.producedMaterials ? data.producedMaterials.toString().replace(/,/gi, ", ") : "NONE"}
<br />
Produces products: {data.product ? "YES" : "NO"}
<br />
<br />
Starting cost: <MoneyCost money={data.startingCost} corp={corp} />
<br />
Recommended starting Industry: {data.recommendStarting ? "YES" : "NO"}
</>
);
};
export const IndustryResearchTrees = createFullRecordFromEntries( export const IndustryResearchTrees = createFullRecordFromEntries(
Object.values(IndustryType).map((industryType) => { Object.values(IndustryType).map((industryType) => {
return [ return [

@ -0,0 +1,34 @@
import React from "react";
import Typography from "@mui/material/Typography";
import { MoneyCost } from "./MoneyCost";
import { Corporation } from "../Corporation";
import { IndustryType } from "../data/Enums";
import { IndustriesData } from "../data/IndustryData";
interface IProps {
industry: IndustryType;
corp: Corporation;
}
export const IndustryDescription = ({ industry, corp }: IProps) => {
const data = IndustriesData[industry];
return (
<Typography>
{data.description}
<br />
<br />
Required Materials: {Object.keys(data.requiredMaterials).toString().replace(/,/gi, ", ")}
<br />
Produces Materials: {data.producedMaterials ? data.producedMaterials.toString().replace(/,/gi, ", ") : "NONE"}
<br />
Produces products: {data.product ? "YES" : "NO"}
<br />
<br />
Starting cost: <MoneyCost money={data.startingCost} corp={corp} />
<br />
Recommended starting Industry: {data.recommendStarting ? "YES" : "NO"}
</Typography>
);
};

@ -1,17 +1,20 @@
import React, { useState } from "react"; import React, { useState } from "react";
import Box from "@mui/material/Box";
import MenuItem from "@mui/material/MenuItem";
import Select, { SelectChangeEvent } from "@mui/material/Select";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import { dialogBoxCreate } from "../../ui/React/DialogBox"; import { dialogBoxCreate } from "../../ui/React/DialogBox";
import { IndustryDescriptions, IndustriesData } from "../IndustryData"; import { IndustriesData } from "../data/IndustryData";
import { IndustryType } from "../data/Enums"; import { IndustryType } from "../data/Enums";
import { useCorporation } from "./Context"; import { useCorporation } from "./Context";
import { NewDivision } from "../Actions"; import { NewDivision } from "../Actions";
import Typography from "@mui/material/Typography";
import { ButtonWithTooltip } from "../../ui/Components/ButtonWithTooltip"; import { ButtonWithTooltip } from "../../ui/Components/ButtonWithTooltip";
import TextField from "@mui/material/TextField";
import MenuItem from "@mui/material/MenuItem";
import Box from "@mui/material/Box";
import Select, { SelectChangeEvent } from "@mui/material/Select";
import { KEY } from "../../utils/helpers/keyCodes"; import { KEY } from "../../utils/helpers/keyCodes";
import { IndustryDescription } from "./IndustryDescription";
interface IProps { interface IProps {
setDivisionName: (name: string) => void; setDivisionName: (name: string) => void;
} }
@ -58,9 +61,6 @@ export function NewDivisionTab(props: IProps): React.ReactElement {
setIndustry(event.target.value as IndustryType); setIndustry(event.target.value as IndustryType);
} }
const desc = IndustryDescriptions(industry, corp);
if (desc === undefined) throw new Error(`Desired industry for new division doesn't exists: '${industry}'`);
return ( return (
<> <>
<Typography> <Typography>
@ -74,7 +74,7 @@ export function NewDivisionTab(props: IProps): React.ReactElement {
</MenuItem> </MenuItem>
))} ))}
</Select> </Select>
<Typography>{desc}</Typography> <IndustryDescription industry={industry} corp={corp} />
<br /> <br />
<br /> <br />

@ -1,7 +1,7 @@
import React, { useState } from "react"; import React, { useState } from "react";
import { dialogBoxCreate } from "../../../ui/React/DialogBox"; import { dialogBoxCreate } from "../../../ui/React/DialogBox";
import { Modal } from "../../../ui/React/Modal"; import { Modal } from "../../../ui/React/Modal";
import { IndustriesData } from "../../IndustryData"; import { IndustriesData } from "../../data/IndustryData";
import { IndustryType } from "../../data/Enums"; import { IndustryType } from "../../data/Enums";
import { MakeProduct } from "../../Actions"; import { MakeProduct } from "../../Actions";
import { useCorporation, useDivision } from "../Context"; import { useCorporation, useDivision } from "../Context";

@ -1,6 +1,6 @@
import React, { useState } from "react"; import React, { useState } from "react";
import { Modal } from "../../../ui/React/Modal"; import { Modal } from "../../../ui/React/Modal";
import { IndustryResearchTrees } from "../../IndustryData"; import { IndustryResearchTrees } from "../../data/IndustryData";
import * as corpConstants from "../../data/Constants"; import * as corpConstants from "../../data/Constants";
import { Division } from "../../Division"; import { Division } from "../../Division";
import { Research } from "../../Actions"; import { Research } from "../../Actions";

@ -52,7 +52,7 @@ import {
import { CorpUnlocks } from "../Corporation/data/CorporationUnlocks"; import { CorpUnlocks } from "../Corporation/data/CorporationUnlocks";
import { CorpUpgrades } from "../Corporation/data/CorporationUpgrades"; import { CorpUpgrades } from "../Corporation/data/CorporationUpgrades";
import { CorpUnlockName, CorpUpgradeName, CorpEmployeeJob, IndustryType } from "../Corporation/data/Enums"; import { CorpUnlockName, CorpUpgradeName, CorpEmployeeJob, IndustryType } from "../Corporation/data/Enums";
import { IndustriesData, IndustryResearchTrees } from "../Corporation/IndustryData"; import { IndustriesData, IndustryResearchTrees } from "../Corporation/data/IndustryData";
import * as corpConstants from "../Corporation/data/Constants"; import * as corpConstants from "../Corporation/data/Constants";
import { ResearchMap } from "../Corporation/ResearchMap"; import { ResearchMap } from "../Corporation/ResearchMap";
import { Factions } from "../Faction/Factions"; import { Factions } from "../Faction/Factions";
@ -413,6 +413,7 @@ export function NetscriptCorporation(): InternalAPI<NSCorporation> {
const warehouse = getWarehouse(divisionName, cityName); const warehouse = getWarehouse(divisionName, cityName);
const material = getMaterial(divisionName, cityName, materialName); const material = getMaterial(divisionName, cityName, materialName);
const option = helpers.string(ctx, "option", _option); const option = helpers.string(ctx, "option", _option);
assertMember(ctx, corpConstants.smartSupplyOptions, "Smart Supply Option", "option", option);
if (!hasUnlock(CorpUnlockName.SmartSupply)) if (!hasUnlock(CorpUnlockName.SmartSupply))
throw helpers.makeRuntimeErrorMsg(ctx, `You have not purchased the Smart Supply upgrade!`); throw helpers.makeRuntimeErrorMsg(ctx, `You have not purchased the Smart Supply upgrade!`);
SetSmartSupplyOption(warehouse, material, option); SetSmartSupplyOption(warehouse, material, option);
@ -682,8 +683,8 @@ export function NetscriptCorporation(): InternalAPI<NSCorporation> {
/* TODO 2.2: possibly just rework the whole corp constants structure to be more readable, and just use cloneDeep /* TODO 2.2: possibly just rework the whole corp constants structure to be more readable, and just use cloneDeep
* to provide it directly to player. * to provide it directly to player.
* TODO 2.2: Roll product information into industriesData, there's no reason to look up a product separately */ * TODO 2.2: Roll product information into industriesData, there's no reason to look up a product separately */
return cloneDeep(omit(corpConstants, "fundingRoundShares", "fundingRoundMultiplier", "valuationLength"));
// TODO: add functions for getting materialInfo and research info // TODO: add functions for getting materialInfo and research info
return cloneDeep(omit(corpConstants, "fundingRoundShares", "fundingRoundMultiplier", "valuationLength"));
}, },
getIndustryData: (ctx) => (_industryName) => { getIndustryData: (ctx) => (_industryName) => {
checkAccess(ctx); checkAccess(ctx);

@ -1,6 +1,6 @@
import { CorpUnlockName } from "../../Corporation/data/Enums"; import { CorpUnlockName } from "../../Corporation/data/Enums";
import { resetIndustryResearchTrees } from "../../Corporation/data/IndustryData";
import { Corporation } from "../../Corporation/Corporation"; import { Corporation } from "../../Corporation/Corporation";
import { resetIndustryResearchTrees } from "../../Corporation/IndustryData";
import type { PlayerObject } from "./PlayerObject"; import type { PlayerObject } from "./PlayerObject";

@ -5,7 +5,7 @@ import { augmentationExists, initAugmentations } from "./Augmentation/Augmentati
import { AugmentationNames } from "./Augmentation/data/AugmentationNames"; import { AugmentationNames } from "./Augmentation/data/AugmentationNames";
import { initBitNodeMultipliers } from "./BitNode/BitNode"; import { initBitNodeMultipliers } from "./BitNode/BitNode";
import { Companies, initCompanies } from "./Company/Companies"; import { Companies, initCompanies } from "./Company/Companies";
import { resetIndustryResearchTrees } from "./Corporation/IndustryData"; import { resetIndustryResearchTrees } from "./Corporation/data/IndustryData";
import { CompletedProgramName } from "./Programs/Programs"; import { CompletedProgramName } from "./Programs/Programs";
import { Factions, initFactions } from "./Faction/Factions"; import { Factions, initFactions } from "./Faction/Factions";
import { joinFaction } from "./Faction/FactionHelpers"; import { joinFaction } from "./Faction/FactionHelpers";

@ -6747,6 +6747,9 @@ type CorpIndustryName =
| "Healthcare" | "Healthcare"
| "Real Estate"; | "Real Estate";
/** @public */
type CorpSmartSupplyOption = "leftovers" | "imports" | "none";
/** Names of all cities /** Names of all cities
* @public */ * @public */
declare enum CityName { declare enum CityName {
@ -7002,7 +7005,7 @@ export interface WarehouseAPI {
divisionName: string, divisionName: string,
city: CityName | `${CityName}`, city: CityName | `${CityName}`,
materialName: string, materialName: string,
option: string, option: CorpSmartSupplyOption,
): void; ): void;
/** /**
* Set material buy data * Set material buy data
@ -7369,6 +7372,8 @@ interface CorporationInfo {
interface CorpConstants { interface CorpConstants {
/** Names of all corporation game states */ /** Names of all corporation game states */
stateNames: CorpStateName[]; stateNames: CorpStateName[];
/** Names of all employee positions */
employeePositions: CorpEmployeePosition[];
/** Names of all industries */ /** Names of all industries */
industryNames: CorpIndustryName[]; industryNames: CorpIndustryName[];
/** Names of all materials */ /** Names of all materials */
@ -7412,6 +7417,7 @@ interface CorpConstants {
maxProductsBase: number; maxProductsBase: number;
/** The minimum decay value for morale/energy */ /** The minimum decay value for morale/energy */
minEmployeeDecay: number; minEmployeeDecay: number;
smartSupplyOptions: CorpSmartSupplyOption[];
} }
/** @public */ /** @public */
type CorpStateName = "START" | "PURCHASE" | "PRODUCTION" | "EXPORT" | "SALE"; type CorpStateName = "START" | "PURCHASE" | "PRODUCTION" | "EXPORT" | "SALE";