-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmegacorp.js
More file actions
1127 lines (1050 loc) · 51.5 KB
/
megacorp.js
File metadata and controls
1127 lines (1050 loc) · 51.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { boxTailSingleton } from 'utils.js';
const _ = globalThis._; // lodash
// Global constants
export const argsSchema = [
['no-expansion', false], // If this flag is set, do not expand to new industries. Just work on what we have.
['reserve-amount', 1e9], // Don't spend the corporation's last $billion if we can help it.
['verbose', false], // Print extra log messages.
['can-accept-funding', true], // When we run low on money, should we look for outside funding?
['can-go-public', true], // If we can't get private funding, should we go public?
['issue-shares', 0], // If we go public, how many shares should we issue?
['can-spend-hashes', true], // Can we spend hacknet hashes (assuming we have them)?
['o', false],
['mock', false], // Run the task assignment queue, but don't actually spend any money.
['price-discovery-only', false], // Don't do any auto-buying, just try to keep the sale price balanced as high as possible. (Emulating TA2 as best we can)
['first', 'Agriculture'], // What should we use for our first division? Agriculture works well, but others should be fine too.
['second', 'RealEstate'], // What should we prefer for our second division? If we can't afford it, we'll buy what we can afford instead.
];
const desiredDivisions = 2; // One Material division to kickstart things, then a product division to really make money.
const bonusMaterials = ['Hardware', 'Robots', 'AICores', 'RealEstate'];
const materialSizes = { Water: 0.05, Energy: 0.01, Food: 0.03, Plants: 0.05, Metal: 0.1, Hardware: 0.06, Chemicals: 0.05, Drugs: 0.02, Robots: 0.5, AICores: 0.1, RealEstate: 0.005 };
const allMaterials = ['Water', 'Energy', 'Food', 'Plants', 'Metal', 'Hardware', 'Chemicals', 'Drugs', 'Robots', 'AICores', 'RealEstate'];
// Map of material (by name) to their sizes (how much space it takes in warehouse)
const unlocks = ['Export', 'Smart Supply', 'Market Research - Demand', 'Market Data - Competition', 'VeChain', 'Shady Accounting', 'Government Partnership', 'Warehouse API', 'Office API'];
const upgrades = ['Smart Factories', 'Smart Storage', 'DreamSense', 'Wilson Analytics', 'Nuoptimal Nootropic Injector Implants', 'Speech Processor Implants', 'Neural Accelerators', 'FocusWires', 'ABC SalesBots', 'Project Insight'];
const cities = ['Aevum', 'Chongqing', 'Sector-12', 'New Tokyo', 'Ishima', 'Volhaven'];
const hqCity = 'Aevum'; // Our production industries will need a headquarters. It doesn't matter which city we use.
const jobs = ['Operations', 'Engineer', 'Research & Development', 'Management', 'Business']; // Also, 'Training', but that's not a real job.
// Classes here, since we want to use Industry shortly.
class Industry {
constructor(name = '', robFac = 0.0, aiFac = 0.0, advFac = 0.0, sciFac = 0.0, hwFac = 0.0, reFac = 0.0, reqMats = {}, prodMats = [], makesProducts = false, startupCost = 0) {
this.name = name;
this.factors = {
Hardware: hwFac,
Robots: robFac,
AICores: aiFac,
RealEstate: reFac,
Science: sciFac,
Advertising: advFac,
};
this.reqMats = reqMats;
this.prodMats = prodMats;
this.makesProducts = makesProducts;
this.startupCost = startupCost;
this.materialBonusPerSqMeter = {};
for (const material of bonusMaterials) {
this.materialBonusPerSqMeter[material] = this.factors[material] / materialSizes[material];
}
let scaleFactor = Object.values(this.materialBonusPerSqMeter).reduce((sum, prod) => sum + prod, 0);
this.scaledMaterialBonus = {};
for (const material of bonusMaterials) {
this.scaledMaterialBonus[material] = this.materialBonusPerSqMeter[material] / scaleFactor;
}
}
static fromObject(obj) {
return new Industry(obj.name, obj.robFac, obj.aiFac, obj.advFac, obj.sciFac, obj.hwFac, obj.reFac, obj.reqMats, obj.prodMats, obj.makesProducts, obj.startupCost);
}
}
class Task {
/**
* A Task that we will try to run later.
* @param {string} name Human readable name of the task to be run.
* @param {function} run callback to run the task.
* @param {number} cost allocated budget for this task
* @param {number} priority priority, higher number is a higher priority
*/
constructor(name, run, cost = 0, priority = 0) {
this.name = name;
this.run = run;
this.cost = cost;
this.priority = priority; // Higher will be done sooner.
}
}
// Industry and Material data copied from Bitburner's code on February 10, 2022. (https://github.com/danielyxie/bitburner/blob/dev/src/Corporation/Industry.ts) with startupCost added manually.
/** @type {Industry[]} */
const industries = [
Industry.fromObject({ name: 'Agriculture', reFac: 0.72, sciFac: 0.5, hwFac: 0.2, robFac: 0.3, aiFac: 0.3, advFac: 0.04, reqMats: { Water: 0.5, Energy: 0.5 }, prodMats: ['Plants', 'Food'], startupCost: 40e9 }),
Industry.fromObject({ name: 'Chemical', reFac: 0.25, sciFac: 0.75, hwFac: 0.2, robFac: 0.25, aiFac: 0.2, advFac: 0.07, reqMats: { Plants: 1, Energy: 0.5, Water: 0.5 }, prodMats: ['Chemicals'], startupCost: 70e9 }),
Industry.fromObject({ name: 'Fishing', reFac: 0.15, sciFac: 0.35, hwFac: 0.35, robFac: 0.5, aiFac: 0.2, advFac: 0.08, reqMats: { Energy: 0.5 }, prodMats: ['Food'], startupCost: 80e9 }),
Industry.fromObject({ name: 'Utilities', reFac: 0.5, sciFac: 0.6, robFac: 0.4, aiFac: 0.4, advFac: 0.08, reqMats: { Hardware: 0.1, Metal: 0.1 }, prodMats: ['Water'], startupCost: 150e9 }),
Industry.fromObject({ name: 'Energy', reFac: 0.65, sciFac: 0.7, robFac: 0.05, aiFac: 0.3, advFac: 0.08, reqMats: { Hardware: 0.1, Metal: 0.2 }, prodMats: ['Energy'], startupCost: 225e9 }),
Industry.fromObject({ name: 'Mining', reFac: 0.3, sciFac: 0.26, hwFac: 0.4, robFac: 0.45, aiFac: 0.45, advFac: 0.06, reqMats: { Energy: 0.8 }, prodMats: ['Metal'], startupCost: 300e9 }),
//reFac is unique for 'Food' bc it diminishes greatly per city. Handle this separately in code?
Industry.fromObject({ name: 'Food', sciFac: 0.12, hwFac: 0.15, robFac: 0.3, aiFac: 0.25, advFac: 0.25, reFac: 0.05, reqMats: { Food: 0.5, Water: 0.5, Energy: 0.2 }, makesProducts: true, startupCost: 10e9 }),
Industry.fromObject({ name: 'Tobacco', reFac: 0.15, sciFac: 0.75, hwFac: 0.15, robFac: 0.2, aiFac: 0.15, advFac: 0.2, reqMats: { Plants: 1, Water: 0.2 }, makesProducts: true, startupCost: 20e9 }),
Industry.fromObject({ name: 'Software', sciFac: 0.62, advFac: 0.16, hwFac: 0.25, reFac: 0.15, aiFac: 0.18, robFac: 0.05, reqMats: { Hardware: 0.5, Energy: 0.5 }, prodMats: ['AICores'], makesProducts: true, startupCost: 25e9 }),
Industry.fromObject({ name: 'Pharmaceutical', reFac: 0.05, sciFac: 0.8, hwFac: 0.15, robFac: 0.25, aiFac: 0.2, advFac: 0.16, reqMats: { Chemicals: 2, Energy: 1, Water: 0.5 }, prodMats: ['Drugs'], makesProducts: true, startupCost: 200e9 }),
Industry.fromObject({ name: 'Computer', reFac: 0.2, sciFac: 0.62, robFac: 0.36, aiFac: 0.19, advFac: 0.17, reqMats: { Metal: 2, Energy: 1 }, prodMats: ['Hardware'], makesProducts: true, startupCost: 500e9 }),
Industry.fromObject({ name: 'RealEstate', robFac: 0.6, aiFac: 0.6, advFac: 0.25, sciFac: 0.05, hwFac: 0.05, reqMats: { Metal: 5, Energy: 5, Water: 2, Hardware: 4 }, prodMats: ['RealEstate'], makesProducts: true, startupCost: 600e9 }),
Industry.fromObject({ name: 'Healthcare', reFac: 0.1, sciFac: 0.75, advFac: 0.11, hwFac: 0.1, robFac: 0.1, aiFac: 0.1, reqMats: { Robots: 10, AICores: 5, Energy: 5, Water: 5 }, makesProducts: true, startupCost: 750e9 }),
Industry.fromObject({ name: 'Robotics', reFac: 0.32, sciFac: 0.65, aiFac: 0.36, advFac: 0.18, hwFac: 0.19, reqMats: { Hardware: 5, Energy: 3 }, prodMats: ['Robots'], makesProducts: true, startupCost: 1e12 }),
];
// Global state
/** @type {CorporationInfo} */
let myCorporation;
let options;
let verbose;
let raisingCapital = 0; // Used to flag that we are trying to raise private funding
let extraReserve = 0; // Used when we're saving to fund a new product.
let fillSpaceQueue = []; // Flag these offices as needing workers assigned to roles.
export function autocomplete(data, _) {
data.flags(argsSchema);
return [];
}
let c;
/** @param {NS} ns **/
export async function main(ns) {
ns.disableLog('sleep');
c = ns.corporation;
// Pull in any information we only need at startup.
options = ns.flags(argsSchema);
verbose = options.verbose;
let createCorp = false;
// See if we've already created a corporation.
try {
myCorporation = c.getCorporation();
} catch {
createCorp = true;
}
if (createCorp) {
try {
c.createCorporation('corp', true);
myCorporation = c.getCorporation();
} catch {
return;
}
}
await ns.write('/tmp/incorp.txt', '', 'w');
boxTailSingleton(ns, 'corp', '🏠', '400px');
ns.clearLog();
// If we already have a corporation, make sure we didn't leave any workers waiting for assignment.
for (const division of myCorporation.divisions) {
for (const city of division.cities) {
fillSpaceQueue.push(`${division.name}/${city}`);
}
}
// We've set up the initial corporation, now run it over time.
while (true) {
// Do all our spending and expanding.
await doManageCorporation(ns);
// Try to manage sale prices for products.
await doPriceDiscovery(ns);
// While we wait for the next tick, process any open office positions
await fillOpenPositionsFromQueue(ns);
// Sleep until the next time we go into the 'START' phase
await sleepWhileNotInStartState(ns, true);
if (verbose) log(ns, ``);
}
}
/**
* This function is called in our main loop. Assess the current state of the corporation, and improve it as best we can.
* @param {NS} ns
**/
async function doManageCorporation(ns) {
// Assess the current state of the corporation, and figure out our budget.
myCorporation = c.getCorporation();
let netIncome = myCorporation.revenue - myCorporation.expenses;
let now = new Date().toLocaleString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true });
if (verbose) log(ns, `----- [ ${myCorporation.name} Quarterly Report ${now} ] -----`);
log(ns, `Corporate cash on hand: ${ns.nFormat(myCorporation.funds, '0.0a')} (Gross: ${ns.nFormat(myCorporation.revenue, '0.0a')}/s, Net: ${ns.nFormat(netIncome, '0.0a')}/s)`);
// See if we can raise more money.
await tryRaiseCapital(ns);
myCorporation = c.getCorporation();
let budget = myCorporation.funds - options['reserve-amount'] - extraReserve;
// If we're making more than $1 sextillion / sec, we need to stop. The game gets slow if we start employing too many people.
if (myCorporation.revenue > 1e21) budget = 0;
budget = Math.max(0, budget);
if (verbose) log(ns, `Working with a corporate budget of ${ns.nFormat(budget, '0.0a')}`);
// Let's figure out all of the things we'd like to do, before we commit to anything.
let tasks = [];
/**
* What sort of corporation-wide stuff would we like to do?
* Buy Unlocks? Buy upgrades?
*/
let availableUnlocks = [];
const purchasedUnlocks = [];
for (const unlockable of unlocks) {
if (c.hasUnlockUpgrade(unlockable)) purchasedUnlocks.push(unlockable);
else availableUnlocks.push(unlockable);
}
for (const unlockable of availableUnlocks) {
let cost = c.getUnlockUpgradeCost(unlockable);
if (cost > budget) continue;
// If we can afford it, and we don't have it yet, consider buying it.
let shouldBuy = false;
if (unlockable === 'Smart Supply' && cost < budget * 0.8) {
// Push this one to the top of the list. Doing it in code is annoying.
tasks.push(new Task('Unlock ' + unlockable, () => c.unlockUpgrade(unlockable), cost, 110));
} else if (unlockable === 'Shady Accounting' && cost < budget * 0.5) shouldBuy = true;
else if (unlockable === 'Government Partnership' && cost < budget * 0.5) shouldBuy = true;
// else if (unlockable === 'Export' && cost < budget * 0.1) shouldBuy = true;
// Put the task on our to-do list. Put all unlocks at priority 0 as "nice-to-haves".
if (shouldBuy) tasks.push(new Task('Unlock ' + unlockable, () => c.unlockUpgrade(unlockable), cost, 0));
}
let hasProductionDivision = false;
for (const division of myCorporation.divisions) {
let industry = industries.find((i) => i.name === division.type);
if (industry.makesProducts) hasProductionDivision = true;
}
// Can we afford to level any upgrades?
for (const upgrade of upgrades) {
let cost = c.getUpgradeLevelCost(upgrade);
let nextLevel = c.getUpgradeLevel(upgrade) + 1;
if (cost > budget) continue;
if (upgrade === 'Wilson Analytics' && cost < budget * 0.9 && hasProductionDivision) {
// Analytics fuels advertising, which drives up the price of products, which generates profits.
// Scale the priority based on how cheap this is (cheaper is higher priority [0-100]).
let priority = Math.round((1 - cost / budget) * 100);
tasks.push(new Task(`Upgrading '${upgrade}' to level ${nextLevel}`, () => c.levelUpgrade(upgrade), cost, priority));
} else if (['Smart Factories', 'Smart Storage'].includes(upgrade) && cost < budget * 0.1) {
// More storage means more materials, which drives more production. More production means more sales.
tasks.push(new Task(`Upgrading '${upgrade}' to level ${nextLevel}`, () => c.levelUpgrade(upgrade), cost, 10));
} else if (cost < budget * 0.01) {
// Upgrade other stuff too, as long as it's cheap compared to our budget.
tasks.push(new Task(`Upgrading '${upgrade}' to level ${nextLevel}`, () => c.levelUpgrade(upgrade), cost, 1));
}
}
/**
* Let's take a look at our divisions for big problems. Do we need to expand to a new industry? Are any
* of our existing industries showing a loss? What else might we need to consider here? We'll be looking
* at every division at the end of the loop to do maintenance, so this is just high level stuff.
*/
if (myCorporation.divisions.length === 0) {
// We definitely need a new division!
// Use up to 80% of our budget to start this first division.
let newDivisionBudget = budget * 0.9;
// Just consider the basic materials-producing industries for our first division. Products take a long time to come online.
let possibleIndustries = industries.filter((ind) => !ind.makesProducts);
// And only the ones where we'll be able to spend at least half our budget setting up shop.
possibleIndustries = possibleIndustries.filter((ind) => ind.startupCost < newDivisionBudget * 0.5);
// TODO: Pick a starting industry using some sort of logic.
// For the moment, let's just try to go with Agriculture. It's cheap and works well.
let newIndustry = possibleIndustries.find((ind) => ind.name === options['first']);
if (newIndustry) {
tasks.push(new Task(`Add the first division, '${newIndustry.name}'`, () => doCreateNewDivision(ns, newIndustry, newDivisionBudget), newDivisionBudget, 100));
} else {
// If we can't afford to create our first industry, something has gone very wrong. Quit now.
log(ns, `ERROR: Could not afford to create our first industry!`, 'error', true);
ns.exit();
}
}
// Figure out where we are in the fundraising progression. Don't buy a production industry until after accepting round 3.
let offer = c.getInvestmentOffer();
if (myCorporation.divisions.length > 0 && myCorporation.divisions.length < desiredDivisions && offer.round > 3) {
let newDivisionBudget = budget * 0.9;
let possibleIndustries = industries.filter((ind) => ind.makesProducts);
// Only consider industries where we can still have a budget to actually get started.
possibleIndustries = possibleIndustries.filter((ind) => ind.startupCost < budget * 0.5);
possibleIndustries.sort((a, b) => a.startupCost - b.startupCost).reverse();
if (verbose && possibleIndustries.length) {
log(ns, `We would like to expand into a new industry. Possibilities:`);
for (const industry of possibleIndustries) {
log(ns, ` ${ns.nFormat(industry.startupCost, '0.0a')} - ${industry.name}`);
}
} else if (verbose) log(ns, `INFO: We would like to create a new division but we cannot afford one. Willing to spend ${ns.nFormat(budget, '0.0a')}.`);
// Try to use the industry from the command line. If that doesn't work, fall back to picking from our list of possibilities.
// let newIndustry = possibleIndustries.find((ind) => ind.name == 'Pharmaceutical');
let newIndustry = possibleIndustries.find((ind) => ind.name === options['second']);
if (!newIndustry && possibleIndustries.length > 0) {
newIndustry = possibleIndustries[0];
}
if (newIndustry) {
tasks.push(new Task(`Add a production division, '${newIndustry.name}'`, () => doCreateNewDivision(ns, newIndustry, newDivisionBudget), newDivisionBudget, 100));
} else {
log(ns, `ERROR: Buying industry failed. Aborting!`, 'error', true);
ns.exit();
}
}
// If we have all of our divisions bought, it's worth spending hashes on research.
// if (myCorporation.divisions.length >= desiredDivisions) {
// if (options['can-spend-hashes'])
// await doSpendHashes(ns, 'Exchange for Corporation Research');
// }
/**
* We've looked at the at the corporation, and come up with a list of tasks we'd like to do. Now, figure out
* which ones we can actually accomplish on our budget.
*/
tasks.sort((a, b) => a.cost - b.cost).reverse();
tasks.sort((a, b) => a.priority - b.priority).reverse();
/**
* Finally, run each task in priority order. If we run out of money, should we buy lower priority stuff, or
* wait? If we wait, the money might get spent expanding a division instead. This may all take some
* adjustments over time.
*/
let spent = await runTasks(ns, tasks, budget);
if (spent) budget -= spent;
if (spent > 0 && verbose) log(ns, `Spent ${ns.nFormat(spent, '0.0a')} of our budget of ${ns.nFormat(budget, '0.0a')}.`);
/**
* Even though we've done all of our desired high level tasks, we still need to tend to each division individually.
* If we don't have all the automation bits, we may need to adjust pricing. If we have room in warehouses, we can buy
* more materials. If we have products, we may be able to start on a new product. We may have research to spend.
*/
for (const division of myCorporation.divisions) {
// If we have multiple divisions, hold the lion's share of the budget for production industries.
let industry = industries.find((ind) => ind.name === division.type);
let divisionalBudget = budget;
if (myCorporation.divisions.length > 1 && !industry.makesProducts) {
divisionalBudget *= 0.05;
}
let spent = await doManageDivision(ns, division, divisionalBudget);
if (spent) budget -= spent;
}
}
/**
* Try to raise money.
* Advances through the funding rounds, eventually going public. Potentially spends hacknet hashes for money.
* @param {NS} ns
*/
async function tryRaiseCapital(ns) {
// First, spend hacknet hashes.
// if (options['can-spend-hashes'] && myCorporation.funds < 10e9)
// await doSpendHashes(ns, 'Sell for Corporation Funds');
// If we're not public, then raise private funding.
if (!myCorporation.public) {
let offer = c.getInvestmentOffer();
// If we've finished round 4, clear our raising capital flag.
if (offer.round > 4) raisingCapital = 0;
let willAccept = true;
if (offer && offer.round <= 4) {
log(ns, `Considering raising private capital round ${offer.round}. Offered ${ns.nFormat(offer.funds, '0.0a')} for ${offer.shares} shares.`);
// Make sure all employees are happy.
let satisfied = allEmployeesSatisfied(ns);
if (!satisfied) {
let prefix = ' *';
if (!willAccept) prefix = ' ';
log(ns, `${prefix} Round ${offer.round} financing waiting on employee stats to stabilize.`);
willAccept = false;
}
// Make sure we have filled a reasonable amount of our warehouses with materials.
for (const division of myCorporation.divisions) {
let industry = industries.find((i) => i.name === division.type);
for (const city of division.cities) {
if (!c.hasWarehouse(division.name, city)) continue;
let warehouse = c.getWarehouse(division.name, city);
let warehouseSpaceRequiredForCycle = getReservedWarehouseSpace(ns, industry, division, city);
let warehouseSpaceAvailable = warehouse.size - warehouseSpaceRequiredForCycle - warehouse.sizeUsed;
if (warehouseSpaceAvailable > warehouseSpaceRequiredForCycle * 0.2) {
let prefix = ' *';
if (!willAccept) prefix = ' ';
log(ns, `${prefix} Round ${offer.round} financing waiting on ${division.name} warehouses to gain materials.`);
willAccept = false;
break;
}
}
}
// If we have a product division, make sure it has a maximum number of products before we accept the offer.
for (const division of myCorporation.divisions) {
const maxProducts = getMaxProducts(ns, division.name);
let industry = industries.find((i) => i.name === division.type);
if (industry.makesProducts && division.products.length < maxProducts) {
let prefix = ' *';
if (!willAccept) prefix = ' ';
log(ns, `${prefix} Round ${offer.round} financing waiting on ${division.name} division to create products (${division.products.length}/${maxProducts})`);
willAccept = false;
}
if (offer.round >= 4 && industry.makesProducts) {
// Wait for the last product to finish researching
let completeProducts = division.products.map((prodName) => c.getProduct(division.name, prodName)).filter((prod) => prod.developmentProgress >= 100);
if (completeProducts.length < maxProducts) {
let prefix = ' *';
if (!willAccept) prefix = ' ';
log(ns, `${prefix} Round ${offer.round} financing waiting on ${division.name} division to complete products (${completeProducts.length}/${maxProducts})`);
willAccept = false;
}
}
}
// TODO: Funding is proportional to revenue. We can cook the books so that revenue looks higher than it should by stockpiling goods, then selling them all at once.
// Make sure we aren't spending money on materials when we get funding. Each time we come through the loop and would purchase, increment the counter. After 4 times, purchase.
if (willAccept) raisingCapital++;
else raisingCapital = 0;
// If we've passed all the checks, then accept the next round of funding.
if (options['can-accept-funding'] && raisingCapital > 4 && !options.mock) {
let success = c.acceptInvestmentOffer();
raisingCapital = 0;
if (success) log(ns, `WARNING: Accepted round ${offer.round} funding. Took ${ns.nFormat(offer.funds, '0.0a')} for ${offer.shares} shares.`);
else log(ns, `ERROR: Tried to accept round ${offer.round} funding, but something went wrong.`);
} else if (options['can-accept-funding'] && raisingCapital > 0) {
log(ns, `SUCCESS: Raising capital in ${5 - raisingCapital} cycles.`);
}
} else {
// We're public, so we can't be raising capital.
raisingCapital = 0;
}
// Finally, if we're out of private funding, we may as well go public
offer = c.getInvestmentOffer();
if (options['can-go-public'] && !options.mock && offer.round > 4) {
// Looks like we're out of private funding. Time to go public.
log(ns, `SUCCESS: Private funding complete. Time to IPO. Selling ${options['issue-shares']} shares.`);
c.goPublic(options['issue-shares']);
// and set our dividend to 10%
c.issueDividends(0.1);
}
} else {
// We're public, so we can't be raising capital.
raisingCapital = 0;
}
}
/**
* Do all employees have enough happiness, energy, and morale?
* @param {NS} ns
* @param {number} lowerLimit - minimum for all stats [0,1]
* @returns {boolean}
*/
function allEmployeesSatisfied(ns, lowerLimit = 0.9995) {
let allSatisfied = true;
for (const division of myCorporation.divisions) {
for (const city of division.cities) {
let office = c.getOffice(division.name, city);
let employees = office.employees.map((e) => c.getEmployee(division.name, city, e));
let avgMorale = employees.map((e) => e.mor).reduce((sum, mor) => sum + mor, 0) / employees.length;
let avgEnergy = employees.map((e) => e.ene).reduce((sum, ene) => sum + ene, 0) / employees.length;
let avgHappiness = employees.map((e) => e.hap).reduce((sum, hap) => sum + hap, 0) / employees.length;
if (avgEnergy < office.maxEne * lowerLimit || avgHappiness < office.maxHap * lowerLimit || avgMorale < office.maxMor * lowerLimit) {
allSatisfied = false;
break;
}
}
}
return allSatisfied;
}
/**
* Given a list of tasks, execute them in order.
* @param {NS} ns
* @param {Task[]} tasks
* @param {number} budget
* @param {boolean} keepSpending Should we keep spending money on items further down the list after hitting an item we can't afford?
* @returns {number} the amount spent.
*/
async function runTasks(ns, tasks, budget, keepSpending = true) {
const startingBudget = budget;
for (const task of tasks) {
let success = false;
if (budget - task.cost > 0) {
log(ns, ` Spending ${ns.nFormat(task.cost, '0.0a')} on ${task.name}`);
// Some of the ns.corporation calls we use are void functions, so treat a return value of undefined with no exception as a success.
if (!options.mock)
try {
success = await task.run();
if (success === undefined) success = true;
} catch (e) {
log(ns, `WARNING: Failed to execute ${task.name} - ${task.run}`);
log(ns, `WARNING: ${e}`);
}
if (success) budget -= task.cost;
}
if (!success && !keepSpending) break;
}
return startingBudget - budget;
}
/**
* Create a bare bones new division, then use any remaining money to set it up.
* @param {NS} ns
* @param {*} newIndustry
* @param {number} newDivisionBudget
* @returns {boolean} true if we created the new division, false if not.
*/
async function doCreateNewDivision(ns, newIndustry, newDivisionBudget) {
if (options['no-expansion'] || options['mock']) return false;
myCorporation = c.getCorporation();
let numDivisions = myCorporation.divisions.length;
c.expandIndustry(newIndustry.name, newIndustry.name);
myCorporation = c.getCorporation();
if (numDivisions === myCorporation.divisions.length) {
log(ns, `ERROR: Failed to create new division! Expected to create '${newIndustry.name}'.`, 'error', true);
ns.exit();
}
newDivisionBudget -= newIndustry.startupCost;
if (verbose) log(ns, `Spending ${ns.nFormat(newIndustry.startupCost, '0.0a')} setting up a new '${newIndustry.name}' division.`);
let newDivision = c.getDivision(newIndustry.name);
// Hire the first three employees in Sector-12
fillSpaceQueue.push(`${newDivision.name}/Sector-12`);
// Do the first round of purchasing now.
await doManageDivision(ns, newDivision, newDivisionBudget);
if (newDivision) return true;
else return false;
}
/**
* Given an existing division, try to allocate our budget to growing the business.
* @param {NS} ns
* @param {Division} division division from ns.corporation.getDivision()
* @param {number} budget amount we can spend
* @returns {number} the amount we spent while managing this division.
*/
async function doManageDivision(ns, division, budget) {
myCorporation = c.getCorporation();
const industry = industries.find((ind) => ind.name === division.type);
budget = Math.max(0, budget);
const totalBudget = budget;
/**
* Take stock of the current state of this division. Just like at the corporate level,
* collect some tasks that we'd like to do, then see what we can execute. Don't worry too
* much about spending the whole budget. Anything we don't spend now will get passed on
* to other divisions, or recycled in the next pass.
*/
if (verbose) log(ns, `Managing ${division.name} division with a budget of ${ns.nFormat(budget, '0.0a')}.`);
let spent = 0;
let tasks = [];
// Can we expand to new cities?
if (division.cities.length < cities.length) {
// We aren't in all cities yet, so we want to expand.
for (const city of cities) {
if (!division.cities.includes(city)) {
let cost = c.getExpandCityCost();
if (cost < budget * 0.25) {
if (verbose) log(ns, `Want to open new offices in ${city}.`);
tasks.push(new Task(`Expand ${division.name} to ${city}`, () => doExpandCity(ns, division.name, city), cost, 80));
} else if (verbose) log(ns, `WARNING: We would like to expand to ${city}, but it would cost ${ns.nFormat(cost, '0.0a')} on our budget of ${ns.nFormat(budget, '0.0a')}.`);
}
}
}
// Go ahead and expand immediately, so we can buy other stuff for any new locations on this cycle.
if (tasks.length > 0) {
spent = await runTasks(ns, tasks, budget);
budget -= spent;
tasks = [];
}
// Update our status
myCorporation = c.getCorporation();
division = c.getDivision(division.name);
let hasMarketTA2 = c.hasResearched(division.name, 'Market-TA.II');
// Division wide tasks
// Can we buy advertising? This is how we go exponential in our production industry.
let adCount = c.getHireAdVertCount(division.name);
let adPrice = c.getHireAdVertCost(division.name);
if (industry.makesProducts && adPrice < budget * 0.9) {
tasks.push(new Task(`Buy advertising campaign #${adCount + 1} for ${division.name}`, () => c.hireAdVert(division.name), adPrice, 60));
adCount++;
}
// Buy the first advertising campaign for non-product industries
if (adCount === 0 && !industry.makesProducts && adPrice < budget * 0.9) {
// Buy one advertising campaign in material markets
tasks.push(new Task(`Buy advertising campaign #${adCount + 1} for ${division.name}`, () => c.hireAdVert(division.name), adPrice, 60));
}
// Consider buying more advertising. All industires with MarketTA2, or a second one for production industries.
if ((industry.makesProducts || hasMarketTA2) && adPrice < budget * 0.5) {
tasks.push(new Task(`Buy advertising campaign #${adCount + 1} for ${division.name}`, () => c.hireAdVert(division.name), adPrice, 20));
}
// Should we spend any research?
let researchToSpend = division.research;
if (industry.makesProducts || hasMarketTA2) {
// Willing to spend in inverse proportion to how much stored science helps this product.
researchToSpend = division.research * (1 - industry.factors.Science);
}
let researchTypes = ['Hi-Tech R&D Laboratory', 'uPgrade: Fulcrum', 'uPgrade: Capacity.I', 'uPgrade: Capacity.II', 'Market-TA.I', 'Market-TA.II'];
for (const researchType of researchTypes) {
let hasResearch = false;
let cost = Infinity;
try {
hasResearch = c.hasResearched(division.name, researchType);
cost = c.getResearchCost(division.name, researchType);
} catch { }
if (!hasResearch && researchToSpend >= cost) {
log(ns, `INFO: Buying research project ${researchType} for ${cost} research points.`, 'info');
c.research(division.name, researchType);
researchToSpend -= cost;
} else if (!hasResearch && cost !== Infinity) {
if (verbose) log(ns, `Considered spending up to ${researchToSpend} of ${division.research} research on '${researchType}' but it would cost ${cost}.`);
// If we don't have this research, and can't afford to buy it, don't buy the next item on the list
break;
}
}
// If this is a production industry, see if we should be researching a new product.
if (industry.makesProducts) {
const maxProducts = getMaxProducts(ns, division.name);
let products = division.products.map((p) => c.getProduct(division.name, p));
let progress = products.map((p) => p.developmentProgress).filter((cmp) => cmp < 100)[0];
if (progress === undefined) progress = 100;
if (verbose) log(ns, `Projects: ${products.length}/${maxProducts}. Current project: ${progress}% complete.`);
if (progress === 100) {
// No product being researched. Consider creating a new one.
if (products.length < maxProducts) {
// We're not full, so go ahead.
spent += createNewProduct(ns, division);
budget -= spent;
} // Discontinue an existing product for a new one if we're not raising capital.
else {
// log(ns, `Considering creating a new product. rC: ${raisingCapital} eR: ${mf(extraReserve)}`);
if (raisingCapital === 0) {
if (extraReserve > 0 && myCorporation.funds > extraReserve) {
// We have enough money saved up. Time to ditch the product with the lowest budget.
products.sort((a, b) => budgetFromProductName(a.name) - budgetFromProductName(b.name));
let lowBudgetProduct = products[0];
c.discontinueProduct(division.name, lowBudgetProduct.name);
myCorporation = c.getCorporation();
}
// Try to create the Product. If it fails, it will set a reserve for us.
spent += createNewProduct(ns, division);
budget -= spent;
}
}
}
}
// Per city tasks.
for (const city of division.cities) {
// Can we expand any of our offices for more employees?
let officeSize = c.getOffice(division.name, city).size;
let seats = 15; // Grow by officeSize when small, then by 15
seats = Math.min(seats, officeSize);
let cost = c.getOfficeSizeUpgradeCost(division.name, city, seats);
if (industry.makesProducts && city === hqCity && cost < budget * 0.9) {
tasks.push(new Task(`Buy space for ${seats} more employees of ${division.name}/${city}`, () => upgradeOfficeSize(ns, division.name, city, seats), cost, 70));
} else if (industry.makesProducts && city !== hqCity && cost < budget * 0.1) {
tasks.push(new Task(`Buy space for ${seats} more employees of ${division.name}/${city}`, () => upgradeOfficeSize(ns, division.name, city, seats), cost, 70));
} else if (!industry.makesProducts && cost < budget * 0.4) {
tasks.push(new Task(`Buy space for ${seats} more employees of ${division.name}/${city}`, () => upgradeOfficeSize(ns, division.name, city, seats), cost, 70));
}
// Can we expand our warehouse space?
if (!c.hasWarehouse(division.name, city)) {
// We don't have a warehouse here. We should try to buy one in this city.
cost = c.getPurchaseWarehouseCost();
if (cost < budget * 0.5) {
tasks.push(new Task(`Buy warehouse ${division.name}/${city}`, () => c.purchaseWarehouse(division.name, city), cost, 80));
}
// Anything else we want to do with a city requires a warehouse, so just skip to the next city.
continue;
}
// We have a warehouse. Can we expand it?
let warehouse = c.getWarehouse(division.name, city);
// TODO: How much do we care about expanding the warehouse? We should base it on how much of an impact more materials would have.
cost = c.getUpgradeWarehouseCost(division.name, city);
if (cost < budget * 0.25) {
tasks.push(new Task(`Buy warehouse space for ${division.name}/${city}`, () => c.upgradeWarehouse(division.name, city), cost, 20));
}
// Turn on Smart Supply if we have it
if (c.hasUnlockUpgrade('Smart Supply') && !warehouse.smartSupplyEnabled) {
try {
if (verbose) log(ns, `Turning on Smart Supply for ${division.name}/${city}.`);
c.setSmartSupply(division.name, city, true);
} catch (e) {
log(ns, `ERROR: ${e}`);
}
}
// Can we buy more materials given the space we currently have?
// First, wait to cycle around to 'START' so we have a clean read on the warehouse levels.
await sleepWhileNotInStartState(ns);
// Calculate the required free space for a production cycle's worth of Material and products.
let warehouseSpaceRequiredForCycle = getReservedWarehouseSpace(ns, industry, division, city);
// We don't want to drive the corp too deeply negative with material purchases too soon, or
// else nothing else will ever be bought, and employees will never get happy.
let freeSpace = warehouse.size - warehouse.sizeUsed;
let warehouseSpaceAvailable = freeSpace - warehouseSpaceRequiredForCycle;
let tolerance = warehouseSpaceRequiredForCycle * 0.01;
let enoughSpace = warehouseSpaceAvailable >= tolerance; // Tiny safety margin
const satisfied = allEmployeesSatisfied(ns);
if ((budget > 0 || satisfied) && enoughSpace && raisingCapital === 0) {
// We have a decent amount of space to fill.
if (verbose) log(ns, ` ${division.name}/${city} warehouse: Wants +${warehouseSpaceAvailable} m² materials. ${warehouseSpaceRequiredForCycle} m² reserved.`);
for (const material of bonusMaterials) {
//if (industry.prodMats.includes(material)) continue; // Don't buy the materials we make.
let amt = (industry.scaledMaterialBonus[material] * warehouseSpaceAvailable) / 4;
// somewhat scale the amount we buy with our budget
let scaleFactor = Math.log10(budget) - 11; // Don't go full speed until our budget is $100b or more.
scaleFactor = Math.max(-2, scaleFactor);
scaleFactor = Math.min(0, scaleFactor);
let scale = Math.pow(10, scaleFactor);
// Only scale if we're waiting on employees to get happy.
if (!satisfied) amt = scale * amt;
c.buyMaterial(division.name, city, material, amt);
}
} else {
// Make sure we're not buying anything -- we're either out of room or out of money.
for (const material of bonusMaterials) {
c.buyMaterial(division.name, city, material, 0);
}
}
// It's possible to get into a situation where we've grown production faster than warehouse space.
if (warehouseSpaceAvailable < -tolerance) {
// Start clearing things out.
if (verbose) log(ns, ` ${division.name}/${city} warehouse: Wants to reserve ${warehouseSpaceRequiredForCycle} of ${warehouse.size} m², but only ${freeSpace} m² free! Selling some materials.`);
for (const material of allMaterials) {
let amt = c.getMaterial(division.name, city, material).qty;
let sellAmt = amt * 0.025;
c.sellMaterial(division.name, city, material, sellAmt.toFixed(2), 'MP*0.80');
}
} else {
// Make sure we reset. It should be safe to sell '0' here, because the things we want to sell will get reset in the price discovery loop.
for (const material of allMaterials) {
c.sellMaterial(division.name, city, material, '0', 'MP');
}
}
}
// Figure out which tasks we can afford to run, and in which order.
tasks.sort((a, b) => a.cost - b.cost).reverse();
tasks.sort((a, b) => a.priority - b.priority).reverse();
// Finally, run all the tasks we've collected.
spent += await runTasks(ns, tasks, budget);
if (spent > 0 && verbose) log(ns, `Spent ${ns.nFormat(spent, '0.0a')} of our budget of ${ns.nFormat(totalBudget, '0.0a')}.`);
return spent;
}
/**
* How much space do we need to leave fee in this warehouse for a full cycle of production?
* @param {NS} ns
* @param {Industry} industry
* @param {Division} division
* @param {string} city
* @returns {number}
*/
function getReservedWarehouseSpace(ns, industry, division, city) {
let rawMaterialSize = 0;
let warehouseSpaceRequiredForCycle = 0;
let maxProd = 0;
// Products take the same space as what was used to create it.
for (const matName in industry.reqMats) {
let matAmt = industry.reqMats[matName];
rawMaterialSize += matAmt * materialSizes[matName];
}
// Max production is based on a bunch of production multipliers.
maxProd = getMaximumProduction(ns, division, city);
// How many materials could we produce? Material sizes are predefined.
for (const matName of industry.prodMats) {
warehouseSpaceRequiredForCycle += materialSizes[matName] * maxProd;
}
if (industry.makesProducts) {
const maxProducts = getMaxProducts(ns, division.name);
warehouseSpaceRequiredForCycle += maxProducts * maxProd * rawMaterialSize;
}
// We produce stuff 10 times per cycle
warehouseSpaceRequiredForCycle *= 10;
// If we don't have automatic price discovery, we'll need some extra free space.
let hasMarketTA2 = c.hasResearched(division.name, 'Market-TA.II');
if (!hasMarketTA2) warehouseSpaceRequiredForCycle *= 3;
else warehouseSpaceRequiredForCycle *= 1.5;
return warehouseSpaceRequiredForCycle;
}
function getMaximumProduction(ns, division, city) {
let office = c.getOffice(division.name, city);
let officeMult = getOfficeProductivity(office); // Workers
let prodMult = division.prodMult; // Materials
let corpMult = 1 + 0.03 * c.getUpgradeLevel('Smart Factories'); // Corporate upgrades.
let resMult = 1;
if (c.hasResearched(division.name, 'Drones - Assembly')) resMult *= 1.2;
if (c.hasResearched(division.name, 'Self-Correcting Assemblers')) resMult *= 1.1;
return officeMult * prodMult * corpMult * resMult;
}
/**
* Try to create a new product for this division, with a budget at least twice the size of the last
* one we bought. If we don't have enough money, or all our product slots are full,
* then set a reserve for the desired amount.
*
* @param {NS} ns
* @param {Division} division
* @returns amount of money spent, if any.
*/
function createNewProduct(ns, division) {
let wantToSpend = 2e9; // $2b minimum.
let spent = 0;
let spentOnProducts = [];
try {
spentOnProducts = division.products
.map((p) => budgetFromProductName(p))
.sort((a, b) => a - b)
.reverse();
} catch (error) { }
if (spentOnProducts.length > 0) {
// If our products weren't named correctly default to assuming they were 2b, 4b, 8b...
wantToSpend = wantToSpend * Math.pow(2, spentOnProducts.length - 1);
wantToSpend = Math.max(spentOnProducts[0] * 2, wantToSpend, myCorporation.revenue * 100);
}
let productName = `${division.type}-${Math.log10(wantToSpend).toFixed(2)}`;
try {
c.makeProduct(division.name, hqCity, productName, wantToSpend / 2, wantToSpend / 2);
log(ns, `Creating new product '${productName}' for ${ns.nFormat(wantToSpend, '0.0a')}.`, 'info', true);
spent += wantToSpend;
extraReserve = 0;
} catch (e) {
// If we fail to create the product, just reserve the money we want to spend.
log(ns, `Reserving budget of ${ns.nFormat(wantToSpend, '0.0a')} for next product.`);
extraReserve = wantToSpend;
}
return spent;
}
function getMaxProducts(ns, divisionName) {
let maxProducts = 3;
if (c.hasResearched(divisionName, 'uPgrade: Capacity.I')) maxProducts++;
if (c.hasResearched(divisionName, 'uPgrade: Capacity.II')) maxProducts++;
return maxProducts;
}
/** @param {NS} ns
* @param waitForNext
*/
async function sleepWhileNotInStartState(ns, waitForNext = false) {
myCorporation = c.getCorporation();
if (waitForNext) {
while (myCorporation.state === 'START') {
await ns.sleep(50);
myCorporation = c.getCorporation();
}
}
let lastState = 'Unknown';
while (myCorporation.state !== 'START') {
if (verbose && myCorporation.state !== lastState) {
log(ns, `Waiting for corporation to move into the 'START' status. Currently: '${myCorporation.state}'.`);
lastState = myCorporation.state;
}
await ns.sleep(50); // Better keep the sleep short, in case we're in catch-up mode.
myCorporation = c.getCorporation();
}
myCorporation = c.getCorporation();
}
/**
* Buy the specified number of seats, and hire employees to fill them.
* @param {NS} ns
* @param {string} divisionName
* @param {string} city
* @param {number} seats
* @returns {boolean} returns true on success
*/
async function upgradeOfficeSize(ns, divisionName, city, seats) {
// First buy the new seats.
let success = false;
try {
if (seats > 0) c.upgradeOfficeSize(divisionName, city, seats);
success = true;
} catch (e) {
log(ns, `ERROR: Failed to upgrade office size by ${seats} seats in ${city}.`);
log(ns, `ERROR: ${e}`);
}
if (!success) return false;
/**
* Now that we have more office space, we need to hire and assign workers. Since
* worker assignment takes a long time, add them to a queue and we'll handle it
* later.
*/
fillSpaceQueue.push(`${divisionName}/${city}`);
return true;
}
async function fillOpenPositionsFromQueue(ns) {
myCorporation = c.getCorporation();
fillSpaceQueue = [...new Set(fillSpaceQueue)]; // Unique
// Try not to run past the end of a cycle..
while (['START'].includes(myCorporation.state) && fillSpaceQueue.length > 0) {
let office = fillSpaceQueue.shift();
let divisionName = office.split('/')[0];
let cityName = office.split('/')[1];
await fillOpenPositions(ns, divisionName, cityName);
myCorporation = c.getCorporation();
}
}
/**
* Fill any open positions with employees.
* @param {NS} ns
* @param {string} divisionName
* @param {string} cityName
*/
async function fillOpenPositions(ns, divisionName, cityName) {
if (options.mock) return;
let office = c.getOffice(divisionName, cityName);
let employees = office.employees.map((e) => c.getEmployee(divisionName, cityName, e));
let numUnassigned = employees.filter((e) => e.pos === 'Unassigned').length;
let openJobs = office.size - office.employees.length;
for (let i = 0; i < openJobs; i++) {
c.hireEmployee(divisionName, cityName);
}
openJobs += numUnassigned;
office = c.getOffice(divisionName, cityName);
if (openJobs > 0) {
if (verbose) log(ns, `Assigning ${openJobs} new employees to work in ${divisionName}/${cityName}`);
let employeesPerJob = Math.floor(office.employees.length / jobs.length);
let employeesLeft = office.employees.length % jobs.length;
for (let i = 0; i < jobs.length; i++) {
const job = jobs[i];
let num = employeesPerJob;
if (i < employeesLeft) num++;
// if (verbose) log(ns, `Assigning ${num} employees to work as ${job} in ${cityName}`);
if (num) await c.setAutoJobAssignment(divisionName, cityName, job, num);
}
}
}
/**
* Attempt to find a reasonably stable price for each product. This will take several production cycles to stabilize.
* @param {NS} ns
*/
async function doPriceDiscovery(ns) {
if (verbose) log(ns, `Doing price discovery for products.`);
myCorporation = c.getCorporation();
for (const division of myCorporation.divisions) {
const industry = industries.find((i) => i.name === division.type);
// If we have Market-TA.II researched, just let that work.
let hasMarketTA2 = c.hasResearched(division.name, 'Market-TA.II');
if (hasMarketTA2) {
for (const city of division.cities) {
// Default prices
industry.prodMats.forEach((material) => c.sellMaterial(division.name, city, material, 'MAX', 'MP'));
division.products.forEach((product) => c.sellProduct(division.name, city, product, 'MAX', 'MP'));
// Turn on automation.
industry.prodMats.forEach((material) => c.setMaterialMarketTA2(division.name, city, material, true));
division.products.forEach((product) => c.setProductMarketTA2(division.name, product, true));
}
// No need to do any other price discovery on this division.
continue;
}
// Materials are easy. Just sell them for Market price.
for (const materialName of industry.prodMats) {
for (const city of division.cities) {
// sometimes in low valuation nodes might not have a warehouse yet
if(!c.hasWarehouse(division.name, city)){
continue;
}
c.sellMaterial(division.name, city, materialName, 'PROD', 'MP');
}
}
// Go through each product, and see if the price needs to be adjusted. We can only
// adjust the price on a per-product basis (despite the UI letting you do it
// manually, the API is busted.)
let prevProductMultiplier = 1.0;
for (const productName of division.products) {
const product = c.getProduct(division.name, productName);
if (product.developmentProgress < 100) continue;
let sPrice = product.sCost;
// sPrice ought to be of the form 'MP * 123.45'. If not, we should use the price of the last product we calculated.
let lastPriceMultiplier = prevProductMultiplier;
try {
let sMult = sPrice.split('*')[1];
lastPriceMultiplier = Number.parseFloat(sMult);
} catch { }
let votes = [];
for (const city of division.cities) {
// sometimes in low valuation nodes might not have a warehouse yet
if(!c.hasWarehouse(division.name, city)){
continue;
}
// Each city is going to "vote" for how they want the price to be manipulated.
let qty = product.cityData[city][0];
let produced = product.cityData[city][1];
let sold = product.cityData[city][2];
// if (verbose) log(ns, `${division.name}/${city}:${product.name} (qty, prod, sold): ` + product.cityData[city].map((n) => nf(n)));
if (produced === sold && qty === 0) {
// We sold every item we produced. Vote to double the price.
votes.push(lastPriceMultiplier * 2);
}
// If we've accumulated a big stockpile, reduce our prices.
else if (qty > produced * 100) {