Merge pull request #3120 from danielyxie/dev

arcade
This commit is contained in:
hydroflame 2022-03-11 15:23:29 -05:00 committed by GitHub
commit 5874fff0bd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
86 changed files with 642 additions and 453 deletions

@ -43,7 +43,7 @@ module.exports = {
curly: ["off"], curly: ["off"],
"default-case": ["off"], "default-case": ["off"],
"dot-notation": ["off"], "dot-notation": ["off"],
"eol-last": ["off"], "eol-last": ["error"],
eqeqeq: ["off"], eqeqeq: ["off"],
"for-direction": ["error"], "for-direction": ["error"],
"func-call-spacing": ["off"], "func-call-spacing": ["off"],
@ -236,7 +236,7 @@ module.exports = {
"no-ternary": ["off"], "no-ternary": ["off"],
"no-this-before-super": ["off"], "no-this-before-super": ["off"],
"no-throw-literal": ["error"], "no-throw-literal": ["error"],
"no-trailing-spaces": ["off"], "no-trailing-spaces": ["error"],
"no-undef": ["off"], "no-undef": ["off"],
"no-undef-init": ["error"], "no-undef-init": ["error"],
"no-undefined": ["off"], "no-undefined": ["off"],

1
CODE_OF_CONDUCT.md Normal file

@ -0,0 +1 @@
Don't be an ass.

2
dist/bitburner.d.ts vendored

@ -3915,7 +3915,7 @@ export declare interface NS extends Singularity {
* @param data - Data to write. * @param data - Data to write.
* @returns True if the data is successfully written to the port, and false otherwise. * @returns True if the data is successfully written to the port, and false otherwise.
*/ */
tryWritePort(port: number, data: string[] | number): Promise<boolean>; tryWritePort(port: number, data: string | number): Promise<boolean>;
/** /**
* Read content of a file. * Read content of a file.

34
dist/vendor.bundle.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

@ -2,7 +2,7 @@
Augmentations Augmentations
============= =============
Advances in science and medicine have lead to powerful new technologies Advances in science and medicine have led to powerful new technologies
that allow people to augment themselves beyond normal human capabilities. that allow people to augment themselves beyond normal human capabilities.
There are many different types of Augmentations, ranging from cybernetic There are many different types of Augmentations, ranging from cybernetic
to genetic to biological. Acquiring these Augmentations enhances the to genetic to biological. Acquiring these Augmentations enhances the

@ -312,6 +312,16 @@ function getMenu(window) {
} }
}, },
}, },
{
label: "Reset Zoom",
enabled: utils.getZoomFactor() !== 1,
accelerator: "CommandOrControl+num0",
click: () => {
utils.setZoomFactor(window, 1);
refreshMenu(window);
log.log("Reset zoom");
},
},
], ],
}, },
{ {

@ -1,85 +1,88 @@
LIMITED USE SOFTWARE LICENSE AGREEMENT “Commons Clause” License Condition v1.0
This Limited Use Software License Agreement (the "Agreement") is a legal agreement between you, the end-user, and Daniel Y Xie, The Software is provided to you by the Licensor under the License, as defined below, subject to the following condition.
the creator of the software, hereafter referred to as the Creator.
By downloading or purchasing the software material, which includes source code (the "Source Code"), artwork data, music and software Without limiting other conditions in the License, the grant of rights under the License will not include, and the License does not grant to you, the right to Sell the Software.
tools (collectively, the "Software"), you are agreeing to be bound by the terms of this Agreement. If you do not agree to the terms
of this Agreement, promptly destroy the Software you may have downloaded or copied.
SOFTWARE LICENSE For purposes of the foregoing, “Sell” means practicing any or all of the rights granted to you under the License to provide to third parties, for a fee or other consideration (including without limitation fees for hosting or consulting/ support services related to the Software), a product or service whose value derives, entirely or substantially, from the functionality of the Software. Any license notice or attribution required by the License must also include this Commons Clause License Condition notice.
1. Grant of License. The Creator grants to you the right to use the Software. You have no ownership or proprietary rights in or to Software: Bitburner
the Software, or the Trademark. For purposes of this section, "use" means loading the Software into RAM, as well as installation
on a hard disk or other storage device. The Software, together with any archive copy thereof, shall be destroyed when no longer
used in accordance with this Agreement, or when the right to use the Software is terminated. You agree that the Software will not
be shipped, transferred or exported into any country in violation of the U.S. Export Administration Act (or any other law governing
such matters) and that you will not utilize, in any other manner, the Software in violation of any applicable law.
2. Permitted Uses. License: Apache 2.0 with Commons Clause
You may copy and distribute literal (i.e., verbatim) or modified copies of the Software's source code. Licensor: Daniel Y Xie
You must meet all of the following conditions with respect to any work that you distribute or publish that in whole or in part
contains or is derived from the Software or any part thereof:
(a) The distributed Software may not be used in any way for commercial gain and must not violate any of the restrictions -------------------------------------------------------------------
set forth in Section 3.
(b) If you have modified the Software, you must cause the modified Software to carry prominent notices stating that
you have modified the Software's files. Modifications must not alter or remove any copyright notices in the Software.
(c) The distributed Software must include either a written copy of this License, or a prominent written indication that
the Software is covered by this License and written instructions for printing and/or displaying the copy of the License
on the distribution medium
(d) When modifications to the Software are released under this license, a non-exclusive royalty-free right is granted to
the initial developer of the Software to distribute your modification in future versions of the Software provided
such versions remain available under these terms in addition to any other license(s) of the initial developer.
(d) You may not impose any further restrictions on the recipient's exercise of the rights granted herein.
For educational purposes only, you, the end-user, may use portions of the Source Code, such as particular Apache License
routines, to develop your own software, but may not duplicate the Source Code. The limited Version 2.0, January 2004
right referenced in the preceding sentence is hereinafter referred to as "Educational Use." By so exercising the Educational http://www.apache.org/licenses/
Use right you shall not obtain any ownership, copyright, proprietary or other interest in or to the Source Code, or any portion TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
of the Source Code. You may dispose of your own software in your sole discretion. When exercising the Educational Use right,
you may not use or exploit the Software, or any portion of the Software, which includes the Source Code, for commercial gain.
3. Prohibited Uses: Under no circumstances shall you, the end-user, be permitted, allowed or authorized to commercially Definitions.
exploit the Software or any work that in whole or in part contains or is derived from the Software or any part thereof.
Neither you nor anyone at your direction shall do any of the following acts with regard to the Software,
or any portion thereof:
Rent; "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
Sell; "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
Lease; "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
Offer on a pay-per-play basis; "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
Distribute for money or any other consideration; or "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
In any other manner and through any medium whatsoever commercially exploit or use for any commercial purpose. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
4. Copyright. The Software and all copyrights related thereto (including all characters and other images generated by the "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
Software or depicted in the Software) are owned by the Creator and is protected by United States copyright laws and international treaty
provisions. The Creator shall retain exclusive ownership and copyright in and to the Software and all portions of the Software and you
shall have no ownership or other proprietary interest in such materials. You must treat the Software like any other copyrighted
material. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License.
You may not otherwise reproduce, copy or disclose to others, in whole or in any part, the Software. You may not copy the
written materials accompanying the Software. You agree to use your best efforts to see that any user of the Software licensed
hereunder complies with this Agreement.
5. NO WARRANTIES. The Creator DISCLAIMS ALL WARRANTIES, BOTH EXPRESS IMPLIED, INCLUDING BUT NOT LIMITED TO, IMPLIED WARRANTIES OF "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE WITH RESPECT TO THE SOFTWARE. THIS LIMITED WARRANTY GIVES YOU SPECIFIC
LEGAL RIGHTS. YOU MAY HAVE OTHER RIGHTS WHICH VARY FROM JURISDICTION TO JURISDICTION. the Creator DOES NOT WARRANT THAT THE OPERATION
OF THE SOFTWARE WILL BE UNINTERRUPTED, ERROR FREE OR MEET YOUR SPECIFIC REQUIREMENTS. THE WARRANTY SET FORTH ABOVE IS IN LIEU
OF ALL OTHER EXPRESS WARRANTIES WHETHER ORAL OR WRITTEN. THE AGENTS, EMPLOYEES, DISTRIBUTORS, AND DEALERS OF THE CREATOR ARE NOT AUTHORIZED
TO MAKE MODIFICATIONS TO THIS WARRANTY, OR ADDITIONAL WARRANTIES ON BEHALF OF THE CREATOR.
Exclusive Remedies. The Software is being offered to you free of any charge. You agree that you have no remedy against the creator, "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
its affiliates, contractors, suppliers, and agents for loss or damage caused by any defect or failure in the Software regardless
of the form of action, whether in contract, tort, includinegligence, strict liability or otherwise, with regard to the Software. "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
This Agreement shall be construed in accordance with and governed by the laws of the State of Texas. Copyright and other
proprietary matters will be governed by United States laws and international treaties. IN ANY CASE, THE CREATOR SHALL NOT BE LIABLE Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
FOR LOSS OF DATA, LOSS OF PROFITS, LOST SAVINGS, SPECIAL, INCIDENTAL, CONSEQUENTIAL, INDIRECT OR OTHER SIMILAR DAMAGES ARISING
FROM BREACH OF WARRANTY, BREACH OF CONTRACT, NEGLIGENCE, OR OTHER LEGAL THEORY EVEN IF THE CREATOR OR ITS AGENT HAS BEEN ADVISED OF THE Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
POSSIBILITY OF SUCH DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY. Some jurisdictions do not allow the exclusion or limitation of
incidental or consequential damages, so the above limitation or exclusion may not apply to you. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2022 Daniel Y Xie
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

@ -125,6 +125,6 @@
"electron:packager-win": "electron-packager .package bitburner --platform win32 --arch x64 --out .build --overwrite --icon .package/icon.png", "electron:packager-win": "electron-packager .package bitburner --platform win32 --arch x64 --out .build --overwrite --icon .package/icon.png",
"electron:packager-mac": "electron-packager .package bitburner --platform darwin --arch x64 --out .build --overwrite --icon .package/icon.png", "electron:packager-mac": "electron-packager .package bitburner --platform darwin --arch x64 --out .build --overwrite --icon .package/icon.png",
"electron:packager-linux": "electron-packager .package bitburner --platform linux --arch x64 --out .build --overwrite --icon .package/icon.png", "electron:packager-linux": "electron-packager .package bitburner --platform linux --arch x64 --out .build --overwrite --icon .package/icon.png",
"allbuild": "npm run build && npm run electron && git add --all && git commit -m 'allbuild commit `git rev-parse --short HEAD`' && git push -f -u origin dev" "allbuild": "npm run build && npm run electron && git add --all && git commit -m \"allbuild commit $(which git)\" && git push -f -u origin dev"
} }
} }

@ -36,7 +36,7 @@ export function printAliases(): void {
// Returns true if successful, false otherwise // Returns true if successful, false otherwise
export function parseAliasDeclaration(dec: string, global = false): boolean { export function parseAliasDeclaration(dec: string, global = false): boolean {
const re = /^([\w|!|%|,|@|-]+)=(("(.+)")|('(.+)'))$/; const re = /^([\w|!%,@-]+)=(("(.+)")|('(.+)'))$/;
const matches = dec.match(re); const matches = dec.match(re);
if (matches == null || matches.length != 7) { if (matches == null || matches.length != 7) {
return false; return false;

@ -0,0 +1,43 @@
import React, { useState } from "react";
import { BBCabinetRoot } from "./BBCabinet";
import Button from "@mui/material/Button";
import { use } from "../../ui/Context";
import { AlertEvents } from "../../ui/React/AlertManager";
enum Page {
None,
Megabyteburner2000,
}
export function ArcadeRoot(): React.ReactElement {
const player = use.Player();
const [page, setPage] = useState(Page.None);
function mbBurner2000(): void {
if (player.sourceFileLvl(1) === 0) {
AlertEvents.emit("This machine is broken.");
} else {
setPage(Page.Megabyteburner2000);
}
}
if (page === Page.None) {
return (
<>
<Button onClick={mbBurner2000}>Megabyte burner 2000</Button>
</>
);
}
let currentGame = <></>;
switch (page) {
case Page.Megabyteburner2000:
currentGame = <BBCabinetRoot />;
}
return (
<>
<Button onClick={() => setPage(Page.None)}>Back</Button>
{currentGame}
</>
);
}

@ -0,0 +1,52 @@
import React from "react";
import Typography from "@mui/material/Typography";
const metaBB = "https://bitburner-official.github.io/bitburner-legacy/";
const style = {
width: "1060px",
height: "800px",
border: "0px",
} as any;
export function BBCabinetRoot(): React.ReactElement {
// prettier-ignore
const joystick =
<>
<Typography sx={{lineHeight: '1em',whiteSpace: 'pre'}}> </Typography>
<Typography sx={{lineHeight: '1em',whiteSpace: 'pre'}}> ,'" "', .-. </Typography>
<Typography sx={{lineHeight: '1em',whiteSpace: 'pre'}}> / \ ( ) </Typography>
<Typography sx={{lineHeight: '1em',whiteSpace: 'pre'}}> | | .-. '-' .-. </Typography>
<Typography sx={{lineHeight: '1em',whiteSpace: 'pre'}}> \ / ( ) ( )</Typography>
<Typography sx={{lineHeight: '1em',whiteSpace: 'pre'}}> '.___.' '-' .-. '-'</Typography>
<Typography sx={{lineHeight: '1em',whiteSpace: 'pre'}}> ||| ( ) </Typography>
<Typography sx={{lineHeight: '1em',whiteSpace: 'pre'}}> ||| '-' </Typography>
</>;
return (
<>
<div
style={{
width: "1060px",
height: "800px",
padding: "0",
overflow: "hidden",
borderColor: "white",
borderStyle: "solid",
borderWidth: "5px",
}}
>
<iframe src={metaBB} style={style} />
</div>
<div
style={{
width: "1060px",
borderColor: "white",
borderStyle: "solid",
borderWidth: "5px",
}}
>
{joystick}
</div>
</>
);
}

@ -2598,12 +2598,7 @@ function augmentationExists(name: string): boolean {
export function isRepeatableAug(aug: Augmentation): boolean { export function isRepeatableAug(aug: Augmentation): boolean {
const augName = aug instanceof Augmentation ? aug.name : aug; const augName = aug instanceof Augmentation ? aug.name : aug;
return augName === AugmentationNames.NeuroFluxGovernor;
if (augName === AugmentationNames.NeuroFluxGovernor) {
return true;
}
return false;
} }
export { installAugmentations, initAugmentations, applyAugmentation, augmentationExists }; export { installAugmentations, initAugmentations, applyAugmentation, augmentationExists };

@ -8,8 +8,8 @@
import React, { useState } from "react"; import React, { useState } from "react";
import { AugmentationAccordion } from "../../ui/React/AugmentationAccordion"; import { AugmentationAccordion } from "../../ui/React/AugmentationAccordion";
import { Augmentations } from "../../Augmentation/Augmentations"; import { Augmentations } from "../Augmentations";
import { AugmentationNames } from "../../Augmentation/data/AugmentationNames"; import { AugmentationNames } from "../data/AugmentationNames";
import { Settings } from "../../Settings/Settings"; import { Settings } from "../../Settings/Settings";
import { use } from "../../ui/Context"; import { use } from "../../ui/Context";

@ -4,8 +4,8 @@
*/ */
import * as React from "react"; import * as React from "react";
import { Augmentations } from "../../Augmentation/Augmentations"; import { Augmentations } from "../Augmentations";
import { AugmentationNames } from "../../Augmentation/data/AugmentationNames"; import { AugmentationNames } from "../data/AugmentationNames";
import { Player } from "../../Player"; import { Player } from "../../Player";
import { AugmentationAccordion } from "../../ui/React/AugmentationAccordion"; import { AugmentationAccordion } from "../../ui/React/AugmentationAccordion";

@ -132,7 +132,7 @@ export function BitverseRoot(props: IProps): React.ReactElement {
const player = use.Player(); const player = use.Player();
const enter = enterBitNode; const enter = enterBitNode;
const destroyed = player.bitNodeN; const destroyed = player.bitNodeN;
const [destroySequence, setDestroySequence] = useState(true && !props.quick); const [destroySequence, setDestroySequence] = useState(!props.quick);
// Update NextSourceFileFlags // Update NextSourceFileFlags
const nextSourceFileFlags = SourceFileFlags.slice(); const nextSourceFileFlags = SourceFileFlags.slice();

@ -1914,6 +1914,9 @@ export class Bladeburner implements IBladeburner {
} }
process(router: IRouter, player: IPlayer): void { process(router: IRouter, player: IPlayer): void {
// Edge race condition when the engine checks the processing counters and attempts to route before the router is initialized.
if (!router.isInitialized) return;
// Edge case condition...if Operation Daedalus is complete trigger the BitNode // Edge case condition...if Operation Daedalus is complete trigger the BitNode
if (router.page() !== Page.BitVerse && this.blackops.hasOwnProperty("Operation Daedalus")) { if (router.page() !== Page.BitVerse && this.blackops.hasOwnProperty("Operation Daedalus")) {
return router.toBitVerse(false, false); return router.toBitVerse(false, false);

@ -22,7 +22,7 @@ export function OperationPage(props: IProps): React.ReactElement {
between different Operations. between different Operations.
<br /> <br />
<br /> <br />
For operations, you can use a team. You must first recruit team members. Having a larger team will improves your For operations, you can use a team. You must first recruit team members. Having a larger team will improve your
chances of success. chances of success.
<br /> <br />
<br /> <br />

@ -19,6 +19,9 @@ import { ResearchMap } from "./ResearchMap";
import { isRelevantMaterial } from "./ui/Helpers"; import { isRelevantMaterial } from "./ui/Helpers";
export function NewIndustry(corporation: ICorporation, industry: string, name: string): void { export function NewIndustry(corporation: ICorporation, industry: string, name: string): void {
if (corporation.divisions.find(({ type }) => industry == type))
throw new Error(`You have already expanded into the ${industry} industry!`);
for (let i = 0; i < corporation.divisions.length; ++i) { for (let i = 0; i < corporation.divisions.length; ++i) {
if (corporation.divisions[i].name === name) { if (corporation.divisions[i].name === name) {
throw new Error("This division name is already in use!"); throw new Error("This division name is already in use!");
@ -111,8 +114,8 @@ export function SellMaterial(mat: Material, amt: string, price: string): void {
if (amt.includes("MAX") || amt.includes("PROD")) { if (amt.includes("MAX") || amt.includes("PROD")) {
let q = amt.replace(/\s+/g, ""); let q = amt.replace(/\s+/g, "");
q = q.replace(/[^-()\d/*+.MAXPROD]/g, ""); q = q.replace(/[^-()\d/*+.MAXPROD]/g, "");
let tempQty = q.replace(/MAX/g, "1"); let tempQty = q.replace(/MAX/g, mat.maxsll.toString());
tempQty = tempQty.replace(/PROD/g, "1"); tempQty = tempQty.replace(/PROD/g, mat.prd.toString());
try { try {
tempQty = eval(tempQty); tempQty = eval(tempQty);
} catch (e) { } catch (e) {
@ -176,8 +179,8 @@ export function SellProduct(product: Product, city: string, amt: string, price:
//Dynamically evaluated quantity. First test to make sure its valid //Dynamically evaluated quantity. First test to make sure its valid
let qty = amt.replace(/\s+/g, ""); let qty = amt.replace(/\s+/g, "");
qty = qty.replace(/[^-()\d/*+.MAXPROD]/g, ""); qty = qty.replace(/[^-()\d/*+.MAXPROD]/g, "");
let temp = qty.replace(/MAX/g, "1"); let temp = qty.replace(/MAX/g, product.maxsll.toString());
temp = temp.replace(/PROD/g, "1"); temp = temp.replace(/PROD/g, product.data[city][1].toString());
try { try {
temp = eval(temp); temp = eval(temp);
} catch (e) { } catch (e) {
@ -291,7 +294,7 @@ export function BuyBackShares(corporation: ICorporation, player: IPlayer, numSha
if (numShares > corporation.issuedShares) throw new Error("You don't have that many shares to buy!"); if (numShares > corporation.issuedShares) throw new Error("You don't have that many shares to buy!");
if (!corporation.public) throw new Error("You haven't gone public!"); if (!corporation.public) throw new Error("You haven't gone public!");
const buybackPrice = corporation.sharePrice * 1.1; const buybackPrice = corporation.sharePrice * 1.1;
if (corporation.funds < (numShares * buybackPrice)) throw new Error("You cant afford that many shares!"); if (player.money < (numShares * buybackPrice)) throw new Error("You cant afford that many shares!");
corporation.numShares += numShares; corporation.numShares += numShares;
corporation.issuedShares -= numShares; corporation.issuedShares -= numShares;
player.loseMoney(numShares * buybackPrice, "corporation"); player.loseMoney(numShares * buybackPrice, "corporation");

@ -828,7 +828,7 @@ export class Industry implements IIndustry {
} }
} }
const maxSell = mat.maxsll =
(mat.qlt + 0.001) * (mat.qlt + 0.001) *
marketFactor * marketFactor *
markup * markup *
@ -839,7 +839,7 @@ export class Industry implements IIndustry {
let sellAmt; let sellAmt;
if (isString(mat.sllman[1])) { if (isString(mat.sllman[1])) {
//Dynamically evaluated //Dynamically evaluated
let tmp = (mat.sllman[1] as string).replace(/MAX/g, (maxSell + "").toUpperCase()); let tmp = (mat.sllman[1] as string).replace(/MAX/g, (mat.maxsll + "").toUpperCase());
tmp = tmp.replace(/PROD/g, mat.prd + ""); tmp = tmp.replace(/PROD/g, mat.prd + "");
try { try {
sellAmt = eval(tmp); sellAmt = eval(tmp);
@ -856,13 +856,13 @@ export class Industry implements IIndustry {
); );
sellAmt = 0; sellAmt = 0;
} }
sellAmt = Math.min(maxSell, sellAmt); sellAmt = Math.min(mat.maxsll, sellAmt);
} else if (mat.sllman[1] === -1) { } else if (mat.sllman[1] === -1) {
//Backwards compatibility, -1 = MAX //Backwards compatibility, -1 = MAX
sellAmt = maxSell; sellAmt = mat.maxsll;
} else { } else {
//Player's input value is just a number //Player's input value is just a number
sellAmt = Math.min(maxSell, mat.sllman[1] as number); sellAmt = Math.min(mat.maxsll, mat.sllman[1] as number);
} }
sellAmt = sellAmt * CorporationConstants.SecsPerMarketCycle * marketCycles; sellAmt = sellAmt * CorporationConstants.SecsPerMarketCycle * marketCycles;
@ -1188,8 +1188,7 @@ export class Industry implements IIndustry {
} }
} }
const maxSell = product.maxsll = 0.5 *
0.5 *
Math.pow(product.rat, 0.65) * Math.pow(product.rat, 0.65) *
marketFactor * marketFactor *
corporation.getSalesMultiplier() * corporation.getSalesMultiplier() *
@ -1200,7 +1199,7 @@ export class Industry implements IIndustry {
let sellAmt; let sellAmt;
if (product.sllman[city][0] && isString(product.sllman[city][1])) { if (product.sllman[city][0] && isString(product.sllman[city][1])) {
//Sell amount is dynamically evaluated //Sell amount is dynamically evaluated
let tmp = product.sllman[city][1].replace(/MAX/g, (maxSell + "").toUpperCase()); let tmp = product.sllman[city][1].replace(/MAX/g, (product.maxsll + "").toUpperCase());
tmp = tmp.replace(/PROD/g, product.data[city][1]); tmp = tmp.replace(/PROD/g, product.data[city][1]);
try { try {
tmp = eval(tmp); tmp = eval(tmp);
@ -1214,16 +1213,16 @@ export class Industry implements IIndustry {
city + city +
" office. Sell price is being set to MAX", " office. Sell price is being set to MAX",
); );
tmp = maxSell; tmp = product.maxsll;
} }
sellAmt = Math.min(maxSell, tmp); sellAmt = Math.min(product.maxsll, tmp);
} else if (product.sllman[city][0] && product.sllman[city][1] > 0) { } else if (product.sllman[city][0] && product.sllman[city][1] > 0) {
//Sell amount is manually limited //Sell amount is manually limited
sellAmt = Math.min(maxSell, product.sllman[city][1]); sellAmt = Math.min(product.maxsll, product.sllman[city][1]);
} else if (product.sllman[city][0] === false) { } else if (product.sllman[city][0] === false) {
sellAmt = 0; sellAmt = 0;
} else { } else {
sellAmt = maxSell; sellAmt = product.maxsll;
} }
if (sellAmt < 0) { if (sellAmt < 0) {
sellAmt = 0; sellAmt = 0;

@ -62,6 +62,9 @@ export class Material {
marketTa2 = false; marketTa2 = false;
marketTa2Price = 0; marketTa2Price = 0;
// Determines the maximum amount of this material that can be sold in one market cycle
maxsll = 0;
constructor(params: IConstructorParams = {}) { constructor(params: IConstructorParams = {}) {
if (params.name) { if (params.name) {
this.name = params.name; this.name = params.name;

@ -186,8 +186,7 @@ export class OfficeSpace {
jobCount--; jobCount--;
} }
} }
if (jobCount !== amount) return false; return jobCount === amount;
return true;
} }
toJSON(): any { toJSON(): any {

@ -96,6 +96,8 @@ export class Product {
marketTa2 = false; marketTa2 = false;
marketTa2Price: IMap<number> = createCityMap<number>(0); marketTa2Price: IMap<number> = createCityMap<number>(0);
// Determines the maximum amount of this product that can be sold in one market cycle
maxsll = 0;
constructor(params: IConstructorParams = {}) { constructor(params: IConstructorParams = {}) {
this.name = params.name ? params.name : ""; this.name = params.name ? params.name : "";
this.dmd = params.demand ? params.demand : 0; this.dmd = params.demand ? params.demand : 0;

@ -6,6 +6,7 @@ import { IIndustry } from "../IIndustry";
import { ExportMaterial } from "../Actions"; import { ExportMaterial } from "../Actions";
import { Modal } from "../../ui/React/Modal"; import { Modal } from "../../ui/React/Modal";
import { useCorporation } from "./Context"; import { useCorporation } from "./Context";
import { isRelevantMaterial } from "./Helpers";
import Typography from "@mui/material/Typography"; import Typography from "@mui/material/Typography";
import TextField from "@mui/material/TextField"; import TextField from "@mui/material/TextField";
import Button from "@mui/material/Button"; import Button from "@mui/material/Button";
@ -22,11 +23,13 @@ interface IProps {
// Create a popup that lets the player manage exports // Create a popup that lets the player manage exports
export function ExportModal(props: IProps): React.ReactElement { export function ExportModal(props: IProps): React.ReactElement {
const corp = useCorporation(); const corp = useCorporation();
if (corp.divisions.length === 0) throw new Error("Export popup created with no divisions."); const possibleDivisions = corp.divisions.filter((division: IIndustry) => isRelevantMaterial(props.mat.name, division));
if (Object.keys(corp.divisions[0].warehouses).length === 0) if (possibleDivisions.length === 0) throw new Error("Export popup created with no divisions.");
const defaultDivision = possibleDivisions[0];
if (Object.keys(defaultDivision.warehouses).length === 0)
throw new Error("Export popup created in a division with no warehouses."); throw new Error("Export popup created in a division with no warehouses.");
const [industry, setIndustry] = useState<string>(corp.divisions[0].name); const [industry, setIndustry] = useState<string>(defaultDivision.name);
const [city, setCity] = useState<string>(Object.keys(corp.divisions[0].warehouses)[0]); const [city, setCity] = useState<string>(Object.keys(defaultDivision.warehouses)[0]);
const [amt, setAmt] = useState(""); const [amt, setAmt] = useState("");
const setRerender = useState(false)[1]; const setRerender = useState(false)[1];
@ -84,7 +87,9 @@ export function ExportModal(props: IProps): React.ReactElement {
second. You can set the export amount to 'MAX' to export all of the materials in this warehouse. second. You can set the export amount to 'MAX' to export all of the materials in this warehouse.
</Typography> </Typography>
<Select onChange={onIndustryChange} value={industry}> <Select onChange={onIndustryChange} value={industry}>
{corp.divisions.map((division: IIndustry) => ( {corp.divisions
.filter((division: IIndustry) => isRelevantMaterial(props.mat.name, division))
.map((division: IIndustry) => (
<MenuItem key={division.name} value={division.name}> <MenuItem key={division.name} value={division.name}>
{division.name} {division.name}
</MenuItem> </MenuItem>

@ -4,7 +4,7 @@ import { IIndustry } from "../IIndustry";
// current industry. // current industry.
export function isRelevantMaterial(matName: string, division: IIndustry): boolean { export function isRelevantMaterial(matName: string, division: IIndustry): boolean {
// Materials that affect Production multiplier // Materials that affect Production multiplier
const prodMultiplierMats = ["Hardware", "Robots", "AICores", "RealEstate"]; const prodMultiplierMats = ["Hardware", "Robots", "AICores", "RealEstate", "AI Cores", "Real Estate"];
if (Object.keys(division.reqMats).includes(matName)) { if (Object.keys(division.reqMats).includes(matName)) {
return true; return true;

@ -95,8 +95,10 @@ function WarehouseRoot(props: IProps): React.ReactElement {
const mats = []; const mats = [];
for (const matName of Object.keys(props.warehouse.materials)) { for (const matName of Object.keys(props.warehouse.materials)) {
if (!(props.warehouse.materials[matName] instanceof Material)) continue; if (!(props.warehouse.materials[matName] instanceof Material)) continue;
// Only create UI for materials that are relevant for the industry // Only create UI for materials that are relevant for the industry or in stock
if (!isRelevantMaterial(matName, division)) continue; const isInStock = props.warehouse.materials[matName].qty > 0;
const isRelevant = isRelevantMaterial(matName, division);
if (!isInStock && !isRelevant) continue;
mats.push( mats.push(
<MaterialElem <MaterialElem
rerender={props.rerender} rerender={props.rerender}

@ -20,14 +20,7 @@ export function determineCrimeSuccess(p: IPlayer, type: string): boolean {
dialogBoxCreate(`ERR: Unrecognized crime type: ${type} This is probably a bug please contact the developer`); dialogBoxCreate(`ERR: Unrecognized crime type: ${type} This is probably a bug please contact the developer`);
return false; return false;
} }
return Math.random() <= chance;
if (Math.random() <= chance) {
//Success
return true;
} else {
//Failure
return false;
}
} }
export function findCrime(roughName: string): Crime | null { export function findCrime(roughName: string): Crime | null {

@ -6,8 +6,7 @@ export let LastExportBonus = 0;
const bonusTimer = 24 * 60 * 60 * 1000; // 24h const bonusTimer = 24 * 60 * 60 * 1000; // 24h
export function canGetBonus(): boolean { export function canGetBonus(): boolean {
const now = new Date().getTime(); const now = new Date().getTime();
if (now - LastExportBonus > bonusTimer) return true; return now - LastExportBonus > bonusTimer;
return false;
} }
export function onExport(p: IPlayer): void { export function onExport(p: IPlayer): void {

@ -7,7 +7,7 @@ import { PurchaseableAugmentation } from "./PurchaseableAugmentation";
import { Augmentations } from "../../Augmentation/Augmentations"; import { Augmentations } from "../../Augmentation/Augmentations";
import { AugmentationNames } from "../../Augmentation/data/AugmentationNames"; import { AugmentationNames } from "../../Augmentation/data/AugmentationNames";
import { Faction } from "../../Faction/Faction"; import { Faction } from "../Faction";
import { PurchaseAugmentationsOrderSetting } from "../../Settings/SettingEnums"; import { PurchaseAugmentationsOrderSetting } from "../../Settings/SettingEnums";
import { Settings } from "../../Settings/Settings"; import { Settings } from "../../Settings/Settings";
import { hasAugmentationPrereqs } from "../FactionHelpers"; import { hasAugmentationPrereqs } from "../FactionHelpers";

@ -4,7 +4,7 @@
import React, { useState } from "react"; import React, { useState } from "react";
import { CONSTANTS } from "../../Constants"; import { CONSTANTS } from "../../Constants";
import { Faction } from "../../Faction/Faction"; import { Faction } from "../Faction";
import { IPlayer } from "../../PersonObjects/IPlayer"; import { IPlayer } from "../../PersonObjects/IPlayer";
import { repFromDonation } from "../formulas/donation"; import { repFromDonation } from "../formulas/donation";
import { Favor } from "../../ui/React/Favor"; import { Favor } from "../../ui/React/Favor";

@ -13,7 +13,7 @@ import { Option } from "./Option";
import { CONSTANTS } from "../../Constants"; import { CONSTANTS } from "../../Constants";
import { BitNodeMultipliers } from "../../BitNode/BitNodeMultipliers"; import { BitNodeMultipliers } from "../../BitNode/BitNodeMultipliers";
import { Faction } from "../../Faction/Faction"; import { Faction } from "../Faction";
import { use } from "../../ui/Context"; import { use } from "../../ui/Context";
import { CreateGangModal } from "./CreateGangModal"; import { CreateGangModal } from "./CreateGangModal";
@ -24,6 +24,7 @@ import { CovenantPurchasesRoot } from "../../PersonObjects/Sleeve/ui/CovenantPur
type IProps = { type IProps = {
faction: Faction; faction: Faction;
augPage: boolean;
}; };
// Info text for all options on the UI // Info text for all options on the UI
@ -70,7 +71,6 @@ function MainPage({ faction, rerender, onAugmentations }: IMainProps): React.Rea
const router = use.Router(); const router = use.Router();
const [sleevesOpen, setSleevesOpen] = useState(false); const [sleevesOpen, setSleevesOpen] = useState(false);
const [gangOpen, setGangOpen] = useState(false); const [gangOpen, setGangOpen] = useState(false);
const p = player;
const factionInfo = faction.getInfo(); const factionInfo = faction.getInfo();
function manageGang(): void { function manageGang(): void {
@ -104,20 +104,20 @@ function MainPage({ faction, rerender, onAugmentations }: IMainProps): React.Rea
// We have a special flag for whether the player this faction is the player's // We have a special flag for whether the player this faction is the player's
// gang faction because if the player has a gang, they cannot do any other action // gang faction because if the player has a gang, they cannot do any other action
const isPlayersGang = p.inGang() && p.getGangName() === faction.name; const isPlayersGang = player.inGang() && player.getGangName() === faction.name;
// Flags for whether special options (gang, sleeve purchases, donate, etc.) // Flags for whether special options (gang, sleeve purchases, donate, etc.)
// should be shown // should be shown
const favorToDonate = Math.floor(CONSTANTS.BaseFavorToDonate * BitNodeMultipliers.RepToDonateToFaction); const favorToDonate = Math.floor(CONSTANTS.BaseFavorToDonate * BitNodeMultipliers.RepToDonateToFaction);
const canDonate = faction.favor >= favorToDonate; const canDonate = faction.favor >= favorToDonate;
const canPurchaseSleeves = faction.name === "The Covenant" && p.bitNodeN === 10; const canPurchaseSleeves = faction.name === "The Covenant" && player.bitNodeN === 10;
let canAccessGang = p.canAccessGang() && GangNames.includes(faction.name); let canAccessGang = player.canAccessGang() && GangNames.includes(faction.name);
if (p.inGang()) { if (player.inGang()) {
if (p.getGangName() !== faction.name) { if (player.getGangName() !== faction.name) {
canAccessGang = false; canAccessGang = false;
} else if (p.getGangName() === faction.name) { } else if (player.getGangName() === faction.name) {
canAccessGang = true; canAccessGang = true;
} }
} }
@ -174,6 +174,10 @@ function MainPage({ faction, rerender, onAugmentations }: IMainProps): React.Rea
export function FactionRoot(props: IProps): React.ReactElement { export function FactionRoot(props: IProps): React.ReactElement {
const setRerender = useState(false)[1]; const setRerender = useState(false)[1];
const player = use.Player();
const router = use.Router();
const [purchasingAugs, setPurchasingAugs] = useState(props.augPage);
function rerender(): void { function rerender(): void {
setRerender((old) => !old); setRerender((old) => !old);
} }
@ -185,7 +189,16 @@ export function FactionRoot(props: IProps): React.ReactElement {
const faction = props.faction; const faction = props.faction;
const [purchasingAugs, setPurchasingAugs] = useState(false); if (player && !player.factions.includes(faction.name)) {
return (
<>
<Typography variant="h4" color="primary">
You have not joined {faction.name} yet!
</Typography>
<Button onClick={() => router.toFactions()}>Back to Factions</Button>
</>
);
}
return purchasingAugs ? ( return purchasingAugs ? (
<AugmentationsPage faction={faction} routeToMainPage={() => setPurchasingAugs(false)} /> <AugmentationsPage faction={faction} routeToMainPage={() => setPurchasingAugs(false)} />

@ -41,6 +41,10 @@ export function FactionsRoot(props: IProps): React.ReactElement {
props.router.toFaction(faction); props.router.toFaction(faction);
} }
function openFactionAugPage(faction: Faction): void {
props.router.toFaction(faction, true);
}
function acceptInvitation(event: React.MouseEvent<HTMLButtonElement, MouseEvent>, faction: string): void { function acceptInvitation(event: React.MouseEvent<HTMLButtonElement, MouseEvent>, faction: string): void {
if (!event.isTrusted) return; if (!event.isTrusted) return;
joinFaction(Factions[faction]); joinFaction(Factions[faction]);
@ -61,7 +65,7 @@ export function FactionsRoot(props: IProps): React.ReactElement {
</Typography> </Typography>
{(props.player.factions.length > 0 && ( {(props.player.factions.length > 0 && (
<Paper sx={{ my: 1, p: 1, pb: 0, display: "inline-block" }}> <Paper sx={{ my: 1, p: 1, pb: 0, display: "inline-block" }}>
<Table padding="none"> <Table padding="none" style={{ width: "fit-content" }}>
<TableBody> <TableBody>
{props.player.factions.map((faction: string) => ( {props.player.factions.map((faction: string) => (
<TableRow key={faction}> <TableRow key={faction}>
@ -75,6 +79,17 @@ export function FactionsRoot(props: IProps): React.ReactElement {
<Button onClick={() => openFaction(Factions[faction])}>Details</Button> <Button onClick={() => openFaction(Factions[faction])}>Details</Button>
</Box> </Box>
</TableCell> </TableCell>
<TableCell align="right">
<Box ml={1} mb={1}>
<Button sx={{ width: '100%' }} onClick={() => openFactionAugPage(Factions[faction])}>
Augmentations Left: {Factions[faction]
.augmentations
.filter((augmentation: string) =>
!props.player.hasAugmentation(augmentation))
.length}
</Button>
</Box>
</TableCell>
</TableRow> </TableRow>
))} ))}
</TableBody> </TableBody>

@ -4,8 +4,8 @@
*/ */
import React, { useState, useEffect } from "react"; import React, { useState, useEffect } from "react";
import { Faction } from "../../Faction/Faction"; import { Faction } from "../Faction";
import { FactionInfo } from "../../Faction/FactionInfo"; import { FactionInfo } from "../FactionInfo";
import { Reputation } from "../../ui/React/Reputation"; import { Reputation } from "../../ui/React/Reputation";
import { Favor } from "../../ui/React/Favor"; import { Favor } from "../../ui/React/Favor";

@ -9,7 +9,7 @@ import { PurchaseAugmentationModal } from "./PurchaseAugmentationModal";
import { Augmentations } from "../../Augmentation/Augmentations"; import { Augmentations } from "../../Augmentation/Augmentations";
import { AugmentationNames } from "../../Augmentation/data/AugmentationNames"; import { AugmentationNames } from "../../Augmentation/data/AugmentationNames";
import { Faction } from "../../Faction/Faction"; import { Faction } from "../Faction";
import { IPlayer } from "../../PersonObjects/IPlayer"; import { IPlayer } from "../../PersonObjects/IPlayer";
import { Settings } from "../../Settings/Settings"; import { Settings } from "../../Settings/Settings";
import { Money } from "../../ui/React/Money"; import { Money } from "../../ui/React/Money";

@ -273,7 +273,7 @@ export function EquipmentsSubpage(): React.ReactElement {
sx={{ m: 1, width: '15%' }} sx={{ m: 1, width: '15%' }}
/> />
<Box display="grid" sx={{ gridTemplateColumns: '1fr 1fr', width: 'fit-content' }}> <Box display="grid" sx={{ gridTemplateColumns: '1fr 1fr', width: '100%' }}>
{members.map((member: GangMember) => ( {members.map((member: GangMember) => (
<GangMemberUpgradePanel key={member.name} member={member} /> <GangMemberUpgradePanel key={member.name} member={member} />
))} ))}

@ -127,10 +127,10 @@ Cities[CityName.NewTokyo].asciiArt = `
o o
\\ \\
\\ [defcomm] [arcade] E [defcomm]
\\ \\
o--x---A--x--o [travel agency] o--x---A--x--o [travel agency]
7 8 10 G 7 8 10 H
[vitalife] o 12 [global pharmaceuticals] [vitalife] o 12 [global pharmaceuticals]
| |
o--D-x----x-------x-C-+--------x--x-B-x---x-o o--D-x----x-------x-C-+--------x--x-B-x---x-o
@ -141,14 +141,14 @@ Cities[CityName.NewTokyo].asciiArt = `
\\ \\
[hospital] o 15 [world stock exchange] [hospital] o 15 [world stock exchange]
| |
o--x--E--x-----x-----x---+---x----x--H--x-o o--x--F--x-----x-----x---+---x----x--I--x-o
| |
| |
o 17 o 17
F [the slums] G [the slums]
`; `;
Cities[CityName.Sector12].asciiArt = ` Cities[CityName.Sector12].asciiArt = `
78 o 97 78 o 97

@ -54,6 +54,7 @@ export enum LocationName {
NewTokyoGlobalPharmaceuticals = "Global Pharmaceuticals", NewTokyoGlobalPharmaceuticals = "Global Pharmaceuticals",
NewTokyoNoodleBar = "Noodle Bar", NewTokyoNoodleBar = "Noodle Bar",
NewTokyoVitaLife = "VitaLife", NewTokyoVitaLife = "VitaLife",
NewTokyoArcade = "Arcade",
// Ishima // Ishima
IshimaNovaMedical = "Nova Medical", IshimaNovaMedical = "Nova Medical",

@ -215,6 +215,11 @@ export const LocationsMetadata: IConstructorParams[] = [
name: LocationName.NewTokyoVitaLife, name: LocationName.NewTokyoVitaLife,
types: [LocationType.Company, LocationType.Special], types: [LocationType.Company, LocationType.Special],
}, },
{
city: CityName.NewTokyo,
name: LocationName.NewTokyoArcade,
types: [LocationType.Special],
},
{ {
city: CityName.Sector12, city: CityName.Sector12,
infiltrationData: { infiltrationData: {

@ -34,10 +34,9 @@ const useStyles = makeStyles((theme: Theme) =>
padding: "0px", padding: "0px",
cursor: "pointer", cursor: "pointer",
}, },
}) }),
); );
function toLocation(router: IRouter, location: Location): void { function toLocation(router: IRouter, location: Location): void {
if (location.name === LocationName.TravelAgency) { if (location.name === LocationName.TravelAgency) {
router.toTravel(); router.toTravel();
@ -132,12 +131,14 @@ function ASCIICity(props: IProps): React.ReactElement {
const elems: JSX.Element[] = []; const elems: JSX.Element[] = [];
const lines = props.city.asciiArt.split("\n"); const lines = props.city.asciiArt.split("\n");
let i = 0;
for (const line of lines) { for (const line of lines) {
elems.push( elems.push(
<Typography key={line} sx={{ lineHeight: "1em", whiteSpace: "pre" }}> <Typography key={i} sx={{ lineHeight: "1em", whiteSpace: "pre" }}>
{lineElems(line)} {lineElems(line)}
</Typography>, </Typography>,
); );
i++;
} }
return <>{elems}</>; return <>{elems}</>;

@ -32,6 +32,7 @@ import { CorruptableText } from "../../ui/React/CorruptableText";
import { HacknetNode } from "../../Hacknet/HacknetNode"; import { HacknetNode } from "../../Hacknet/HacknetNode";
import { HacknetServer } from "../../Hacknet/HacknetServer"; import { HacknetServer } from "../../Hacknet/HacknetServer";
import { GetServer } from "../../Server/AllServers"; import { GetServer } from "../../Server/AllServers";
import { ArcadeRoot } from "../../Arcade/ui/ArcadeRoot";
type IProps = { type IProps = {
loc: Location; loc: Location;
@ -81,7 +82,12 @@ export function SpecialLocation(props: IProps): React.ReactElement {
return <></>; return <></>;
} }
const text = inBladeburner ? "Enter Bladeburner Headquarters" : "Apply to Bladeburner Division"; const text = inBladeburner ? "Enter Bladeburner Headquarters" : "Apply to Bladeburner Division";
return <><br/><Button onClick={handleBladeburner}>{text}</Button></>; return (
<>
<br />
<Button onClick={handleBladeburner}>{text}</Button>
</>
);
} }
function renderNoodleBar(): React.ReactElement { function renderNoodleBar(): React.ReactElement {
@ -311,6 +317,9 @@ export function SpecialLocation(props: IProps): React.ReactElement {
case LocationName.IshimaGlitch: { case LocationName.IshimaGlitch: {
return renderGlitch(); return renderGlitch();
} }
case LocationName.NewTokyoArcade: {
return <ArcadeRoot />;
}
default: default:
console.error(`Location ${props.loc.name} doesn't have any special properties`); console.error(`Location ${props.loc.name} doesn't have any special properties`);
return <></>; return <></>;

@ -59,6 +59,8 @@ export const RamCostConstants: IMap<number> = {
ScriptBladeburnerApiBaseRamCost: 4, ScriptBladeburnerApiBaseRamCost: 4,
ScriptStanekWidth: 0.4,
ScriptStanekHeight: 0.4,
ScriptStanekCharge: 0.4, ScriptStanekCharge: 0.4,
ScriptStanekFragmentDefinitions: 0, ScriptStanekFragmentDefinitions: 0,
ScriptStanekPlacedFragments: 5, ScriptStanekPlacedFragments: 5,
@ -354,6 +356,8 @@ export const RamCosts: IMap<any> = {
}, },
stanek: { stanek: {
width: RamCostConstants.ScriptStanekWidth,
height: RamCostConstants.ScriptStanekHeight,
charge: RamCostConstants.ScriptStanekCharge, charge: RamCostConstants.ScriptStanekCharge,
fragmentDefinitions: RamCostConstants.ScriptStanekFragmentDefinitions, fragmentDefinitions: RamCostConstants.ScriptStanekFragmentDefinitions,
activeFragments: RamCostConstants.ScriptStanekPlacedFragments, activeFragments: RamCostConstants.ScriptStanekPlacedFragments,

@ -60,8 +60,5 @@ export function isScriptErrorMessage(msg: string): boolean {
return false; return false;
} }
const splitMsg = msg.split("|DELIMITER|"); const splitMsg = msg.split("|DELIMITER|");
if (splitMsg.length != 4) { return splitMsg.length == 4;
return false;
}
return true;
} }

@ -692,8 +692,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
workerScript.log( workerScript.log(
"weaken", "weaken",
() => () =>
`'${server.hostname}' security level weakened to ${ `'${server.hostname}' security level weakened to ${server.hackDifficulty
server.hackDifficulty
}. Gained ${numeralWrapper.formatExp(expGain)} hacking exp (t=${numeralWrapper.formatThreads(threads)})`, }. Gained ${numeralWrapper.formatExp(expGain)} hacking exp (t=${numeralWrapper.formatThreads(threads)})`,
); );
workerScript.scriptRef.onlineExpGained += expGain; workerScript.scriptRef.onlineExpGained += expGain;
@ -807,7 +806,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
if (possibleLogs[fn] === undefined) { if (possibleLogs[fn] === undefined) {
throw makeRuntimeErrorMsg("isLogEnabled", `Invalid argument: ${fn}.`); throw makeRuntimeErrorMsg("isLogEnabled", `Invalid argument: ${fn}.`);
} }
return workerScript.disableLogs[fn] ? false : true; return !workerScript.disableLogs[fn];
}, },
getScriptLogs: function (fn: any, hostname: any, ...scriptArgs: any): any { getScriptLogs: function (fn: any, hostname: any, ...scriptArgs: any): any {
const runningScriptObj = getRunningScript(fn, hostname, "getScriptLogs", scriptArgs); const runningScriptObj = getRunningScript(fn, hostname, "getScriptLogs", scriptArgs);
@ -1590,10 +1589,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
} }
} }
const txtFile = getTextFile(filename, server); const txtFile = getTextFile(filename, server);
if (txtFile != null) { return txtFile != null;
return true;
}
return false;
}, },
isRunning: function (fn: any, hostname: any = workerScript.hostname, ...scriptArgs: any): any { isRunning: function (fn: any, hostname: any = workerScript.hostname, ...scriptArgs: any): any {
updateDynamicRam("isRunning", getRamCost(Player, "isRunning")); updateDynamicRam("isRunning", getRamCost(Player, "isRunning"));
@ -1628,6 +1624,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
return cost; return cost;
}, },
purchaseServer: function (aname: any, aram: any): any { purchaseServer: function (aname: any, aram: any): any {
if (arguments.length !== 2) throw makeRuntimeErrorMsg("purchaseServer", "Takes 2 arguments");
const name = helper.string("purchaseServer", "name", aname); const name = helper.string("purchaseServer", "name", aname);
const ram = helper.number("purchaseServer", "ram", aram); const ram = helper.number("purchaseServer", "ram", aram);
updateDynamicRam("purchaseServer", getRamCost(Player, "purchaseServer")); updateDynamicRam("purchaseServer", getRamCost(Player, "purchaseServer"));
@ -1836,6 +1833,12 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}, },
tryWritePort: function (port: any, data: any = ""): any { tryWritePort: function (port: any, data: any = ""): any {
updateDynamicRam("tryWritePort", getRamCost(Player, "tryWritePort")); updateDynamicRam("tryWritePort", getRamCost(Player, "tryWritePort"));
if (typeof data !== "string" && typeof data !== "number") {
throw makeRuntimeErrorMsg(
"tryWritePort",
`Trying to write invalid data to a port: only strings and numbers are valid.`,
);
}
if (!isNaN(port)) { if (!isNaN(port)) {
port = Math.round(port); port = Math.round(port);
if (port < 1 || port > CONSTANTS.NumNetscriptPorts) { if (port < 1 || port > CONSTANTS.NumNetscriptPorts) {

@ -23,9 +23,13 @@ export function NetscriptStanek(player: IPlayer, workerScript: WorkerScript, hel
return { return {
width: function (): number { width: function (): number {
helper.updateDynamicRam("width", getRamCost(player, "stanek", "width"));
checkStanekAPIAccess("width");
return staneksGift.width(); return staneksGift.width();
}, },
height: function (): number { height: function (): number {
helper.updateDynamicRam("height", getRamCost(player, "stanek", "height"));
checkStanekAPIAccess("height");
return staneksGift.height(); return staneksGift.height();
}, },
charge: function (arootX: unknown, arootY: unknown): Promise<void> { charge: function (arootX: unknown, arootY: unknown): Promise<void> {

@ -25,7 +25,7 @@ import { Cities } from "../../Locations/Cities";
import { Locations } from "../../Locations/Locations"; import { Locations } from "../../Locations/Locations";
import { CityName } from "../../Locations/data/CityNames"; import { CityName } from "../../Locations/data/CityNames";
import { LocationName } from "../../Locations/data/LocationNames"; import { LocationName } from "../../Locations/data/LocationNames";
import { Sleeve } from "../../PersonObjects/Sleeve/Sleeve"; import { Sleeve } from "../Sleeve/Sleeve";
import { import {
calculateSkill as calculateSkillF, calculateSkill as calculateSkillF,
calculateSkillProgress as calculateSkillProgressF, calculateSkillProgress as calculateSkillProgressF,
@ -590,7 +590,7 @@ export function process(this: IPlayer, router: IRouter, numCycles = 1): void {
if (this.isWorking) { if (this.isWorking) {
if (this.workType == CONSTANTS.WorkTypeFaction) { if (this.workType == CONSTANTS.WorkTypeFaction) {
if (this.workForFaction(numCycles)) { if (this.workForFaction(numCycles)) {
router.toFaction(); router.toFaction(Factions[this.currentWorkFactionName]);
} }
} else if (this.workType == CONSTANTS.WorkTypeCreateProgram) { } else if (this.workType == CONSTANTS.WorkTypeCreateProgram) {
if (this.createProgramWork(numCycles)) { if (this.createProgramWork(numCycles)) {
@ -933,6 +933,8 @@ export function startFactionSecurityWork(this: IPlayer, faction: Faction): void
export function workForFaction(this: IPlayer, numCycles: number): boolean { export function workForFaction(this: IPlayer, numCycles: number): boolean {
const faction = Factions[this.currentWorkFactionName]; const faction = Factions[this.currentWorkFactionName];
if (!faction) { return false; }
//Constantly update the rep gain rate //Constantly update the rep gain rate
switch (this.factionWorkType) { switch (this.factionWorkType) {
case CONSTANTS.FactionWorkHacking: case CONSTANTS.FactionWorkHacking:
@ -2002,18 +2004,13 @@ export function isQualified(this: IPlayer, company: Company, position: CompanyPo
const reqAgility = position.requiredDexterity > 0 ? position.requiredDexterity + offset : 0; const reqAgility = position.requiredDexterity > 0 ? position.requiredDexterity + offset : 0;
const reqCharisma = position.requiredCharisma > 0 ? position.requiredCharisma + offset : 0; const reqCharisma = position.requiredCharisma > 0 ? position.requiredCharisma + offset : 0;
if ( return this.hacking >= reqHacking &&
this.hacking >= reqHacking &&
this.strength >= reqStrength && this.strength >= reqStrength &&
this.defense >= reqDefense && this.defense >= reqDefense &&
this.dexterity >= reqDexterity && this.dexterity >= reqDexterity &&
this.agility >= reqAgility && this.agility >= reqAgility &&
this.charisma >= reqCharisma && this.charisma >= reqCharisma &&
company.playerReputation >= position.requiredReputation company.playerReputation >= position.requiredReputation;
) {
return true;
}
return false;
} }
/********** Reapplying Augmentations and Source File ***********/ /********** Reapplying Augmentations and Source File ***********/
@ -2571,7 +2568,7 @@ export function queueAugmentation(this: IPlayer, name: string): void {
/************* Coding Contracts **************/ /************* Coding Contracts **************/
export function gainCodingContractReward(this: IPlayer, reward: ICodingContractReward, difficulty = 1): string { export function gainCodingContractReward(this: IPlayer, reward: ICodingContractReward, difficulty = 1): string {
if (reward == null || reward.type == null || reward == null) { if (reward == null || reward.type == null) {
return `No reward for this contract`; return `No reward for this contract`;
} }

@ -859,10 +859,8 @@ export class Sleeve extends Person {
* Returns boolean indicating success * Returns boolean indicating success
*/ */
workForFaction(p: IPlayer, factionName: string, workType: string): boolean { workForFaction(p: IPlayer, factionName: string, workType: string): boolean {
if (factionName === "") { const faction = Factions[factionName]
return false; if (factionName === "" || !faction || !(faction instanceof Faction) || !p.factions.includes(factionName)) {
}
if (!(Factions[factionName] instanceof Faction) || !p.factions.includes(factionName)) {
return false; return false;
} }
@ -872,7 +870,7 @@ export class Sleeve extends Person {
this.resetTaskStatus(); this.resetTaskStatus();
} }
const factionInfo = Factions[factionName].getInfo(); const factionInfo = faction.getInfo();
// Set type of work (hacking/field/security), and the experience gains // Set type of work (hacking/field/security), and the experience gains
const sanitizedWorkType: string = workType.toLowerCase(); const sanitizedWorkType: string = workType.toLowerCase();

@ -17,10 +17,10 @@ import { Money } from "../../../ui/React/Money";
import { MoneyRate } from "../../../ui/React/MoneyRate"; import { MoneyRate } from "../../../ui/React/MoneyRate";
import { use } from "../../../ui/Context"; import { use } from "../../../ui/Context";
import { ReputationRate } from "../../../ui/React/ReputationRate"; import { ReputationRate } from "../../../ui/React/ReputationRate";
import { StatsElement } from "../ui/StatsElement"; import { StatsElement } from "./StatsElement";
import { MoreStatsModal } from "./MoreStatsModal"; import { MoreStatsModal } from "./MoreStatsModal";
import { MoreEarningsModal } from "../ui/MoreEarningsModal"; import { MoreEarningsModal } from "./MoreEarningsModal";
import { TaskSelector } from "../ui/TaskSelector"; import { TaskSelector } from "./TaskSelector";
import { FactionWorkType } from "../../../Faction/FactionWorkTypeEnum"; import { FactionWorkType } from "../../../Faction/FactionWorkTypeEnum";
import { StatsTable } from "../../../ui/React/StatsTable"; import { StatsTable } from "../../../ui/React/StatsTable";

@ -75,7 +75,10 @@ function possibleFactions(player: IPlayer, sleeve: Sleeve): string[] {
} }
} }
return factions; return factions.filter(faction => {
const facInfo = Factions[faction].getInfo();
return facInfo.offerHackingWork || facInfo.offerFieldWork || facInfo.offerSecurityWork
});
} }
const tasks: { const tasks: {

@ -161,7 +161,7 @@ class BitburnerSaveObject {
return reject(new Error("Error importing file")); return reject(new Error("Error importing file"));
} }
const result = target.result; const result = target.result;
if (typeof result !== "string" || result === null) { if (typeof result !== "string") {
return reject(new Error("FileReader event was not type string")); return reject(new Error("FileReader event was not type string"));
} }
const contents = result; const contents = result;

@ -11,7 +11,7 @@ import acorn, { parse } from "acorn";
import { RamCalculationErrorCode } from "./RamCalculationErrorCodes"; import { RamCalculationErrorCode } from "./RamCalculationErrorCodes";
import { RamCosts, RamCostConstants } from "../Netscript/RamCostGenerator"; import { RamCosts, RamCostConstants } from "../Netscript/RamCostGenerator";
import { Script } from "../Script/Script"; import { Script } from "./Script";
import { WorkerScript } from "../Netscript/WorkerScript"; import { WorkerScript } from "../Netscript/WorkerScript";
import { areImportsEquals } from "../Terminal/DirectoryHelpers"; import { areImportsEquals } from "../Terminal/DirectoryHelpers";
import { IPlayer } from "../PersonObjects/IPlayer"; import { IPlayer } from "../PersonObjects/IPlayer";

@ -2,7 +2,7 @@ import { CONSTANTS } from "../Constants";
import { Player } from "../Player"; import { Player } from "../Player";
import { BaseServer } from "../Server/BaseServer"; import { BaseServer } from "../Server/BaseServer";
import { Server } from "../Server/Server"; import { Server } from "../Server/Server";
import { RunningScript } from "../Script/RunningScript"; import { RunningScript } from "./RunningScript";
import { processSingleServerGrowth } from "../Server/ServerHelpers"; import { processSingleServerGrowth } from "../Server/ServerHelpers";
import { GetServer } from "../Server/AllServers"; import { GetServer } from "../Server/AllServers";

@ -535,6 +535,8 @@ export interface BitNodeMultipliers {
CompanyWorkExpGain: number; CompanyWorkExpGain: number;
/** Influences how much money the player earns when completing working their job. */ /** Influences how much money the player earns when completing working their job. */
CompanyWorkMoney: number; CompanyWorkMoney: number;
/** Influences the money gain from dividends of corporations created by the player. */
CorporationSoftCap: number;
/** Influences the valuation of corporations created by the player. */ /** Influences the valuation of corporations created by the player. */
CorporationValuation: number; CorporationValuation: number;
/** Influences the base experience gained for each ability when the player commits a crime. */ /** Influences the base experience gained for each ability when the player commits a crime. */
@ -5650,7 +5652,7 @@ export interface NS extends Singularity {
* @param data - Data to write. * @param data - Data to write.
* @returns True if the data is successfully written to the port, and false otherwise. * @returns True if the data is successfully written to the port, and false otherwise.
*/ */
tryWritePort(port: number, data: string[] | number): Promise<boolean>; tryWritePort(port: number, data: string | number): Promise<boolean>;
/** /**
* Read content of a file. * Read content of a file.
@ -6902,3 +6904,14 @@ interface GameInfo {
commit: string; commit: string;
platform: string; platform: string;
} }
/**
* Used for autocompletion
* @public
*/
interface AutocompleteData {
servers: string[];
scripts: string[];
txts: string[];
flags(schema: [string, string | number | boolean | string[]][]): any;
}

@ -32,8 +32,8 @@ import Typography from "@mui/material/Typography";
import Link from "@mui/material/Link"; import Link from "@mui/material/Link";
import Box from "@mui/material/Box"; import Box from "@mui/material/Box";
import SettingsIcon from "@mui/icons-material/Settings"; import SettingsIcon from "@mui/icons-material/Settings";
import SyncIcon from '@mui/icons-material/Sync'; import SyncIcon from "@mui/icons-material/Sync";
import CloseIcon from '@mui/icons-material/Close'; import CloseIcon from "@mui/icons-material/Close";
import Table from "@mui/material/Table"; import Table from "@mui/material/Table";
import TableCell from "@mui/material/TableCell"; import TableCell from "@mui/material/TableCell";
import TableRow from "@mui/material/TableRow"; import TableRow from "@mui/material/TableRow";
@ -133,13 +133,12 @@ export function Root(props: IProps): React.ReactElement {
// Prevent Crash if script is open on deleted server // Prevent Crash if script is open on deleted server
openScripts = openScripts.filter((script) => { openScripts = openScripts.filter((script) => {
return GetServer(script.hostname) !== null; return GetServer(script.hostname) !== null;
}) });
if (currentScript && (GetServer(currentScript.hostname) === null)) { if (currentScript && GetServer(currentScript.hostname) === null) {
currentScript = openScripts[0]; currentScript = openScripts[0];
if (currentScript === undefined) currentScript = null; if (currentScript === undefined) currentScript = null;
} }
const [dimensions, setDimensions] = useState({ const [dimensions, setDimensions] = useState({
height: window.innerHeight, height: window.innerHeight,
width: window.innerWidth, width: window.innerWidth,
@ -205,6 +204,32 @@ export function Root(props: IProps): React.ReactElement {
save(); save();
props.router.toTerminal(); props.router.toTerminal();
}); });
// Setup "go to next tab" and "go to previous tab". This is a little more involved
// since these aren't Ex commands (they run in normal mode, not after typing `:`)
MonacoVim.VimMode.Vim.defineAction("nextTabs", function (_cm: any, args: { repeat?: number }) {
const nTabs = args.repeat ?? 1;
// Go to the next tab (to the right). Wraps around when at the rightmost tab
const currIndex = currentTabIndex();
if (currIndex !== undefined) {
const nextIndex = (currIndex + nTabs) % openScripts.length;
onTabClick(nextIndex);
}
});
MonacoVim.VimMode.Vim.defineAction("prevTabs", function (_cm: any, args: { repeat?: number }) {
const nTabs = args.repeat ?? 1;
// Go to the previous tab (to the left). Wraps around when at the leftmost tab
const currIndex = currentTabIndex();
if (currIndex !== undefined) {
let nextIndex = currIndex - nTabs;
while (nextIndex < 0) {
nextIndex += openScripts.length;
}
onTabClick(nextIndex);
}
});
MonacoVim.VimMode.Vim.mapCommand("gt", "action", "nextTabs", {}, { context: "normal" });
MonacoVim.VimMode.Vim.mapCommand("gT", "action", "prevTabs", {}, { context: "normal" });
editor.focus(); editor.focus();
}); });
} catch {} } catch {}
@ -316,13 +341,18 @@ export function Root(props: IProps): React.ReactElement {
.loader(); .loader();
// replaced the bare tokens with regexes surrounded by \b, e.g. \b{token}\b which matches a word-break on either side // replaced the bare tokens with regexes surrounded by \b, e.g. \b{token}\b which matches a word-break on either side
// this prevents the highlighter from highlighting pieces of variables that start with a reserved token name // this prevents the highlighter from highlighting pieces of variables that start with a reserved token name
l.language.tokenizer.root.unshift([new RegExp('\\bns\\b'), { token: "ns" }]); l.language.tokenizer.root.unshift([new RegExp("\\bns\\b"), { token: "ns" }]);
for (const symbol of symbols) l.language.tokenizer.root.unshift([new RegExp(`\\b${symbol}\\b`), { token: "netscriptfunction" }]); for (const symbol of symbols)
l.language.tokenizer.root.unshift([new RegExp(`\\b${symbol}\\b`), { token: "netscriptfunction" }]);
const otherKeywords = ["let", "const", "var", "function"]; const otherKeywords = ["let", "const", "var", "function"];
const otherKeyvars = ["true", "false", "null", "undefined"]; const otherKeyvars = ["true", "false", "null", "undefined"];
otherKeywords.forEach((k) => l.language.tokenizer.root.unshift([new RegExp(`\\b${k}\\b`), { token: "otherkeywords" }])); otherKeywords.forEach((k) =>
otherKeyvars.forEach((k) => l.language.tokenizer.root.unshift([new RegExp(`\\b${k}\\b`), { token: "otherkeyvars" }])); l.language.tokenizer.root.unshift([new RegExp(`\\b${k}\\b`), { token: "otherkeywords" }]),
l.language.tokenizer.root.unshift([new RegExp('\\bthis\\b'), { token: "this" }]); );
otherKeyvars.forEach((k) =>
l.language.tokenizer.root.unshift([new RegExp(`\\b${k}\\b`), { token: "otherkeyvars" }]),
);
l.language.tokenizer.root.unshift([new RegExp("\\bthis\\b"), { token: "this" }]);
})(); })();
const source = (libSource + "").replace(/export /g, ""); const source = (libSource + "").replace(/export /g, "");
@ -604,17 +634,27 @@ export function Root(props: IProps): React.ReactElement {
openScripts = items; openScripts = items;
} }
function onTabClick(index: number): void { function currentTabIndex(): number | undefined {
if (currentScript !== null) { if (currentScript !== null) {
// Save currentScript to openScripts return openScripts.findIndex(
const curIndex = openScripts.findIndex(
(script) => (script) =>
currentScript !== null && currentScript !== null &&
script.fileName === currentScript.fileName && script.fileName === currentScript.fileName &&
script.hostname === currentScript.hostname, script.hostname === currentScript.hostname,
); );
}
return undefined;
}
function onTabClick(index: number): void {
if (currentScript !== null) {
// Save currentScript to openScripts
const curIndex = currentTabIndex();
if (curIndex !== undefined) {
openScripts[curIndex] = currentScript; openScripts[curIndex] = currentScript;
} }
}
currentScript = { ...openScripts[index] }; currentScript = { ...openScripts[index] };
@ -701,15 +741,17 @@ export function Root(props: IProps): React.ReactElement {
if (openScript.code !== serverScriptCode) { if (openScript.code !== serverScriptCode) {
PromptEvent.emit({ PromptEvent.emit({
txt: "Do you want to overwrite the current editor content with the contents of " + txt:
openScript.fileName + " on the server? This cannot be undone.", "Do you want to overwrite the current editor content with the contents of " +
openScript.fileName +
" on the server? This cannot be undone.",
resolve: (result: boolean) => { resolve: (result: boolean) => {
if (result) { if (result) {
// Save changes // Save changes
openScript.code = serverScriptCode; openScript.code = serverScriptCode;
// Switch to target tab // Switch to target tab
onTabClick(index) onTabClick(index);
if (editorRef.current !== null && openScript !== null) { if (editorRef.current !== null && openScript !== null) {
if (openScript.model === undefined || openScript.model.isDisposed()) { if (openScript.model === undefined || openScript.model.isDisposed()) {
@ -753,11 +795,11 @@ export function Root(props: IProps): React.ReactElement {
// 44px bottom tool bar + 16px margin // 44px bottom tool bar + 16px margin
// + vim bar 34px // + vim bar 34px
const editorHeight = dimensions.height - (130 + (options.vim ? 34 : 0)); const editorHeight = dimensions.height - (130 + (options.vim ? 34 : 0));
const tabsMaxWidth = 1640 const tabsMaxWidth = 1640;
const tabMargin = 5 const tabMargin = 5;
const tabMaxWidth = openScripts.length ? (tabsMaxWidth / openScripts.length) - tabMargin : 0 const tabMaxWidth = openScripts.length ? tabsMaxWidth / openScripts.length - tabMargin : 0;
const tabIconWidth = 25 const tabIconWidth = 25;
const tabTextWidth = tabMaxWidth - (tabIconWidth * 2) const tabTextWidth = tabMaxWidth - tabIconWidth * 2;
return ( return (
<> <>
<div style={{ display: currentScript !== null ? "block" : "none", height: "100%", width: "100%" }}> <div style={{ display: currentScript !== null ? "block" : "none", height: "100%", width: "100%" }}>
@ -783,20 +825,22 @@ export function Root(props: IProps): React.ReactElement {
const iconButtonStyle = { const iconButtonStyle = {
maxWidth: `${tabIconWidth}px`, maxWidth: `${tabIconWidth}px`,
minWidth: `${tabIconWidth}px`, minWidth: `${tabIconWidth}px`,
minHeight: '38.5px', minHeight: "38.5px",
maxHeight: '38.5px', maxHeight: "38.5px",
...(currentScript?.fileName === openScripts[index].fileName ? { ...(currentScript?.fileName === openScripts[index].fileName
? {
background: Settings.theme.button, background: Settings.theme.button,
borderColor: Settings.theme.button, borderColor: Settings.theme.button,
color: Settings.theme.primary color: Settings.theme.primary,
} : { }
: {
background: Settings.theme.backgroundsecondary, background: Settings.theme.backgroundsecondary,
borderColor: Settings.theme.backgroundsecondary, borderColor: Settings.theme.backgroundsecondary,
color: Settings.theme.secondary color: Settings.theme.secondary,
}) }),
}; };
const scriptTabText = `${hostname}:~/${fileName} ${dirty(index)}` const scriptTabText = `${hostname}:~/${fileName} ${dirty(index)}`;
return ( return (
<Draggable <Draggable
key={fileName + hostname} key={fileName + hostname}
@ -811,51 +855,52 @@ export function Root(props: IProps): React.ReactElement {
{...provided.dragHandleProps} {...provided.dragHandleProps}
style={{ style={{
...provided.draggableProps.style, ...provided.draggableProps.style,
minWidth: '200px',
maxWidth: `${tabMaxWidth}px`, maxWidth: `${tabMaxWidth}px`,
marginRight: `${tabMargin}px`, marginRight: `${tabMargin}px`,
flexShrink: 0, flexShrink: 0,
border: '1px solid ' + Settings.theme.well, border: "1px solid " + Settings.theme.well,
}} }}
> >
<Tooltip title={scriptTabText}> <Tooltip title={scriptTabText}>
<Button <Button
onClick={() => onTabClick(index)} onClick={() => onTabClick(index)}
onMouseDown={e => { onMouseDown={(e) => {
e.preventDefault(); e.preventDefault();
if (e.button === 1) onTabClose(index); if (e.button === 1) onTabClose(index);
}} }}
style={{ style={{
maxWidth: `${tabTextWidth}px`, maxWidth: `${tabTextWidth}px`,
overflow: "hidden", overflow: "hidden",
...(currentScript?.fileName === openScripts[index].fileName ? { ...(currentScript?.fileName === openScripts[index].fileName
? {
background: Settings.theme.button, background: Settings.theme.button,
borderColor: Settings.theme.button, borderColor: Settings.theme.button,
color: Settings.theme.primary color: Settings.theme.primary,
} : { }
: {
background: Settings.theme.backgroundsecondary, background: Settings.theme.backgroundsecondary,
borderColor: Settings.theme.backgroundsecondary, borderColor: Settings.theme.backgroundsecondary,
color: Settings.theme.secondary color: Settings.theme.secondary,
}) }),
}} }}
> >
<span style={{ overflow: 'hidden', direction: 'rtl', textOverflow: "ellipsis" }}> <span style={{ overflow: "hidden", direction: "rtl", textOverflow: "ellipsis" }}>
{scriptTabText} {scriptTabText}
</span> </span>
</Button> </Button>
</Tooltip> </Tooltip>
<Tooltip title="Overwrite editor content with saved file content"> <Tooltip title="Overwrite editor content with saved file content">
<Button onClick={() => onTabUpdate(index)} style={iconButtonStyle}> <Button onClick={() => onTabUpdate(index)} style={iconButtonStyle}>
<SyncIcon fontSize='small' /> <SyncIcon fontSize="small" />
</Button> </Button>
</Tooltip> </Tooltip>
<Button onClick={() => onTabClose(index)} style={iconButtonStyle}> <Button onClick={() => onTabClose(index)} style={iconButtonStyle}>
<CloseIcon fontSize='small' /> <CloseIcon fontSize="small" />
</Button> </Button>
</div> </div>
)} )}
</Draggable> </Draggable>
) );
})} })}
{provided.placeholder} {provided.placeholder}
</Box> </Box>
@ -885,14 +930,24 @@ export function Root(props: IProps): React.ReactElement {
></Box> ></Box>
<Box display="flex" flexDirection="row" sx={{ m: 1 }} alignItems="center"> <Box display="flex" flexDirection="row" sx={{ m: 1 }} alignItems="center">
<Button startIcon={<SettingsIcon />} onClick={() => setOptionsOpen(true)} sx={{ mr: 1 }}>Options</Button> <Button startIcon={<SettingsIcon />} onClick={() => setOptionsOpen(true)} sx={{ mr: 1 }}>
Options
</Button>
<Button onClick={beautify}>Beautify</Button> <Button onClick={beautify}>Beautify</Button>
<Button color={updatingRam ? "secondary" : "primary"} sx={{ mx: 1 }} onClick={() => { setRamInfoOpen(true) }}> <Button
color={updatingRam ? "secondary" : "primary"}
sx={{ mx: 1 }}
onClick={() => {
setRamInfoOpen(true);
}}
>
{ram} {ram}
</Button> </Button>
<Button onClick={save}>Save (Ctrl/Cmd + s)</Button> <Button onClick={save}>Save (Ctrl/Cmd + s)</Button>
<Button onClick={props.router.toTerminal}>Close (Ctrl/Cmd + b)</Button> <Button sx={{ mx: 1 }} onClick={props.router.toTerminal}>
<Typography sx={{ mx: 1 }}> Terminal (Ctrl/Cmd + b)
</Button>
<Typography>
{" "} {" "}
Documentation:{" "} Documentation:{" "}
<Link target="_blank" href="https://bitburner.readthedocs.io/en/latest/index.html"> <Link target="_blank" href="https://bitburner.readthedocs.io/en/latest/index.html">
@ -930,7 +985,9 @@ export function Root(props: IProps): React.ReactElement {
<React.Fragment key={n + r}> <React.Fragment key={n + r}>
<TableRow> <TableRow>
<TableCell sx={{ color: Settings.theme.primary }}>{n}</TableCell> <TableCell sx={{ color: Settings.theme.primary }}>{n}</TableCell>
<TableCell align="right" sx={{ color: Settings.theme.primary }}>{r}</TableCell> <TableCell align="right" sx={{ color: Settings.theme.primary }}>
{r}
</TableCell>
</TableRow> </TableRow>
</React.Fragment> </React.Fragment>
))} ))}

@ -14,7 +14,7 @@ import { WorkerScript } from "../Netscript/WorkerScript";
import { IMap } from "../types"; import { IMap } from "../types";
import { EventEmitter } from "../utils/EventEmitter"; import { EventEmitter } from "../utils/EventEmitter";
import { numeralWrapper } from ".././ui/numeralFormat"; import { numeralWrapper } from "../ui/numeralFormat";
import { dialogBoxCreate } from "../ui/React/DialogBox"; import { dialogBoxCreate } from "../ui/React/DialogBox";
import { Reviver } from "../utils/JSONReviver"; import { Reviver } from "../utils/JSONReviver";

@ -17,7 +17,7 @@ export function expr(
const expr = args.join(""); const expr = args.join("");
// Sanitize the math expression // Sanitize the math expression
const sanitizedExpr = expr.replace(/s+/g, "").replace(/[^-()\d/*+.]/g, ""); const sanitizedExpr = expr.replace(/s+/g, "").replace(/[^-()\d/*+.%]/g, "");
let result; let result;
try { try {
result = eval(sanitizedExpr); result = eval(sanitizedExpr);

@ -5,7 +5,7 @@ import { toString } from "lodash";
import React from "react"; import React from "react";
import { IPlayer } from "../../PersonObjects/IPlayer"; import { IPlayer } from "../../PersonObjects/IPlayer";
import { BaseServer } from "../../Server/BaseServer"; import { BaseServer } from "../../Server/BaseServer";
import { evaluateDirectoryPath, getFirstParentDirectory, isValidDirectoryPath } from "../../Terminal/DirectoryHelpers"; import { evaluateDirectoryPath, getFirstParentDirectory, isValidDirectoryPath } from "../DirectoryHelpers";
import { IRouter } from "../../ui/Router"; import { IRouter } from "../../ui/Router";
import { ITerminal } from "../ITerminal"; import { ITerminal } from "../ITerminal";

@ -10,6 +10,7 @@ import { HelpTexts } from "./HelpText";
import { isScriptFilename } from "../Script/isScriptFilename"; import { isScriptFilename } from "../Script/isScriptFilename";
import { compile } from "../NetscriptJSEvaluator"; import { compile } from "../NetscriptJSEvaluator";
import { Flags } from "../NetscriptFunctions/Flags"; import { Flags } from "../NetscriptFunctions/Flags";
import { AutocompleteData } from "../ScriptEditor/NetscriptDefinitions";
import * as libarg from "arg"; import * as libarg from "arg";
// An array of all Terminal commands // An array of all Terminal commands
@ -298,11 +299,7 @@ export async function determineAllPossibilitiesForTabCompletion(
argv: command.slice(2), argv: command.slice(2),
}); });
const flagFunc = Flags(flags._); const flagFunc = Flags(flags._);
let pos: string[] = []; const autocompleteData: AutocompleteData = {
let pos2: string[] = [];
pos = pos.concat(
loadedModule.autocomplete(
{
servers: GetAllServers().map((server) => server.hostname), servers: GetAllServers().map((server) => server.hostname),
scripts: currServ.scripts.map((script) => script.filename), scripts: currServ.scripts.map((script) => script.filename),
txts: currServ.textFiles.map((txt) => txt.fn), txts: currServ.textFiles.map((txt) => txt.fn),
@ -317,7 +314,12 @@ export async function determineAllPossibilitiesForTabCompletion(
return undefined; return undefined;
} }
}, },
}, }
let pos: string[] = [];
let pos2: string[] = [];
pos = pos.concat(
loadedModule.autocomplete(
autocompleteData,
flags._, flags._,
), ),
); );

@ -307,15 +307,7 @@ export const codingContractTypesMetadata: ICodingContractTypeMetadata[] = [
reach = Math.max(i + data[i], reach); reach = Math.max(i + data[i], reach);
} }
const solution: boolean = i === n; const solution: boolean = i === n;
return (ans === "1" && solution) || (ans === "0" && !solution);
if (ans === "1" && solution) {
return true;
}
if (ans === "0" && !solution) {
return true;
}
return false;
}, },
}, },
{ {

@ -401,9 +401,12 @@ const Engine: {
() => () =>
AlertEvents.emit( AlertEvents.emit(
<> <>
Offline for {timeOfflineString}. While you were offline, your scripts generated{" "} Offline for {timeOfflineString}. While you were offline:
<Money money={offlineHackingIncome} />, your Hacknet Nodes generated {hacknetProdInfo} and you gained{" "} <ul>
<Reputation reputation={offlineReputation} /> reputation divided amongst your factions. <li>Your scripts generated{" "} <Money money={offlineHackingIncome} /></li>
<li>Your Hacknet Nodes generated {hacknetProdInfo}</li>
<li>You gained{" "} <Reputation reputation={offlineReputation} /> reputation divided amongst your factions</li>
</ul>
</>, </>,
), ),
250, 250,

@ -26,7 +26,7 @@ import { convertTimeMsToTimeElapsedString } from "../../utils/StringHelperFuncti
import { arrayToString } from "../../utils/helpers/arrayToString"; import { arrayToString } from "../../utils/helpers/arrayToString";
import { Money } from "../React/Money"; import { Money } from "../React/Money";
import { MoneyRate } from "../React/MoneyRate"; import { MoneyRate } from "../React/MoneyRate";
import { RecentScript } from "../..//Netscript/RecentScripts"; import { RecentScript } from "../../Netscript/RecentScripts";
import { LogBoxEvents } from "../React/LogBoxManager"; import { LogBoxEvents } from "../React/LogBoxManager";
const useStyles = makeStyles({ const useStyles = makeStyles({

@ -1,6 +1,6 @@
import React, { useState, useEffect } from "react"; import React, { useState, useEffect } from "react";
import { numeralWrapper } from "../ui/numeralFormat"; import { numeralWrapper } from "./numeralFormat";
import { convertTimeMsToTimeElapsedString } from "../utils/StringHelperFunctions"; import { convertTimeMsToTimeElapsedString } from "../utils/StringHelperFunctions";
import { BitNodeMultipliers } from "../BitNode/BitNodeMultipliers"; import { BitNodeMultipliers } from "../BitNode/BitNodeMultipliers";
import { SourceFileFlags } from "../SourceFile/SourceFileFlags"; import { SourceFileFlags } from "../SourceFile/SourceFileFlags";

@ -44,7 +44,7 @@ import { CorporationRoot } from "../Corporation/ui/CorporationRoot";
import { InfiltrationRoot } from "../Infiltration/ui/InfiltrationRoot"; import { InfiltrationRoot } from "../Infiltration/ui/InfiltrationRoot";
import { ResleeveRoot } from "../PersonObjects/Resleeving/ui/ResleeveRoot"; import { ResleeveRoot } from "../PersonObjects/Resleeving/ui/ResleeveRoot";
import { WorkInProgressRoot } from "./WorkInProgressRoot"; import { WorkInProgressRoot } from "./WorkInProgressRoot";
import { GameOptionsRoot } from "../ui/React/GameOptionsRoot"; import { GameOptionsRoot } from "./React/GameOptionsRoot";
import { SleeveRoot } from "../PersonObjects/Sleeve/ui/SleeveRoot"; import { SleeveRoot } from "../PersonObjects/Sleeve/ui/SleeveRoot";
import { HacknetRoot } from "../Hacknet/ui/HacknetRoot"; import { HacknetRoot } from "../Hacknet/ui/HacknetRoot";
import { GenericLocation } from "../Locations/ui/GenericLocation"; import { GenericLocation } from "../Locations/ui/GenericLocation";
@ -54,7 +54,7 @@ import { Root as ScriptEditorRoot } from "../ScriptEditor/ui/ScriptEditorRoot";
import { MilestonesRoot } from "../Milestones/ui/MilestonesRoot"; import { MilestonesRoot } from "../Milestones/ui/MilestonesRoot";
import { TerminalRoot } from "../Terminal/ui/TerminalRoot"; import { TerminalRoot } from "../Terminal/ui/TerminalRoot";
import { TutorialRoot } from "../Tutorial/ui/TutorialRoot"; import { TutorialRoot } from "../Tutorial/ui/TutorialRoot";
import { ActiveScriptsRoot } from "../ui/ActiveScripts/ActiveScriptsRoot"; import { ActiveScriptsRoot } from "./ActiveScripts/ActiveScriptsRoot";
import { FactionsRoot } from "../Faction/ui/FactionsRoot"; import { FactionsRoot } from "../Faction/ui/FactionsRoot";
import { FactionRoot } from "../Faction/ui/FactionRoot"; import { FactionRoot } from "../Faction/ui/FactionRoot";
import { CharacterStats } from "./CharacterStats"; import { CharacterStats } from "./CharacterStats";
@ -110,106 +110,45 @@ const useStyles = makeStyles((theme: Theme) =>
}), }),
); );
const uninitialized = (): any => {
throw new Error("Router called before initialization");
};
export let Router: IRouter = { export let Router: IRouter = {
page: () => { isInitialized: false,
throw new Error("Router called before initialization"); page: uninitialized,
}, allowRouting: uninitialized,
allowRouting: () => { toActiveScripts: uninitialized,
throw new Error("Router called before initialization"); toAugmentations: uninitialized,
}, toBitVerse: uninitialized,
toActiveScripts: () => { toBladeburner: uninitialized,
throw new Error("Router called before initialization"); toStats: uninitialized,
}, toCity: uninitialized,
toAugmentations: () => { toCorporation: uninitialized,
throw new Error("Router called before initialization"); toCreateProgram: uninitialized,
}, toDevMenu: uninitialized,
toBitVerse: () => { toFaction: uninitialized,
throw new Error("Router called before initialization"); toFactions: uninitialized,
}, toGameOptions: uninitialized,
toBladeburner: () => { toGang: uninitialized,
throw new Error("Router called before initialization"); toHacknetNodes: uninitialized,
}, toInfiltration: uninitialized,
toStats: () => { toJob: uninitialized,
throw new Error("Router called before initialization"); toMilestones: uninitialized,
}, toResleeves: uninitialized,
toCity: () => { toScriptEditor: uninitialized,
throw new Error("Router called before initialization"); toSleeves: uninitialized,
}, toStockMarket: uninitialized,
toCorporation: () => { toTerminal: uninitialized,
throw new Error("Router called before initialization"); toTravel: uninitialized,
}, toTutorial: uninitialized,
toCreateProgram: () => { toWork: uninitialized,
throw new Error("Router called before initialization"); toBladeburnerCinematic: uninitialized,
}, toLocation: uninitialized,
toDevMenu: () => { toStaneksGift: uninitialized,
throw new Error("Router called before initialization"); toAchievements: uninitialized,
}, toThemeBrowser: uninitialized,
toFaction: () => { toImportSave: uninitialized,
throw new Error("Router called before initialization");
},
toFactions: () => {
throw new Error("Router called before initialization");
},
toGameOptions: () => {
throw new Error("Router called before initialization");
},
toGang: () => {
throw new Error("Router called before initialization");
},
toHacknetNodes: () => {
throw new Error("Router called before initialization");
},
toInfiltration: () => {
throw new Error("Router called before initialization");
},
toJob: () => {
throw new Error("Router called before initialization");
},
toMilestones: () => {
throw new Error("Router called before initialization");
},
toResleeves: () => {
throw new Error("Router called before initialization");
},
toScriptEditor: () => {
throw new Error("Router called before initialization");
},
toSleeves: () => {
throw new Error("Router called before initialization");
},
toStockMarket: () => {
throw new Error("Router called before initialization");
},
toTerminal: () => {
throw new Error("Router called before initialization");
},
toTravel: () => {
throw new Error("Router called before initialization");
},
toTutorial: () => {
throw new Error("Router called before initialization");
},
toWork: () => {
throw new Error("Router called before initialization");
},
toBladeburnerCinematic: () => {
throw new Error("Router called before initialization");
},
toLocation: () => {
throw new Error("Router called before initialization");
},
toStaneksGift: () => {
throw new Error("Router called before initialization");
},
toAchievements: () => {
throw new Error("Router called before initialization");
},
toThemeBrowser: () => {
throw new Error("Router called before initialization");
},
toImportSave: () => {
throw new Error("Router called before initialization");
},
}; };
function determineStartPage(player: IPlayer): Page { function determineStartPage(player: IPlayer): Page {
@ -223,6 +162,7 @@ export function GameRoot({ player, engine, terminal }: IProps): React.ReactEleme
const [{ files, vim }, setEditorOptions] = useState({ files: {}, vim: false }); const [{ files, vim }, setEditorOptions] = useState({ files: {}, vim: false });
const [page, setPage] = useState(determineStartPage(player)); const [page, setPage] = useState(determineStartPage(player));
const setRerender = useState(0)[1]; const setRerender = useState(0)[1];
const [augPage, setAugPage] = useState<boolean>(false);
const [faction, setFaction] = useState<Faction>( const [faction, setFaction] = useState<Faction>(
player.currentWorkFactionName ? Factions[player.currentWorkFactionName] : (undefined as unknown as Faction), player.currentWorkFactionName ? Factions[player.currentWorkFactionName] : (undefined as unknown as Faction),
); );
@ -266,6 +206,7 @@ export function GameRoot({ player, engine, terminal }: IProps): React.ReactEleme
} }
Router = { Router = {
isInitialized: true,
page: () => page, page: () => page,
allowRouting: (value: boolean) => setAllowRoutingCalls(value), allowRouting: (value: boolean) => setAllowRoutingCalls(value),
toActiveScripts: () => setPage(Page.ActiveScripts), toActiveScripts: () => setPage(Page.ActiveScripts),
@ -275,7 +216,8 @@ export function GameRoot({ player, engine, terminal }: IProps): React.ReactEleme
toCorporation: () => setPage(Page.Corporation), toCorporation: () => setPage(Page.Corporation),
toCreateProgram: () => setPage(Page.CreateProgram), toCreateProgram: () => setPage(Page.CreateProgram),
toDevMenu: () => setPage(Page.DevMenu), toDevMenu: () => setPage(Page.DevMenu),
toFaction: (faction?: Faction) => { toFaction: (faction: Faction, augPage = false) => {
setAugPage(augPage);
setPage(Page.Faction); setPage(Page.Faction);
if (faction) setFaction(faction); if (faction) setFaction(faction);
}, },
@ -342,12 +284,11 @@ export function GameRoot({ player, engine, terminal }: IProps): React.ReactEleme
}, },
}; };
useEffect(() => { useEffect(() => {
// Wrap Router navigate functions to be able to disable the execution // Wrap Router navigate functions to be able to disable the execution
_functions(Router). _functions(Router)
filter((fnName) => fnName.startsWith('to')). .filter((fnName) => fnName.startsWith("to"))
forEach((fnName) => { .forEach((fnName) => {
// @ts-ignore - tslint does not like this, couldn't find a way to make it cooperate // @ts-ignore - tslint does not like this, couldn't find a way to make it cooperate
Router[fnName] = _wrap(Router[fnName], (func, ...args) => { Router[fnName] = _wrap(Router[fnName], (func, ...args) => {
if (!allowRoutingCalls) { if (!allowRoutingCalls) {
@ -453,7 +394,7 @@ export function GameRoot({ player, engine, terminal }: IProps): React.ReactEleme
break; break;
} }
case Page.Faction: { case Page.Faction: {
mainPage = <FactionRoot faction={faction} />; mainPage = <FactionRoot faction={faction} augPage={augPage} />;
break; break;
} }
case Page.Milestones: { case Page.Milestones: {
@ -564,13 +505,7 @@ export function GameRoot({ player, engine, terminal }: IProps): React.ReactEleme
break; break;
} }
case Page.ImportSave: { case Page.ImportSave: {
mainPage = ( mainPage = <ImportSaveRoot importString={importString} automatic={importAutomatic} router={Router} />;
<ImportSaveRoot
importString={importString}
automatic={importAutomatic}
router={Router}
/>
);
withSidebar = false; withSidebar = false;
withPopups = false; withPopups = false;
bypassGame = true; bypassGame = true;

@ -1,6 +1,6 @@
import React, { useState, useEffect } from "react"; import React, { useState, useEffect } from "react";
import { EventEmitter } from "../../utils/EventEmitter"; import { EventEmitter } from "../../utils/EventEmitter";
import { Modal } from "../../ui/React/Modal"; import { Modal } from "./Modal";
import Typography from "@mui/material/Typography"; import Typography from "@mui/material/Typography";
import Box from "@mui/material/Box"; import Box from "@mui/material/Box";
import {sha256} from "js-sha256"; import {sha256} from "js-sha256";

@ -4,7 +4,7 @@ import React, { useState, useEffect } from "react";
import { Theme, useTheme } from "@mui/material/styles"; import { Theme, useTheme } from "@mui/material/styles";
import makeStyles from "@mui/styles/makeStyles"; import makeStyles from "@mui/styles/makeStyles";
import createStyles from "@mui/styles/createStyles"; import createStyles from "@mui/styles/createStyles";
import { numeralWrapper } from "../../ui/numeralFormat"; import { numeralWrapper } from "../numeralFormat";
import { Reputation } from "./Reputation"; import { Reputation } from "./Reputation";
import { KillScriptsModal } from "./KillScriptsModal"; import { KillScriptsModal } from "./KillScriptsModal";
import { convertTimeMsToTimeElapsedString } from "../../utils/StringHelperFunctions"; import { convertTimeMsToTimeElapsedString } from "../../utils/StringHelperFunctions";

@ -1,5 +1,5 @@
import * as React from "react"; import * as React from "react";
import { numeralWrapper } from "../../ui/numeralFormat"; import { numeralWrapper } from "../numeralFormat";
import { Theme } from "@mui/material/styles"; import { Theme } from "@mui/material/styles";
import makeStyles from "@mui/styles/makeStyles"; import makeStyles from "@mui/styles/makeStyles";
import createStyles from "@mui/styles/createStyles"; import createStyles from "@mui/styles/createStyles";

@ -1,6 +1,6 @@
import React from "react"; import React from "react";
import { numeralWrapper } from "../../ui/numeralFormat"; import { numeralWrapper } from "../numeralFormat";
import { Hashes } from "../../ui/React/Hashes"; import { Hashes } from "./Hashes";
export function HashRate({ hashes }: { hashes: number }): React.ReactElement { export function HashRate({ hashes }: { hashes: number }): React.ReactElement {
return <Hashes hashes={`${numeralWrapper.formatHashes(hashes)} h / s`} />; return <Hashes hashes={`${numeralWrapper.formatHashes(hashes)} h / s`} />;

@ -1,5 +1,5 @@
import * as React from "react"; import * as React from "react";
import { numeralWrapper } from "../../ui/numeralFormat"; import { numeralWrapper } from "../numeralFormat";
import { Theme } from "@mui/material/styles"; import { Theme } from "@mui/material/styles";
import makeStyles from "@mui/styles/makeStyles"; import makeStyles from "@mui/styles/makeStyles";
import createStyles from "@mui/styles/createStyles"; import createStyles from "@mui/styles/createStyles";

@ -1,5 +1,5 @@
import * as React from "react"; import * as React from "react";
import { numeralWrapper } from "../../ui/numeralFormat"; import { numeralWrapper } from "../numeralFormat";
import { IPlayer } from "../../PersonObjects/IPlayer"; import { IPlayer } from "../../PersonObjects/IPlayer";
import { Theme } from "@mui/material/styles"; import { Theme } from "@mui/material/styles";
import makeStyles from "@mui/styles/makeStyles"; import makeStyles from "@mui/styles/makeStyles";

@ -1,6 +1,6 @@
import React from "react"; import React from "react";
import { numeralWrapper } from "../../ui/numeralFormat"; import { numeralWrapper } from "../numeralFormat";
import { Money } from "../../ui/React/Money"; import { Money } from "./Money";
export function MoneyRate({ money }: { money: number }): JSX.Element { export function MoneyRate({ money }: { money: number }): JSX.Element {
return <Money money={`${numeralWrapper.formatMoney(money)} / sec`} />; return <Money money={`${numeralWrapper.formatMoney(money)} / sec`} />;

@ -1,6 +1,6 @@
import React, { useState, useEffect } from "react"; import React, { useState, useEffect } from "react";
import { EventEmitter } from "../../utils/EventEmitter"; import { EventEmitter } from "../../utils/EventEmitter";
import { Modal } from "../../ui/React/Modal"; import { Modal } from "./Modal";
import Typography from "@mui/material/Typography"; import Typography from "@mui/material/Typography";
import Button from "@mui/material/Button"; import Button from "@mui/material/Button";

@ -1,5 +1,5 @@
import * as React from "react"; import * as React from "react";
import { numeralWrapper } from "../../ui/numeralFormat"; import { numeralWrapper } from "../numeralFormat";
import { Theme } from "@mui/material/styles"; import { Theme } from "@mui/material/styles";
import makeStyles from "@mui/styles/makeStyles"; import makeStyles from "@mui/styles/makeStyles";
import createStyles from "@mui/styles/createStyles"; import createStyles from "@mui/styles/createStyles";

@ -1,6 +1,6 @@
import React from "react"; import React from "react";
import { numeralWrapper } from "../../ui/numeralFormat"; import { numeralWrapper } from "../numeralFormat";
import { Reputation } from "../../ui/React/Reputation"; import { Reputation } from "./Reputation";
export function ReputationRate({ reputation }: { reputation: number }): React.ReactElement { export function ReputationRate({ reputation }: { reputation: number }): React.ReactElement {
return <Reputation reputation={`${numeralWrapper.formatReputation(reputation)} / sec`} />; return <Reputation reputation={`${numeralWrapper.formatReputation(reputation)} / sec`} />;

@ -54,6 +54,7 @@ export interface IRouter {
// toMission(): void; // toMission(): void;
// toRedPill(): void; // toRedPill(): void;
// toworkInProgress(): void; // toworkInProgress(): void;
isInitialized: boolean;
page(): Page; page(): Page;
allowRouting(value: boolean): void; allowRouting(value: boolean): void;
toActiveScripts(): void; toActiveScripts(): void;
@ -65,7 +66,7 @@ export interface IRouter {
toCorporation(): void; toCorporation(): void;
toCreateProgram(): void; toCreateProgram(): void;
toDevMenu(): void; toDevMenu(): void;
toFaction(faction?: Faction): void; // faction name toFaction(faction: Faction, augPage?: boolean): void; // faction name
toFactions(): void; toFactions(): void;
toGameOptions(): void; toGameOptions(): void;
toGang(): void; toGang(): void;

@ -31,10 +31,35 @@ export function WorkInProgressRoot(): React.ReactElement {
const id = setInterval(rerender, CONSTANTS.MilliPerCycle); const id = setInterval(rerender, CONSTANTS.MilliPerCycle);
return () => clearInterval(id); return () => clearInterval(id);
}, []); }, []);
const player = use.Player(); const player = use.Player();
const router = use.Router(); const router = use.Router();
const faction = Factions[player.currentWorkFactionName];
if (player.workType == CONSTANTS.WorkTypeFaction) { if (player.workType == CONSTANTS.WorkTypeFaction) {
const faction = Factions[player.currentWorkFactionName];
if (!faction) {
return (
<Grid container direction="column" justifyContent="center" alignItems="center" style={{ minHeight: "100vh" }}>
<Grid item>
<Typography>
Something has gone wrong, you cannot work for {player.currentWorkFactionName || "(Faction not found)"} at
this time.
</Typography>
</Grid>
</Grid>
);
}
if (!faction) {
return (
<>
<Typography variant="h4" color="primary">
You have not joined {faction} yet!
</Typography>
<Button onClick={() => router.toFactions()}>Back to Factions</Button>
</>
);
}
function cancel(): void { function cancel(): void {
router.toFaction(faction); router.toFaction(faction);
player.finishFactionWork(true); player.finishFactionWork(true);
@ -124,7 +149,6 @@ export function WorkInProgressRoot(): React.ReactElement {
} }
function unfocus(): void { function unfocus(): void {
router.toFaction(faction);
router.toCity(); router.toCity();
player.stopFocusing(); player.stopFocusing();
} }