cortico-world-genesis 2.1.6 → 2.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3636 +0,0 @@
1
- import { fileURLToPath } from 'node:url';
2
- import type { ToolDef, World, WorldHost, WorldWebUiDecl } from 'cortico/core/types.ts';
3
- import { nowIso } from 'cortico/core/util.ts';
4
- import { CLIMATE_LABEL, KIND_LABEL, formatMoonLine, formatPlanetBlock, formatStarBlock } from './card.ts';
5
- import { describeCalendar, mostHabitable } from './clock.ts';
6
- import { surfaceDistanceKm } from './travel.ts';
7
- import type { GenesisConfigSection } from './config.ts';
8
- import { GENESIS_CONFIG_GROUP } from './config.ts';
9
- import {
10
- beginInterstellar,
11
- beginSurfaceMove,
12
- bodyProbeId,
13
- bodyKeyOf,
14
- burnBiomass,
15
- buySeeds,
16
- deployCounter,
17
- deployMonitor,
18
- deploySail,
19
- describeLocation,
20
- displayName,
21
- foundSite,
22
- harvestAt,
23
- installCore,
24
- setGreenhouseTarget,
25
- coldStoresAt,
26
- dryFood,
27
- nameBody,
28
- pressGenerator,
29
- REAL_MS_PER_HOUR,
30
- returnHome,
31
- sellToMerchant,
32
- sowAt,
33
- startGame,
34
- stargazeAt,
35
- sunAt,
36
- surveySite,
37
- timeText,
38
- tick,
39
- transitLabel,
40
- buildStructure,
41
- demolishStructure,
42
- depositTo,
43
- homePlanetOf,
44
- nowPlanetHours,
45
- storeCapacityKg,
46
- storeWeightKg,
47
- bagsInContainer,
48
- containerBagSlots,
49
- takeBagFromContainer,
50
- takeBagFromTerminal,
51
- CONTAINER_BAG_SLOTS,
52
- TERMINAL_BAG_SLOTS,
53
- routeContainer,
54
- storageRouteText,
55
- withdrawFrom,
56
- beginMobilityRepair,
57
- energyCapOf,
58
- beginBatteryUpgrade,
59
- beginSparkPlugUpgrade,
60
- beginSubagentUpgrade,
61
- beginTelescopeUpgrade,
62
- buildLabel,
63
- buildQueueBlocked,
64
- buildQueueSlots,
65
- canRepairMobilityCore,
66
- lookAround,
67
- mobilityCoreMaterials,
68
- mobilityCoreReady,
69
- sparkPlugCard,
70
- batteryCard,
71
- subagentCard,
72
- telescopeCard,
73
- waitFor,
74
- MOBILITY_CORE_COST_KJ,
75
- WAIT_MAX_HOME_HOURS,
76
- buyCylinders,
77
- buyChart,
78
- currentOrders,
79
- deliverOrder,
80
- habitatStatus,
81
- populationStatus,
82
- shipSupplyStatus,
83
- mutateBag,
84
- wakeHumans,
85
- habitatInteriorC,
86
- HABITAT_COMFORT_C,
87
- beginBlueprintsUpgrade,
88
- blueprintsCard,
89
- beginSpectrometerUpgrade,
90
- spectrometerCard,
91
- spectrometerScan,
92
- buyMerchandise,
93
- gridCapacityFor,
94
- gridKeyFor,
95
- planetHasGrid,
96
- rectifierAt,
97
- transferGridEnergy,
98
- tungstenCostFor,
99
- GRID_TAP_HOME_HOURS,
100
- GRID_TAP_KJ_PER_CALL,
101
- GRID_TAP_RANGE_KM,
102
- advanceArms,
103
- armsInCycle,
104
- relinkArm,
105
- relinkDuty,
106
- structurePowered,
107
- ARM_KG_PER_HOUR,
108
- ARM_RANGE_KM,
109
- ARM_MAX_PER_PLANET,
110
- round3,
111
- TUNGSTEN_START,
112
- type GameState,
113
- type Location,
114
- type WaitUntil,
115
- } from './game.ts';
116
- import { sparkPlugOutputKj } from './trade.ts';
117
- import { orderText } from './orders.ts';
118
- import { CHAPTER_TITLES, protocolStatus, protocolText } from './protocol.ts';
119
- import { NUTRIENT_NEEDS, SPECIES, SPECIES_IDS, RESOURCE_LABELS, bagWeightKg, type SpeciesId } from './flora.ts';
120
- import { RESIDENTS_PER_LABOR } from './life.ts';
121
- import { climateAt, siteKeyOf, type Site } from './site.ts';
122
- import { BUY_GOODS, SELL_GOODS, creditTier, dayIndexOf, sellPriceTable, shopOpen, shopWindowText, telescopeWindow } from './trade.ts';
123
- import { BUILD_SPECS, useCanned } from './game.ts';
124
- import { GENERATOR_COOLDOWN_MS } from './power.ts';
125
- import { GameStore } from './game-store.ts';
126
- import { GENESIS_DEFAULTS, GENESIS_LIMITS, validateSpec, type GenesisSpec, type StarSystem, type TerrestrialSurface } from './model.ts';
127
- import type { GenesisBody, GenesisDraft, GenesisPanelProtocol, GenesisPanelState, GenesisPlanetRow, GenesisProtocolPanel, GenesisSurfaceMap } from './panel-types.ts';
128
- import { GenesisStore } from './store.ts';
129
- import { stargazeText } from './stargaze.ts';
130
- import { deriveGenesisShape, describeGenesisMenu, GENESIS_SHAPE } from './system.ts';
131
- import { planetVisibility, terrainPatch, terrainPatchText, type TerrainBody } from './terrain.ts';
132
- import { targetBiomeFor, terraCellsFor, type TerraMap } from './terra.ts';
133
- import { guideText, guideTopics } from './guide.ts';
134
- import { infoText } from './info.ts';
135
-
136
- const ENV_PROMPT_FILE = fileURLToPath(new URL('./ENV_PROMPT.md', import.meta.url));
137
-
138
- /** 工具出错时把人话查出来,别把 stack 甩给模型�?*/
139
- function errorText(error: unknown): string {
140
- if (error instanceof Error) return error.message;
141
- return String(error);
142
- }
143
-
144
- /**
145
- * 种子的入口归丢�:纯数字串按数字,其余按原样丢�句话�? *
146
- * 引擎�?typeof 分叉(数字流 / 字符串流),扢�以这丢�步只能在入口做����? * 下沉�?createSystem() 会让旧存档重算的 specHash 对不上��? */
147
- function normalizeSeedValue(raw: unknown): GenesisSpec['seed'] {
148
- const text = typeof raw === 'string' ? raw.trim() : String(raw ?? '');
149
- if (!text) return GENESIS_DEFAULTS.seed;
150
- return /^\d{1,15}$/.test(text) ? Number(text) : text;
151
- }
152
-
153
- const NO_ARGS = { type: 'object', additionalProperties: false, properties: {} } as const;
154
-
155
- const CREATE_PARAMETERS = {
156
- type: 'object',
157
- additionalProperties: false,
158
- properties: {
159
- seed: {
160
- type: ['string', 'number'],
161
- description: '随机种子:任意字符串(推荐,64 位)�?0 �?2^53�? 的整数��同丢�种子 + 同一组旋钮永远得到同丢�个星系��?,
162
- },
163
- starMass: {
164
- type: 'number',
165
- minimum: GENESIS_LIMITS.starMass.min,
166
- maximum: GENESIS_LIMITS.starMass.max,
167
- description: '恒星质量(太阳质量)�?.0 是太阳;0.3 是暗红矮星,2.0 �?A 型星�?,
168
- },
169
- planetCount: {
170
- type: 'integer',
171
- minimum: GENESIS_LIMITS.planetCount.min,
172
- maximum: GENESIS_LIMITS.planetCount.max,
173
- description: `已废弃:行星数现在由种子决定�?{GENESIS_SHAPE.minPlanets}�?{GENESIS_SHAPE.maxPlanets} 颗),传了也会被忽略。`,
174
- },
175
- maxMoons: {
176
- type: 'integer',
177
- minimum: GENESIS_LIMITS.maxMoons.min,
178
- maximum: GENESIS_LIMITS.maxMoons.max,
179
- description: `已废弃:卫星上限固定为每�?${GENESIS_SHAPE.maxMoons} 颗,传了也会被忽略��`,
180
- },
181
- starName: {
182
- type: 'string',
183
- minLength: 1,
184
- maxLength: 12,
185
- description: '恒星的名字��开屢�定,之后丢�直沿用��?,
186
- },
187
- homeName: {
188
- type: 'string',
189
- minLength: 1,
190
- maxLength: 12,
191
- description: '母星(最宜居那颗行星)的名字。开屢�定,之后丢�直沿用��?,
192
- },
193
- },
194
- required: ['seed', 'starMass', 'starName', 'homeName'],
195
- } as const;
196
-
197
- const TERRAIN_PARAMETERS = {
198
- type: 'object',
199
- additionalProperties: false,
200
- properties: {
201
- lat: { type: 'number', minimum: -90, maximum: 90, description: '纬度�?90 �?90)��不传就是你现在站的位置�? },
202
- lon: { type: 'number', minimum: -180, maximum: 180, description: '经度�?180 �?180)��不传就是你现在站的位置�? },
203
- planetIndex: { type: 'integer', minimum: 1, description: '可��:看第几颗行星�? 起)。不传就是你现在扢�在的天体�? },
204
- moonIndex: { type: 'integer', minimum: 1, description: '可��:看该行星的第几颗卫星�? 起)�? },
205
- },
206
- } as const;
207
-
208
- const MOVE_PARAMETERS = {
209
- type: 'object',
210
- additionalProperties: false,
211
- properties: {
212
- kind: {
213
- type: 'string',
214
- enum: ['surface', 'interstellar', 'home'],
215
- description: 'surface = 在地表走过去;interstellar = 星际航行到看过的天体;home = 回母星(随时可以)��?,
216
- },
217
- lat: { type: 'number', minimum: -90, maximum: 90, description: 'surface 时的目标纬度�? },
218
- lon: { type: 'number', minimum: -180, maximum: 180, description: 'surface 时的目标经度�? },
219
- target: {
220
- type: 'string',
221
- description:
222
- 'interstellar 时的目标天体:可以用【未抵星�?xxxx】(观星报给你的编号,推荐)、p2 这种编号(行星)、p2-m1(卫星)。先 genesis_stargaze 看有哪些�?,
223
- },
224
- },
225
- required: ['kind'],
226
- } as const;
227
-
228
- const LOOK_PARAMETERS = { type: 'object', additionalProperties: false, properties: {} } as const;
229
-
230
- const WAIT_PARAMETERS = {
231
- type: 'object',
232
- additionalProperties: false,
233
- properties: {
234
- hours: {
235
- type: 'number',
236
- minimum: 0.1,
237
- maximum: WAIT_MAX_HOME_HOURS,
238
- description: '要等多少母星时(朢��?7 个母星日,即 168)��?,
239
- },
240
- until: {
241
- type: 'string',
242
- enum: ['dawn', 'dusk', 'ripe', 'built', 'arrive'],
243
- description: '等到某个事件:天�?/ 天黑 / 有作物成�?/ 工程完工 / 抵达。和 hours 二��一�?,
244
- },
245
- },
246
- } as const;
247
-
248
- const UPGRADE_PARAMETERS = {
249
- type: 'object',
250
- additionalProperties: false,
251
- properties: {
252
- id: {
253
- type: 'string',
254
- enum: ['mobility_core', 'telescope', 'spark_plug', 'battery', 'subagent', 'blueprints', 'spectrometer'],
255
- description: '要修的升级��不传就只列出清单��?,
256
- },
257
- },
258
- } as const;
259
-
260
- const NAME_PARAMETERS = {
261
- type: 'object',
262
- additionalProperties: false,
263
- properties: {
264
- name: { type: 'string', minLength: 1, maxLength: 12, description: '给这个天体的名字(最�?12 个字)��卫星会按模板自动起名,这里传什么都忽略�? },
265
- target: { type: 'string', description: '可��:给哪个天体起名��不传就是你现在扢�在的天体�? },
266
- },
267
- required: ['name'],
268
- } as const;
269
-
270
- const MONITOR_PARAMETERS = {
271
- type: 'object',
272
- additionalProperties: false,
273
- properties: {
274
- body: {
275
- type: 'string',
276
- description: '可��:给哪个天体装【环境监测器】(p2 �?p2-m1)��不传就是你现在扢�在的天体;已经装过就只读属����?,
277
- },
278
- },
279
- } as const;
280
-
281
- const SHOP_PARAMETERS = {
282
- type: 'object',
283
- additionalProperties: false,
284
- properties: {
285
- sell: { type: 'string', enum: [...SELL_GOODS.map((g) => g.id), 'survey'], description: '可��:要卖给商人的货��? },
286
- amount: { type: 'number', minimum: 0, description: '可��:卖多少(生物质这类按 kg,测绘数据按份)�? },
287
- },
288
- } as const;
289
-
290
- const BUY_PARAMETERS = {
291
- type: 'object',
292
- additionalProperties: false,
293
- properties: {
294
- kind: { type: 'string', enum: ['random', 'premium', 'giant_plant', 'cylinder', 'energy', 'tungsten', 'chart'], description: 'random = 随机基因种子(花 kJ);premium = 高级种子(花信用点);giant_plant = 大型植物(还没开通);cylinder = 高强度钢瓶(花信用点,多买有折扣);energy = 能量块(5,000 kJ�?20 信用点,直接进电池不损��);tungsten = �?1 份(700 信用点);chart = 星图�?00 信用点,每天丢�张):画丢�颗你还没见过的天体,拿到就不用等观星窗口�? },
295
- species: { type: 'string', enum: [...SPECIES_IDS], description: '要买哪种种子(kind=random/premium 时用)��? },
296
- count: { type: 'number', minimum: 1, maximum: 100, description: 'kind=cylinder 时买几个�? },
297
- },
298
- required: ['kind'],
299
- } as const;
300
-
301
- const SURVEY_PARAMETERS = {
302
- type: 'object',
303
- additionalProperties: false,
304
- properties: {
305
- site: { type: 'string', description: '可��:哪个站点。不传就用你脚下刚建的那个��? },
306
- },
307
- } as const;
308
-
309
- const SITE_PARAMETERS = {
310
- type: 'object',
311
- additionalProperties: false,
312
- properties: {
313
- lat: { type: 'number', minimum: -90, maximum: 90, description: '可��:纬度。不传就用你现在的位置��? },
314
- lon: { type: 'number', minimum: -180, maximum: 180, description: '可��:经度�? },
315
- },
316
- } as const;
317
-
318
- const PLANT_PARAMETERS = {
319
- type: 'object',
320
- additionalProperties: false,
321
- properties: {
322
- bag: { type: 'string', description: '哪袋种子(genesis_shop �?genesis_flora 里能看到袋子�?id)��? },
323
- site: { type: 'string', description: '可��:种到哪个站点。不传就是你脚下那个�? },
324
- count: { type: 'number', minimum: 1, maximum: 5, description: '可��:丢�次种几粒/几群,默认整袋��? },
325
- },
326
- required: ['bag'],
327
- } as const;
328
-
329
- const FLORA_PARAMETERS = {
330
- type: 'object',
331
- additionalProperties: false,
332
- properties: {
333
- site: { type: 'string', description: '可��:只看这个站点。不传就列你名下扢�有站点的作物�? },
334
- },
335
- } as const;
336
-
337
- const HARVEST_PARAMETERS = {
338
- type: 'object',
339
- additionalProperties: false,
340
- properties: {
341
- plant: { type: 'string', description: '哪株/哪群(genesis_flora 里的 id)��? },
342
- site: { type: 'string', description: '可��:它在哪个站点。不传就按当前站点找�? },
343
- },
344
- required: ['plant'],
345
- } as const;
346
-
347
- const BURN_PARAMETERS = {
348
- type: 'object',
349
- additionalProperties: false,
350
- properties: {
351
- kg: { type: 'number', minimum: 0.01, description: '烧多�?kg 干生物质�? kg �?3,750 kJ)��? },
352
- },
353
- required: ['kg'],
354
- } as const;
355
-
356
- const BUILD_PARAMETERS = {
357
- type: 'object',
358
- additionalProperties: false,
359
- properties: {
360
- kind: { type: 'string', enum: ['greenhouse', 'biome_changer'], description: 'greenhouse = 温室核心(罩住站点);biome_changer = 群系改变器(改一大片群系)��? },
361
- site: { type: 'string', description: '可��:建在哪个站点。不传就是你脚下那个�? },
362
- },
363
- required: ['kind'],
364
- } as const;
365
-
366
- const INSTALL_PARAMETERS = {
367
- type: 'object',
368
- additionalProperties: false,
369
- properties: {
370
- id: {
371
- type: 'string',
372
- enum: [
373
- 'monitor', 'counter', 'sail', 'greenhouse', 'biome_changer', 'cooler', 'heater', 'realism',
374
- 'pump', 'warehouse', 'drone_cluster', 'rocket', 'kiln', 'purifier', 'sealer', 'atmo_extractor',
375
- 'habitat', 'mutation_room', 'cold_store', 'inert_room', 'setpoint', 'miner', 'rectifier', 'terminal',
376
- 'storage_terminal', 'arm', 'planter', 'duty',
377
- 'carrier', 'wind', 'fire', 'converter',
378
- ],
379
- description:
380
- '装什么:monitor=环境监测器(150,000 kJ);counter=凌日计数器;sail=太阳能帆�?,000 kJ,建在脚下这块陆地上,产量按经纬度算);' +
381
- 'planter=种植盆(8,000 kJ,不用钨:只能同时种 3 粒,通电就夹�?22�?湿度 0.7—��极热极冷母星的第一口粮);' +
382
- 'greenhouse=温室核心;biome_changer=群系改变器;cooler=制冷核心;heater=制热核心;pump=水泵�? +
383
- 'warehouse=仓库(只能建在陆地站点,1,000 kg);drone_cluster=无人机集群(�?serves 丢�个仓库,远程取货 100 kJ/kg);rocket=运载火箭�?50 kg,星际航行时跟着走)�? +
384
- 'kiln=炭化炉(生物质→活��炭+灰);purifier=凢�化器(水+活��炭→饮用水);sealer=封装器(氧气+钢瓶→氧气瓶);' +
385
- 'atmo_extractor=大气提取器(O�?15% 时产氧);habitat=居所(住 20 人,每小时自动扣补给);mutation_room=辐射诱变室(种子→突变种子)�? +
386
- 'cold_store=冷库�?20,000 kJ�?200 kg,腐�?×0.5�?00 kJ/母星时);inert_room=惰��气体室�?5,000 kJ + 2 kg 纤维�?120 kg,腐�?×0.75,不耗电�? +
387
- '要求扢�在天体惰性气�?�?68% 且氧�?�?22%);' +
388
- 'miner=采矿机(40,000 kJ + 2 份钨,只能建在岩石行星海�?800 m 以上的陆地,采钨);' +
389
- 'rectifier=整流电塔�?0,000 kJ + 2 份钨,一颗行星只能一座;帆发的电进本地电网,靠近才能手动搬运�?0% 损��)�? +
390
- 'terminal=交易终端�?0,000 kJ + 2 份钨,只能建在陆地;连着无人机集群后,每天商人开张时自动�?target 指定的资源,' +
391
- '并且可以自动�?buySpecies 指定的随机种子,货先落在终端自己的缓冲里—��干�?200 kg、种�?20 袋,满了就不收)�? +
392
- 'storage_terminal=仓储终端�?0,000 kJ + 1 份钨;不是仓库,是一张编排表:决定哪几个容器、按仢�么优先级喂给交易终端�? +
393
- '�?feeds 指定它喂哪座交易终端,无人机集群连仓储终端;编排�?genesis_route 调)�? +
394
- 'arm=机械臂(15,000 kJ + 1 份钨;把 inputs 里几个容器的散货搬进 output,臂�?5 km�?0 kg/母星时��每颗行星最�?20 座;' +
395
- 'items 是资源白名单,不传就全搬;改线用 genesis_link)��? +
396
- 'carrier=空天母舰�?0,000 kJ + 40 份钨,哪里都能��;气��?冰巨星唯丢�的落脚点�?00 kg 货舱 + 20 袋位,最多挂 6 座子建筑(温室��种植盆、提取器、封装器、转换机、风机都行,群系改变�?采矿�?电塔不行),' +
397
- '能住 10 个人(叫醒时选它�?structureId,人从母舰自己的货舱吃饭);子建筑的 siteKey 写成 carrier:<母舰 id>)��? +
398
- 'wind=风力发电站(25,000 kJ + 3 份钨;风暴带群系 9,000 kJ/母星时,海拔 3,000 m 以上 1,500,其�?0)��? +
399
- 'fire=火力发电站(8,000 kJ + 1 份钨;烧生物�?纤维/木炭/干粮�?0 kg/母星时,灰进自带灰仓�?00 kg)��不能再从背包直接烧生物质,要发电就得建它)�? +
400
- 'converter=气液转换机(45,000 kJ + 3 份钨;按 recipes 白名单把 gas �?liquid:ammonia/methane/oxygen)��? +
401
- 'duty=值班终端�?0,000 kJ + 1 份钨,只能建在陆地;绑一座居扢� + 丢�个仓�?+ 朢��?6 个站点,以终端为圆心都在 5 km 内;' +
402
- '居所里每 5 个人算一份人手,自动收成熟作物(这份人手照看的站点多�?8%/份,单站封�?40%)��从值班仓库取种子补种��? +
403
- '取生物质补最缺的养分(氮除外);没有值班终端,人只吃饭不干活;改绑定�?genesis_duty)��?,
404
- },
405
- site: { type: 'string', description: '可��:装在哪个站点(温�?改变�?气��核�?仓库/水泵用);空天母舰上的子建筑�?carrier:<母舰 id>。不传就是脚下那个��? },
406
- extractGas: {
407
- type: 'string',
408
- enum: ['oxygen', 'ammonia', 'methane'],
409
- description: 'atmo_extractor 抽哪种气:oxygen(默认)/ ammonia / methane。大气里没有这种气就抽不出来�?,
410
- },
411
- recipes: {
412
- type: 'array',
413
- items: { type: 'string', enum: ['ammonia', 'methane', 'oxygen'] },
414
- description: 'converter(气液转换机)启用的配方白名单:只转列出来的那几种��?,
415
- },
416
- serves: { type: 'string', description: '无人机集群专用:连哪个仓库(传仓库的建筑 id)��? },
417
- tempC: { type: 'number', description: '温室设定点(℃);只�?id=setpoint 有效,不传表示回到自动模式��? },
418
- target: {
419
- type: 'string',
420
- description: '交易终端自动卖的资源 id(只�?id=terminal 有效):slag=尾矿(默认)、biomass=生物质��dry_food=干粮…��不传按尾矿�?,
421
- },
422
- buySpecies: {
423
- type: 'string',
424
- description:
425
- '交易终端自动买的种子物种(只�?id=terminal 有效):cyanobacteria / diatom / ice_alga / grass / moss / lichen�? +
426
- '每天朢��?1 袋��按随机种子阶梯价付 kJ;不传就不买�?,
427
- },
428
- feeds: {
429
- type: 'string',
430
- description: '仓储终端专用:它喂哪座交易终端(传交易终端的建筑 id)��不传就先建睢�,之后再接线�?,
431
- },
432
- inputs: {
433
- type: 'array',
434
- items: { type: 'string' },
435
- description: '机械臂专用:从哪几个容器取货(传容器 id,可多个)��容器要在这座臂 5 km 内��?,
436
- },
437
- output: {
438
- type: 'string',
439
- description: '机械臂专用:把货搬到哪个容器(仓�?/ 冷库 / 惰��气体室)��?,
440
- },
441
- items: {
442
- type: 'array',
443
- items: { type: 'string' },
444
- description: '机械臂专用:只搬这些资源(白名单,如 ["slag","tungsten"]);不传就全搬��?,
445
- },
446
- habitat: { type: 'string', description: '值班终端专用:给哪座居所派班组(传居扢�的建�?id)��? },
447
- store: { type: 'string', description: '值班终端专用:收成和种子走哪个仓库(传仓�?冷库/惰��气体室的建�?id)��? },
448
- sites: {
449
- type: 'array',
450
- items: { type: 'string' },
451
- description: '值班终端专用:管哪几个站点(1�? 个,站点 key �?"p3@12.4,-33.2")��?,
452
- },
453
- },
454
- required: ['id'],
455
- } as const;
456
-
457
- const STORE_PARAMETERS = {
458
- type: 'object',
459
- additionalProperties: false,
460
- properties: {
461
- action: {
462
- type: 'string',
463
- enum: ['deposit', 'withdraw', 'demolish', 'list', 'dry', 'grid', 'grid_in', 'grid_out', 'bags', 'take', 'use'],
464
- description:
465
- '�?/ �?/ �?/ 只看 / 烘干 / 看本地电�?/ 从电网搬电进电池 / 把电池的电��进电网 / 看终端的种子缓冲 / 从终端缓冲取丢�袋种�?/ 用掉罐装物资(目前只有液氨,施到脚下站点补氮)��?,
466
- },
467
- building: { type: 'string', description: '仓库、火箭或交易终端的建�?id(除 list/grid/dry 外都必填)��? },
468
- bag: { type: 'string', description: 'take 专用:取哪一袋(bags 列出来的 id);不传就取朢�老的丢�袋��? },
469
- resource: { type: 'string', description: '资源 id:biomass / phycocyanin / silica / antifreeze / fiber / lichen_acid / ash / survey�? },
470
- kg: { type: 'number', description: '多少千克(deposit/withdraw 必填�? 0)��? },
471
- kj: { type: 'number', description: `grid_in/grid_out 搬多�?kJ(默�?${GRID_TAP_KJ_PER_CALL},单次上�?${GRID_TAP_KJ_PER_CALL})��` },
472
- },
473
- required: ['action'],
474
- } as const;
475
-
476
- const RECIPES_PARAMETERS = { type: 'object', additionalProperties: false, properties: {} } as const;
477
-
478
- export const GENESIS_TOOL_DECLS: ReadonlyArray<Omit<ToolDef, 'handler'>> = [
479
- {
480
- name: 'genesis_menu',
481
- description: '看创世菜单:种子、恒星质量��行星数、卫星上限的可��范围��默认��,以及现在还能不能创世�?,
482
- tags: ['read'],
483
- parameters: NO_ARGS,
484
- },
485
- {
486
- name: 'genesis_create',
487
- description:
488
- '创世:按给定种子与旋钮生成恒星系,并给恒星和母星命名,写入存档后锁定(再调用不会覆盖,也不会再返回星卡����它不是查询手段)��? +
489
- '这是唯一丢�次��择的机会,调用前先跟对方确认参数与两个名字�?,
490
- tags: ['write'],
491
- parameters: CREATE_PARAMETERS,
492
- },
493
- {
494
- name: 'genesis_card',
495
- description: '读当前这颗星球的星卡:恒星��每颗行星的质量/半径/重力/温度/大气/宜居、卫星��?,
496
- tags: ['read'],
497
- parameters: NO_ARGS,
498
- },
499
- {
500
- name: 'genesis_terrain',
501
- description:
502
- '看��附近��的环境(一片格子,不是单个点)。不传坐标就是你现在站的地方,也可以指定任意天体与坐标��? +
503
- '岩石行星给群�?海拔+均温,气�?冰巨星给风暴带(等气压面),卫星给��卫星��群系��? +
504
- '补丁半径 = 配置里的地形视野 × 该天体的能见度��移动��中改回出发地那丢�片(附剩余时间)�?,
505
- tags: ['read'],
506
- parameters: TERRAIN_PARAMETERS,
507
- },
508
- {
509
- name: 'genesis_time',
510
- description: '看现在是仢�么时候(母星历法)��你在哪、有没有在移动��中。移动��中也能看��?,
511
- tags: ['read'],
512
- parameters: NO_ARGS,
513
- },
514
- {
515
- name: 'genesis_stargaze',
516
- description:
517
- '观星:能见度够的话,看见恒星和星等够亮的行星/卫星。看完之�?1 母星时内才能星际航行到看见的天体�?,
518
- tags: ['read'],
519
- parameters: NO_ARGS,
520
- },
521
- {
522
- name: 'genesis_move',
523
- description:
524
- '出发。地表移动按 600 km/星球时,星际航行�?2 AU/星球日����都不是瞬间到达,要等现实时间��? +
525
- '移动途中看不到环境,也做不了别的,到了会自动收到【已到达】��?,
526
- tags: ['write'],
527
- parameters: MOVE_PARAMETERS,
528
- },
529
- {
530
- name: 'genesis_name',
531
- description: '给你现在扢�在的天体起名(行星自己起,卫星按模板自动起)。没到过的地方不能起名��?,
532
- tags: ['write'],
533
- parameters: NAME_PARAMETERS,
534
- },
535
- {
536
- name: 'genesis_sun',
537
- description: '看此刻太阳在你头顶的位置:高度角、方位角、当地太阳时、白天还是夜里��不霢�要设备��?,
538
- tags: ['read'],
539
- parameters: NO_ARGS,
540
- },
541
- {
542
- name: 'genesis_transit',
543
- description: '看你现在在第几颗行星(或它的第几颗卫星)上��要先在扢�在天体部署��凌日计数器】,否则只会回��未安装凌日计数器������?,
544
- tags: ['read'],
545
- parameters: NO_ARGS,
546
- },
547
- {
548
- name: 'genesis_shop',
549
- description:
550
- '看商人(只在你脚下这颗母星上,每�?12:00�?3:00 营业):收什么��卖仢�么��今天的价,以及你的信用点与库存�? +
551
- '�?sell + amount 就是卖货:收成会换成信用点,信用点余额越高能买的东西越多�?,
552
- tags: ['read', 'write'],
553
- parameters: SHOP_PARAMETERS,
554
- },
555
- {
556
- name: 'genesis_buy',
557
- description:
558
- '买种子:random 用能量(kJ)买丢�袋随机基因种子;premium 用信用点买一袋更好的(要 500 信用点余额起)��? +
559
- '大型植物那条线还没开通��种子只有商人有,所以能量得先转告对方去按发电机、或者用太阳能帆攒��?,
560
- tags: ['write'],
561
- parameters: BUY_PARAMETERS,
562
- },
563
- {
564
- name: 'genesis_survey',
565
- description: '在你脚下的站点采测绘数据�?.1 母星时)。每颗行星的**每个群系**只认第一次;难去的地方(高纬、高山��海/冰盖/风暴带)�?2 份,别的 1 份��测绘数据可以卖给商人��?,
566
- tags: ['write'],
567
- parameters: SURVEY_PARAMETERS,
568
- },
569
- {
570
- name: 'genesis_site',
571
- description: '在你脚下的位置建丢��?1 km² 的站点(农场的地基)。一格(�?555 km)最�?3 个;冰盖、水面不行��?,
572
- tags: ['write'],
573
- parameters: SITE_PARAMETERS,
574
- },
575
- {
576
- name: 'genesis_plant',
577
- description: '把一袋种子种到站点上(一�?5 �?5 群)。水生藻类要种在水边湿地的站点上�?,
578
- tags: ['write'],
579
- parameters: PLANT_PARAMETERS,
580
- },
581
- {
582
- name: 'genesis_flora',
583
- description: '看作物:每个站点的每�?每群植物的阶段��进度��健康��生物量,以及仓库和种子袋��?,
584
- tags: ['read'],
585
- parameters: FLORA_PARAMETERS,
586
- },
587
- {
588
- name: 'genesis_harvest',
589
- description: '收获:大型植物结实后收一次(整株收完);藻类群落可以连续收,会留下接种量继续长��?,
590
- tags: ['write'],
591
- parameters: HARVEST_PARAMETERS,
592
- },
593
- {
594
- name: 'genesis_burn',
595
- description: '烧干生物质发电:1 kg �?3,750 kJ。收成的丢�部分可以烧掉换能量��?,
596
- tags: ['write'],
597
- parameters: BURN_PARAMETERS,
598
- },
599
- {
600
- name: 'genesis_install',
601
- description:
602
- '安装/建��一切设备,�?id 指定装什么:monitor(环境监测器�?,000,000 kJ + 0.1 母星时,装了才能看该天体的详细属性,母星装上则解锁恒星全貌)�? +
603
- 'counter(凌日计数器�?,000,000 kJ + 0.1 母星时)、sail(太阳能帆,20,000 kJ,建在脚下这块陆地上,产量按经纬度算)��? +
604
- 'greenhouse(温室核心,100,000 kJ + 0.1 母星时,把站点气候压�?0�?8℃,断电暂停)��? +
605
- 'biome_changer(群系改变器�?,000,000 kJ + 0.5 母星时,半径 1,500 km 逐格改��成温和气��:每格每母星时 1,250 kJ�?4 母星时改好一格,断电�?48 母星时���回原样)、cooler / heater(气候核心,10,000 kJ,装在有温室的站点上,各再撑 33℃)�? +
606
- 'pump(水泵,20,000 kJ + 0.5 母星时,给旱站点 +0.2 湿度)��warehouse(仓库,50,000 kJ,只建在陆地�?,000 kg)��? +
607
- 'drone_cluster(无人机集群�?00,000 kJ + 1 母星时,要传 serves 指一个仓库,远程取货 100 kJ/kg,不能跨行星)��? +
608
- 'rocket(运载火箭,500,000 kJ + 0.5 母星时,250 kg 的临时仓库,星际航行时自动跟睢�你)�?,
609
- tags: ['write'],
610
- parameters: INSTALL_PARAMETERS,
611
- },
612
- {
613
- name: 'genesis_store',
614
- description:
615
- '存取与拆除:action=deposit 把背包里的东西放进仓�?火箭;action=withdraw 取出来(在旁边免费,靠无人机 100 kJ/kg,火箭不算远程)�? +
616
- 'action=demolish 拆掉(不返能量,里面有东西就拆不了);action=list 只看扢�有仓库与火箭里有仢�么��还剩多少空间��?,
617
- tags: ['write'],
618
- parameters: STORE_PARAMETERS,
619
- },
620
- {
621
- name: 'genesis_recipes',
622
- description: '丢�张表看全:所有建�?设备的��价、��时、维护费、容量,以及每种作物霢�要什么养分��卖仢�么价。省得你猜��?,
623
- tags: ['read'],
624
- parameters: RECIPES_PARAMETERS,
625
- },
626
- {
627
- name: 'genesis_look',
628
- description:
629
- '看��此刻��这里��:脚下群系/海拔/气温、太阳与昼夜、近�?5×5 地形�?00 km 内的站点与建筑(含在建)、天上能看见仢�么,' +
630
- '朢�后一句��结。和 genesis_terrain 的分工:look 回答「我眼前」,terrain 回答「某个坐标附近����移动��中看不了��?,
631
- tags: ['read'],
632
- parameters: LOOK_PARAMETERS,
633
- },
634
- {
635
- name: 'genesis_wait',
636
- description:
637
- '原地等:�?hours 等这么多母星时(朢��?7 个母星日),或传 until(dawn 天亮 / dusk 天黑 / ripe 有作物成�?/ built 工程完工 / arrive 抵达)��? +
638
- '�?1 母星时步进,期间发生的事件会逐条报给你;满足条件会提前停�?,
639
- tags: ['write'],
640
- parameters: WAIT_PARAMETERS,
641
- },
642
- {
643
- name: 'genesis_upgrade',
644
- description:
645
- '船上的升级��不�?id:列出所有升级��需要什么��你现在有多少��带 id: "mobility_core":修机动核心�?00,000 kJ + 硅质�?1.5 kg、纤�?2 kg、抗冻蛋�?0.5 kg、藻蓝素 0.4 kg,��时 0.5 母星时)�? +
646
- '修好前过不了海,也进不了气��?冰巨星的大气层��?,
647
- tags: ['write'],
648
- parameters: UPGRADE_PARAMETERS,
649
- },
650
- {
651
- name: 'genesis_guide',
652
- description: '新手教程:不�?topic 给目录与第一篇;�?topic 给那丢�篇全文(start / plan / time / power / mine / farm / logistics / trade / upgrade / life / trouble)��不知道怎么玩��或对方问����么…��时查它�?,
653
- tags: ['read'],
654
- parameters: {
655
- type: 'object',
656
- additionalProperties: false,
657
- properties: {
658
- topic: {
659
- type: 'string',
660
- enum: ['start', 'plan', 'time', 'power', 'mine', 'farm', 'logistics', 'trade', 'upgrade', 'life', 'trouble'],
661
- description: '哪一篇;不传就是目录 + 弢�屢�篇��?,
662
- },
663
- },
664
- required: [],
665
- },
666
- },
667
- {
668
- name: 'genesis_protocol',
669
- description:
670
- '唤醒协议:把人类从休眠里叫醒�?12 件事,分三章(活下来 / 住得�?/ 叫醒他们)��? +
671
- '不带 id:列出进度与你缺仢�么��带 id 不做事����完成靠你去建��去攒��去种��?,
672
- tags: ['read'],
673
- parameters: {
674
- type: 'object',
675
- additionalProperties: false,
676
- properties: {},
677
- required: [],
678
- },
679
- },
680
- {
681
- name: 'genesis_orders',
682
- description:
683
- '星际商人的基因订单:今天他要仢�么(物种 + 某项基因下限 + 多少 kg + 多少信用点)�? +
684
- '�?order:交货(要手里有货,还要真种睢�对路基因的活株)。每天刷新��?,
685
- tags: ['read'],
686
- parameters: {
687
- type: 'object',
688
- additionalProperties: false,
689
- properties: {
690
- order: { type: 'string', description: '要交的订�?id;不传就只看今天的单子��? },
691
- },
692
- required: [],
693
- },
694
- },
695
- {
696
- name: 'genesis_mutate',
697
- description:
698
- '辐射诱变室:把一袋种子放进去,出�?3�? 颗基因抖动的突变种子(要站在诱变室所在站点)�?,
699
- tags: ['write'],
700
- parameters: {
701
- type: 'object',
702
- additionalProperties: false,
703
- properties: {
704
- bag: { type: 'string', description: '种子�?id(genesis_flora 里能看到)��? },
705
- },
706
- required: ['bag'],
707
- },
708
- },
709
- {
710
- name: 'genesis_wake',
711
- description: '叫醒人类:只�?12 条协议全部完成之后才行��叫醒后人类会住进居扢��?,
712
- tags: ['write'],
713
- parameters: {
714
- type: 'object',
715
- additionalProperties: false,
716
- properties: {
717
- habitat: { type: 'string', description: '可��:居所 id。不传用第一座��? },
718
- },
719
- required: [],
720
- },
721
- },
722
- {
723
- name: 'genesis_veins',
724
- description:
725
- '用质谱仪扫脚下的钨含量:�?5×5 格(�?2,000 km)的剩余矿量写成小表,并指出朢�富的丢�格在哪个方位、多远��? +
726
- '要先在��升级��里装好【质谱仪】;�?6 母星时才能扫丢�次��?,
727
- tags: ['read'],
728
- parameters: { type: 'object', additionalProperties: false, properties: {}, required: [] },
729
- },
730
- {
731
- name: 'genesis_route',
732
- description:
733
- '给��仓储终端��编排货源:把某个容器(仓库/冷库/惰��气体室)的优先级写进编排表�? +
734
- '数字越大越先被交易终端取走,0 朢�低;priority �?-1 就是把它从编排里拿掉(不参与自动交易)��? +
735
- '不传 storage 就找这颗行星上第丢�座仓储终端��?,
736
- tags: ['write'],
737
- parameters: {
738
- type: 'object',
739
- additionalProperties: false,
740
- properties: {
741
- container: { type: 'string', description: '容器的建�?id 或槽位号(面板上显示�?0�?�?…)�? },
742
- priority: { type: 'number', description: '优先�?0�? 的整数(0 朢�低��? 朢�高)�?1 表示踢出编排�? },
743
- storage: { type: 'string', description: '可��:仓储终端 id。不传用这颗行星上第丢�座��? },
744
- },
745
- required: ['container', 'priority'],
746
- },
747
- },
748
- {
749
- name: 'genesis_link',
750
- description:
751
- '给��机械臂】改线:把它的输入容器��输出容器��资源白名单重新接一遍(不传的字段保持原样)�? +
752
- '臂展 5 km、每颗行星最�?20 座;允许接成环,但会白烧电,每天提醒丢�次��?,
753
- tags: ['write'],
754
- parameters: {
755
- type: 'object',
756
- additionalProperties: false,
757
- properties: {
758
- id: { type: 'string', description: '机械臂的建筑 id(不传就用这座行星上第一座)�? },
759
- inputs: { type: 'array', items: { type: 'string' }, description: '新的输入容器 id 列表(可多个)��? },
760
- output: { type: 'string', description: '新的输出容器 id�? },
761
- items: { type: 'array', items: { type: 'string' }, description: '新的资源白名单;传空数组就是全搬�? },
762
- },
763
- required: [],
764
- },
765
- },
766
- {
767
- name: 'genesis_duty',
768
- description:
769
- '给����班终端】改绑定:换它派的居扢�、收成进的仓库��管的站点(不传的字段保持原样)�? +
770
- '居所、仓库��站点都要在终端 5 km 内;丢�座居扢�只能有一座��班终端�?,
771
- tags: ['write'],
772
- parameters: {
773
- type: 'object',
774
- additionalProperties: false,
775
- properties: {
776
- id: { type: 'string', description: '值班终端的建�?id(不传就用这座行星上第一座)�? },
777
- habitat: { type: 'string', description: '新的居所 id(人从哪来)�? },
778
- store: { type: 'string', description: '新的仓库 id(收成和种子走哪)��? },
779
- sites: { type: 'array', items: { type: 'string' }, description: '新的站点 key 列表�?�? 个)�? },
780
- },
781
- required: [],
782
- },
783
- },
784
- {
785
- name: 'genesis_reset',
786
- description: '删档重开:必须传 confirm: "DELETE"。会丢掉整颗星球与全部时间进度,只在对方明确要求时使用��?,
787
- tags: ['write'],
788
- parameters: {
789
- type: 'object',
790
- additionalProperties: false,
791
- properties: {
792
- confirm: { type: 'string', description: '固定�?DELETE�? },
793
- },
794
- required: ['confirm'],
795
- },
796
- },
797
- {
798
- name: 'genesis_info',
799
- description:
800
- '查一件东西的细则:传 query(id 或名字都行,能模糊搜),返回朢�接近�?3 条����第 1 条给完整卡(造价/耗时/维护/容量、作用����么用��坑),�?2�? 条各丢�行摘要��? +
801
- '建筑、资源��作物��升级��机制(能量、袋位��采掘疤、腐烂����班终端…)都能查��? +
802
- '不确定某�?id 是什么��报价多少����么接起来时先查它,不要瞎猜�?,
803
- tags: ['read'],
804
- parameters: {
805
- type: 'object',
806
- additionalProperties: false,
807
- properties: {
808
- query: {
809
- type: 'string',
810
- description: '要查�?id 或名字,例如 "greenhouse"�?温室"�?tungsten"�?腐烂"�?duty"�?,
811
- },
812
- },
813
- required: ['query'],
814
- },
815
- },
816
- ];
817
-
818
- export interface GenesisWorldOptions {
819
- cfg: GenesisConfigSection;
820
- timezone: string;
821
- dataDir: string;
822
- /** 便于测试注入固定时钟;默�?Date.now�?*/
823
- now?: () => number;
824
- }
825
-
826
- export class GenesisWorld implements World {
827
- readonly id = 'genesis';
828
-
829
- private host: WorldHost | null = null;
830
- private system: StarSystem | null = null;
831
- private game: GameState | null = null;
832
- private timer: ReturnType<typeof setTimeout> | null = null;
833
-
834
- private readonly store: GenesisStore;
835
- private readonly games: GameStore;
836
- private readonly now: () => number;
837
-
838
- constructor(private readonly opts: GenesisWorldOptions) {
839
- this.store = new GenesisStore({ dataDir: opts.dataDir });
840
- this.games = new GameStore({ dataDir: opts.dataDir });
841
- this.now = opts.now ?? Date.now;
842
- }
843
-
844
- envPromptVars(): Record<string, string> {
845
- const system = this.system;
846
- const game = this.game;
847
- if (!system) {
848
- return {
849
- 'genesis.summary': '还没有创世��可以调 genesis_menu 看可选范围,再决定要不要 genesis_create�?,
850
- 'genesis.planets': '(还没有行星�?,
851
- 'genesis.now': '还没创世,时间还没开始��?,
852
- };
853
- }
854
- const monitored = game?.monitors ?? [];
855
- const known = system.planets
856
- .map((p, index) => ({ p, key: `p${index + 1}` }))
857
- .filter(({ key }) => monitored.includes(key))
858
- .map(({ p, key }) => `${displayName(game!, key)}�?{KIND_LABEL[p.kind]}�?{p.aAU.toFixed(2)} AU�?{CLIMATE_LABEL[p.climate]}${p.habitable ? ',宜�? : ''}`)
859
- .join('\n');
860
- const now = game ? `${this.timeLine(game)}\n${this.energyLine(game)}` : '(这个存档还没有时间轴)';
861
- return {
862
- 'genesis.summary': `已创�?#${system.specHash}�?{system.star.spectralClass} 型恒星,${system.planets.length} 颗行星��`,
863
- 'genesis.planets': known || '(还没装【环境监测器】,看不到行星的详细属��)',
864
- 'genesis.now': now,
865
- };
866
- }
867
-
868
- tools(): ToolDef[] {
869
- return [
870
- this.menuTool(),
871
- this.createTool(),
872
- this.cardTool(),
873
- this.terrainTool(),
874
- this.timeTool(),
875
- this.stargazeTool(),
876
- this.moveTool(),
877
- this.nameTool(),
878
- this.sunTool(),
879
- this.transitTool(),
880
- this.shopTool(),
881
- this.buyTool(),
882
- this.surveyTool(),
883
- this.siteTool(),
884
- this.plantTool(),
885
- this.floraTool(),
886
- this.harvestTool(),
887
- this.burnTool(),
888
- this.installTool(),
889
- this.storeTool(),
890
- this.recipesTool(),
891
- this.lookTool(),
892
- this.waitTool(),
893
- this.upgradeTool(),
894
- this.guideTool(),
895
- this.protocolTool(),
896
- this.ordersTool(),
897
- this.mutateTool(),
898
- this.wakeTool(),
899
- this.veinsTool(),
900
- this.routeTool(),
901
- this.linkTool(),
902
- this.dutyTool(),
903
- this.resetTool(),
904
- this.infoTool(),
905
- ];
906
- }
907
-
908
- webUi(): WorldWebUiDecl {
909
- return {
910
- label: '创世�?,
911
- config: [GENESIS_CONFIG_GROUP],
912
- badges: [
913
- {
914
- label: '行星',
915
- value: this.system ? String(this.system.planets.length) : '未创�?,
916
- tone: this.system ? 'on' : 'plain',
917
- },
918
- ],
919
- panels: [
920
- {
921
- id: 'system',
922
- title: '这一颗星�?,
923
- description: '弢�屢�在这里创世:种子、恒星质量��行星数、卫星上限,还有恒星与母星的名字。写进存档后锁定,删档才能重选��?,
924
- getMethods: ['state', 'create', 'reset', 'map', 'press', 'monitor', 'sell', 'site', 'plant', 'harvest', 'burn', 'build', 'install', 'store', 'storeDo', 'look', 'veins', 'survey', 'wait', 'order', 'cylinder', 'chart', 'mutate', 'wake', 'preview'],
925
- },
926
- {
927
- id: 'upgrade',
928
- title: '升级',
929
- description: '船身上的东西。迫降时烧坏的机动核心在这里修����修好之前,海面和气态行星的大气都去不了�?,
930
- getMethods: ['state', 'repair'],
931
- },
932
- {
933
- id: 'protocol',
934
- title: '协议',
935
- description: '叫醒船上的人要做的事,分三章:活下来、住得下、叫醒他们��全部完成之后,这里的按钮就能把休眠舱打弢��?,
936
- getMethods: ['state', 'wake'],
937
- },
938
- {
939
- id: 'guide',
940
- title: '手册',
941
- description: '�?genesis_guide 同一份教程,翻着看比叫模型念丢�遍省事��正文在 src/guide/*.md,改文案不用碰代码��?,
942
- getMethods: ['topics', 'read', 'search'],
943
- },
944
- ],
945
- invoke: async (panel, method, args) => this.invoke(panel, method, args),
946
- promptDocs: [
947
- {
948
- key: 'worlds.genesis.envPrompt',
949
- title: '创世 · 环境提示�?,
950
- description: '告诉模型这颗星球是什么��创世只能来丢�次��时间��么走��它不该自己编行星��?,
951
- path: ENV_PROMPT_FILE,
952
- role: 'envPrompt',
953
- vars: [
954
- { name: 'genesis.summary', description: '丢�句话:创没创世��什么恒星��几颗行星��几颗宜居��? },
955
- { name: 'genesis.planets', description: '每颗行星丢�行:名字、类型��轨道��气候��是否宜居��? },
956
- { name: 'genesis.now', description: '现在的时间��所在地、有没有在移动��? },
957
- ],
958
- },
959
- ],
960
- };
961
- }
962
-
963
- async start(host: WorldHost): Promise<void> {
964
- this.host = host;
965
- try {
966
- const save = await this.store.read();
967
- this.system = save?.system ?? null;
968
- this.game = this.system ? await this.games.read(this.system) : null;
969
- } catch {
970
- this.system = null;
971
- this.game = null;
972
- }
973
- this.schedule();
974
- }
975
-
976
- async stop(): Promise<void> {
977
- this.host = null;
978
- if (this.timer) {
979
- clearTimeout(this.timer);
980
- this.timer = null;
981
- }
982
- }
983
-
984
- // —��?时间�?—��?
985
- /** 每次进工具都先把时间推到「现在��:到点就结算并推��已到达】��?*/
986
- private async sync(): Promise<void> {
987
- const system = this.system;
988
- const game = this.game;
989
- if (!system || !game) return;
990
- const result = tick(system, game, this.now());
991
- const changed =
992
- result.state !== game &&
993
- (result.state.lastFloraHomeHours !== game.lastFloraHomeHours ||
994
- result.state.energyKj !== game.energyKj ||
995
- result.state.transit !== game.transit ||
996
- result.state.builds !== game.builds ||
997
- result.state.structures !== game.structures);
998
- if (changed) {
999
- this.game = result.state;
1000
- await this.saveGame();
1001
- }
1002
- for (const event of result.events) await this.push(event.type, event.text);
1003
- this.schedule();
1004
- }
1005
-
1006
- /** 到点由定时器推事件;模型空闲时这�?internal 事件会把它的下一轮唤醒��?*/
1007
- private schedule(): void {
1008
- if (this.timer) {
1009
- clearTimeout(this.timer);
1010
- this.timer = null;
1011
- }
1012
- const transit = this.game?.transit;
1013
- if (!transit || !this.host) return;
1014
- const delay = Math.max(0, transit.arriveRealMs - this.now());
1015
- this.timer = setTimeout(() => {
1016
- this.timer = null;
1017
- void this.sync();
1018
- }, Math.min(delay, 2_147_000_000));
1019
- this.timer.unref?.();
1020
- }
1021
-
1022
- private async saveGame(): Promise<void> {
1023
- if (this.game) await this.games.write(this.game);
1024
- }
1025
-
1026
- private timeLine(game: GameState): string {
1027
- const name = game.calendar.homePlanetName;
1028
- const where = game.location ? `你在 ${describeLocation(game, game.location)}` : '你还没有落地';
1029
- const transit = game.transit;
1030
- if (!transit) return `${timeText(game, this.now())}�?{where},没有在移动。`;
1031
- const leftMs = Math.max(0, transit.arriveRealMs - this.now());
1032
- const leftHours = leftMs / game.msPerPlanetHour;
1033
- return `${timeText(game, this.now())}�?{where},正在移动到 ${describeLocation(game, transit.to)},` +
1034
- `还剩 ${leftHours.toFixed(2)} ${name}时(现实 ${(leftMs / REAL_MS_PER_HOUR).toFixed(2)} 小时)��`;
1035
- }
1036
-
1037
- private async readyState(): Promise<{ system: StarSystem; game: GameState } | { error: string }> {
1038
- await this.sync();
1039
- const system = this.system;
1040
- if (!system) return { error: '还没有创世��先�?genesis_menu,再决定要不�?genesis_create�? };
1041
- const game = this.game;
1042
- if (!game) return { error: '这个存档是旧版本(还没有时间轴),请 genesis_reset 之后重新创世�? };
1043
- return { system, game };
1044
- }
1045
-
1046
- private transitHead(game: GameState): string {
1047
- const transit = game.transit!;
1048
- const leftMs = Math.max(0, transit.arriveRealMs - this.now());
1049
- const leftHours = leftMs / game.msPerPlanetHour;
1050
- return `你在移动途中,还剩约 ${leftHours.toFixed(2)} ${game.calendar.homePlanetName}时` +
1051
- `(现�?${(leftMs / REAL_MS_PER_HOUR).toFixed(2)} 小时)��`;
1052
- }
1053
-
1054
- private transitNote(game: GameState): string | null {
1055
- if (!game.transit) return null;
1056
- return `${this.transitHead(game)}移动期间看不到环境,到了会自动收到��已到达】��`;
1057
- }
1058
-
1059
- /** 移动途中看环境时,回出发地那丢�片������你离开的地方长这样」��?*/
1060
- private departureEnvironment(system: StarSystem, game: GameState): string {
1061
- const from = game.transit!.from;
1062
- let body: TerrainBody;
1063
- try {
1064
- body = this.resolveBody(system, bodyKeyOf(from), game);
1065
- } catch {
1066
- return '出发地的地形读不出来(存档里的坐标对不上)��?;
1067
- }
1068
- const radiusKm = this.opts.cfg.viewBaseKm * planetVisibility(body.atmosphere);
1069
- const patch = terrainPatchText(terrainPatch(body, from.latDeg, from.lonDeg, radiusKm));
1070
- return `出发地环境����?{describeLocation(game, from)}:\n\n${patch}`;
1071
- }
1072
-
1073
- private visibilityOf(system: StarSystem, loc: Location): number {
1074
- const planet = system.planets[loc.planetIndex - 1];
1075
- if (!planet) return 0;
1076
- return loc.moonIndex ? 1 : planetVisibility(planet.atmosphere);
1077
- }
1078
-
1079
- // —��?面板 —��?
1080
- private async invoke(panel: string, method: string, args: unknown[]): Promise<unknown> {
1081
- if (panel === 'upgrade') {
1082
- switch (method) {
1083
- case 'state':
1084
- return this.upgradeState();
1085
- case 'repair':
1086
- return this.repairFromPanel(typeof args[0] === 'string' ? args[0] : 'mobility_core');
1087
- default:
1088
- throw new Error(`「升级��面板没有方法:${method}`);
1089
- }
1090
- }
1091
- if (panel === 'protocol') {
1092
- switch (method) {
1093
- case 'state':
1094
- return this.protocolPanelState();
1095
- case 'wake':
1096
- return this.wakeFromPanel(args[0]);
1097
- default:
1098
- throw new Error(`「协议��面板没有方法:${method}`);
1099
- }
1100
- }
1101
- if (panel === 'guide') {
1102
- switch (method) {
1103
- case 'topics':
1104
- return { topics: guideTopics() };
1105
- case 'read': {
1106
- const id = typeof args[0] === 'string' ? args[0] : '';
1107
- const picked = guideTopics().find((topic) => topic.id === id);
1108
- if (!picked) throw new Error(`没有这篇教程�?{id || '(�?'}。`);
1109
- return { id: picked.id, title: picked.title, text: guideText(picked.id) };
1110
- }
1111
- case 'search': {
1112
- const query = typeof args[0] === 'string' ? args[0] : '';
1113
- return { text: infoText(query) };
1114
- }
1115
- default:
1116
- throw new Error(`「手册��面板没有方法:${method}`);
1117
- }
1118
- }
1119
- if (panel !== 'system') throw new Error(`未知面板�?{panel}`);
1120
- switch (method) {
1121
- case 'state':
1122
- return this.panelState();
1123
- case 'create':
1124
- return this.createFromPanel(args[0]);
1125
- case 'preview':
1126
- return this.previewShape(args[0]);
1127
- case 'reset':
1128
- return this.resetFromPanel(args[0]);
1129
- case 'map':
1130
- return this.surfaceMap(args[0]);
1131
- case 'press':
1132
- return this.pressFromPanel();
1133
- case 'monitor':
1134
- return this.monitorFromPanel(args[0]);
1135
- case 'sell':
1136
- return this.floraAction('sell', args);
1137
- case 'site':
1138
- return this.floraAction('site', args);
1139
- case 'plant':
1140
- return this.floraAction('plant', args);
1141
- case 'harvest':
1142
- return this.floraAction('harvest', args);
1143
- case 'burn':
1144
- return this.floraAction('burn', args);
1145
- case 'build':
1146
- return this.floraAction('build', args);
1147
- case 'install':
1148
- return this.installFromPanel(args[0]);
1149
- case 'move':
1150
- return this.moveFromPanel(args[0]);
1151
- case 'demolish':
1152
- return this.demolishFromPanel(args[0]);
1153
- case 'store':
1154
- return this.storeFromPanel();
1155
- case 'storeDo':
1156
- return this.storeActionFromPanel(args);
1157
- case 'look':
1158
- return this.lookFromPanel();
1159
- case 'veins':
1160
- return this.veinsFromPanel();
1161
- case 'wait':
1162
- return this.waitFromPanel(args[0]);
1163
- case 'order':
1164
- return this.orderFromPanel(args[0]);
1165
- case 'cylinder':
1166
- return this.cylinderFromPanel(args[0]);
1167
- case 'chart':
1168
- return this.chartFromPanel();
1169
- case 'survey':
1170
- return this.surveyFromPanel();
1171
- case 'mutate':
1172
- return this.mutateFromPanel(args[0]);
1173
- case 'wake':
1174
- return this.wakeFromPanel(args[0]);
1175
- default:
1176
- throw new Error(`�?{panel}」面板没有方法:${method}`);
1177
- }
1178
- }
1179
-
1180
- /** 面板「装/建��:走同丢��?genesis_install,人类和模型用一套规则��?*/
1181
- private async installFromPanel(input: unknown): Promise<{ text: string; state: GenesisPanelState }> {
1182
- await this.sync();
1183
- const args = (input ?? {}) as { id?: unknown; serves?: unknown };
1184
- const tool = this.installTool();
1185
- const result = await tool.handler({ id: args.id, serves: args.serves } as Record<string, unknown>, {} as never);
1186
- const text = typeof result === 'string' ? result : result.text;
1187
- if (typeof result !== 'string' && result.failed) throw new Error(text);
1188
- return { text, state: await this.panelState() };
1189
- }
1190
-
1191
- /** 面板「看附近」:�?genesis_look 同一段文字,人类点一下就能读�?*/
1192
- private async lookFromPanel(): Promise<{ text: string }> {
1193
- await this.sync();
1194
- const system = await this.readSystem();
1195
- if (!system || !this.game) throw new Error('还没有创世��?);
1196
- try {
1197
- return { text: lookAround(system, this.game, this.now()).text };
1198
- } catch (error) {
1199
- return { text: errorText(error) };
1200
- }
1201
- }
1202
-
1203
- /** 面板「扫矿��:�?genesis_veins 同一段文字��?*/
1204
- private async veinsFromPanel(): Promise<{ text: string }> {
1205
- await this.sync();
1206
- const system = await this.readSystem();
1207
- if (!system || !this.game) throw new Error('还没有创世��?);
1208
- try {
1209
- const scanned = spectrometerScan(system, this.game, this.now());
1210
- this.game = scanned.state;
1211
- await this.saveGame();
1212
- return { text: scanned.text };
1213
- } catch (error) {
1214
- return { text: errorText(error) };
1215
- }
1216
- }
1217
-
1218
- /** 面板「等丢�会儿」:天亮/天黑/作物�?完工,推时钟并返回发生了仢�么��?*/
1219
- private async waitFromPanel(input: unknown): Promise<{ text: string; state: GenesisPanelState }> {
1220
- await this.sync();
1221
- const system = await this.readSystem();
1222
- if (!system || !this.game) throw new Error('还没有创世��?);
1223
- const until = typeof input === 'string' ? input : String((input as { until?: unknown } | null)?.until ?? 'dawn');
1224
- const waited = waitFor(system, this.game, this.now(), { until: until as never });
1225
- this.game = waited.state;
1226
- await this.saveGame();
1227
- if (waited.events.length > 0) for (const event of waited.events) await this.push(event.type, event.text);
1228
- return { text: waited.reason, state: await this.panelState() };
1229
- }
1230
-
1231
- /** 面板「交货��:把一张订单交掉,然后刷新面板�?*/
1232
- private async orderFromPanel(input: unknown): Promise<{ text: string; state: GenesisPanelState }> {
1233
- await this.sync();
1234
- if (!this.game) throw new Error('还没有创世��?);
1235
- const orderId = typeof input === 'string' ? input : String((input as { id?: unknown } | null)?.id ?? '');
1236
- const delivered = deliverOrder(this.game, orderId, this.now());
1237
- this.game = delivered.state;
1238
- await this.saveGame();
1239
- return { text: delivered.text, state: await this.panelState() };
1240
- }
1241
-
1242
- /** 面板「买钢瓶」:花信用点买几个高强度钢瓶�?*/
1243
- private async cylinderFromPanel(input: unknown): Promise<{ text: string; state: GenesisPanelState }> {
1244
- await this.sync();
1245
- if (!this.game) throw new Error('还没有创世��?);
1246
- const count = Math.max(1, Math.floor(Number(input) || 1));
1247
- const bought = buyCylinders(this.game, count, this.now());
1248
- this.game = bought.state;
1249
- await this.saveGame();
1250
- return { text: bought.text, state: await this.panelState() };
1251
- }
1252
-
1253
- /** 面板「买星图」:商人在的时��那张纸�?*/
1254
- private async chartFromPanel(): Promise<{ text: string; state: GenesisPanelState }> {
1255
- await this.sync();
1256
- const system = await this.readSystem();
1257
- if (!system || !this.game) throw new Error('还没有创世��?);
1258
- const bought = buyChart(system, this.game, this.now());
1259
- this.game = bought.state;
1260
- await this.saveGame();
1261
- return { text: bought.text, state: await this.panelState() };
1262
- }
1263
-
1264
- /** 面板「测绘一圈��:�?genesis_survey 同一条规则(每行星每群系只认第一次)�?*/
1265
- private async surveyFromPanel(): Promise<{ text: string; state: GenesisPanelState }> {
1266
- await this.sync();
1267
- const system = await this.readSystem();
1268
- if (!system || !this.game) throw new Error('还没有创世��?);
1269
- if (this.game.transit) throw new Error(`${this.transitHead(this.game)}移动期间看不到环境,到了会自动收到��已到达】��`);
1270
- const siteKey = this.resolveSite(this.game, undefined);
1271
- const result = surveySite(system, this.game, siteKey, this.now());
1272
- this.game = result.state;
1273
- await this.saveGame();
1274
- return { text: `${result.text}\n${this.inventoryLine(result.state)}`, state: await this.panelState() };
1275
- }
1276
-
1277
- /** 面板「诱变��:把一袋种子��进诱变室��?*/
1278
- private async mutateFromPanel(input: unknown): Promise<{ text: string; state: GenesisPanelState }> {
1279
- await this.sync();
1280
- if (!this.game) throw new Error('还没有创世��?);
1281
- const bagId = typeof input === 'string' ? input : String((input as { bag?: unknown } | null)?.bag ?? '');
1282
- const mutated = mutateBag(this.game, bagId, this.now());
1283
- this.game = mutated.state;
1284
- await this.saveGame();
1285
- return { text: mutated.text, state: await this.panelState() };
1286
- }
1287
-
1288
- /** 面板「叫醒人类��:协议全绿之后的那丢�下��?*/
1289
- private async wakeFromPanel(input: unknown): Promise<{ text: string; state: GenesisPanelState }> {
1290
- await this.sync();
1291
- if (!this.game) throw new Error('还没有创世��?);
1292
- const system = await this.readSystem();
1293
- if (!system) throw new Error('还没有创世��?);
1294
- const habitatId = typeof input === 'string' && input !== '' ? input : undefined;
1295
- const woke = wakeHumans(system, this.game, habitatId, this.now());
1296
- this.game = woke.state;
1297
- await this.saveGame();
1298
- return { text: woke.text, state: await this.panelState() };
1299
- }
1300
-
1301
- /** 面板「去某处」:按经纬度发起地表移动,返回移动中的状态��?*/
1302
- private async moveFromPanel(input: unknown): Promise<GenesisPanelState> {
1303
- await this.sync();
1304
- const system = await this.readSystem();
1305
- if (!system || !this.game) throw new Error('还没有创世��?);
1306
- const args = (input ?? {}) as { latDeg?: unknown; lonDeg?: unknown; target?: unknown };
1307
- if (typeof args.target === 'string' && args.target) {
1308
- const target = this.resolveBodyKey(system, this.game, args.target);
1309
- const result = beginInterstellar(system, this.game, target, this.now());
1310
- this.game = result.state;
1311
- await this.saveGame();
1312
- await this.push(result.event.type, result.event.text);
1313
- return this.panelState();
1314
- }
1315
- const lat = Number(args.latDeg);
1316
- const lon = Number(args.lonDeg);
1317
- if (!Number.isFinite(lat) || !Number.isFinite(lon)) throw new Error('要给出纬度和经度(数字)�?);
1318
- const result = beginSurfaceMove(system, this.game, Math.max(-90, Math.min(90, lat)), lon, this.now());
1319
- this.game = result.state;
1320
- await this.saveGame();
1321
- await this.push(result.event.type, result.event.text);
1322
- return this.panelState();
1323
- }
1324
-
1325
- /** 面板「拆掉��:和模型走同一�?demolishStructure 校验�?*/
1326
- private async demolishFromPanel(input: unknown): Promise<GenesisPanelState> {
1327
- await this.sync();
1328
- if (!this.game) throw new Error('还没有创世��?);
1329
- const id = typeof input === 'string' ? input : String((input as { id?: unknown } | null)?.id ?? '');
1330
- if (!id) throw new Error('要给出建�?id�?);
1331
- const text = demolishStructure(this.game, id);
1332
- const { [id]: _removed, ...stores } = this.game.stores;
1333
- this.game = { ...this.game, structures: this.game.structures.filter((s) => s.id !== id), stores };
1334
- await this.saveGame();
1335
- await this.push('genesis.demolished', text);
1336
- return this.panelState();
1337
- }
1338
-
1339
- /** 面板读仓库:丢�行摘�?+ 每个容器的结构化数据,方便画按钮�?*/
1340
- private async storeFromPanel(): Promise<{ list: string; containers: Array<{ id: string; kind: string; where: string; usedKg: number; capKg: number; contents: Array<{ resource: string; name: string; kg: number }>; bags?: number }> }> {
1341
- const state = await this.panelState();
1342
- const game = this.game;
1343
- if (!game) return { list: state.card ?? '还没有创世��?, containers: [] };
1344
- const containers = game.structures
1345
- .filter((s) => storeCapacityKg(s) > 0)
1346
- .map((s) => {
1347
- const store = game.stores[s.id] ?? {};
1348
- return {
1349
- id: s.id,
1350
- kind: s.kind,
1351
- where: s.kind === 'rocket' ? `p${s.dockedPlanetIndex ?? s.planetIndex}` : s.siteKey,
1352
- usedKg: Math.round(storeWeightKg(store) * 10) / 10,
1353
- capKg: storeCapacityKg(s),
1354
- contents: Object.entries(store).map(([resource, kg]) => ({
1355
- resource,
1356
- name: RESOURCE_LABELS[resource as keyof typeof RESOURCE_LABELS] ?? resource,
1357
- kg,
1358
- })),
1359
- ...(s.kind === 'terminal'
1360
- ? { bags: game.seedBags.filter((b) => b.at === s.id).length }
1361
- : {}),
1362
- };
1363
- });
1364
- return { list: this.storeList(game), containers };
1365
- }
1366
-
1367
- /** 面板上的�?�?拆:人类点按钮走的路径,和模型工具同丢�套规则��?*/
1368
- private async storeActionFromPanel(args: unknown[]): Promise<{ list: string; containers: unknown[] }> {
1369
- const action = String(args[0] ?? '');
1370
- const building = String(args[1] ?? '');
1371
- const resource = String(args[2] ?? '');
1372
- const kg = Number(args[3] ?? 0);
1373
- const synthetic: Record<string, unknown> = { action, building, resource, kg };
1374
- const tool = this.storeTool();
1375
- const result = await tool.handler(synthetic, {} as never);
1376
- const text = typeof result === 'string' ? result : result.text;
1377
- const after = await this.storeFromPanel();
1378
- return { ...after, list: text };
1379
- }
1380
-
1381
- private async readSystem(): Promise<StarSystem | null> {
1382
- const save = await this.store.read();
1383
- this.system = save?.system ?? null;
1384
- return this.system;
1385
- }
1386
-
1387
- /** 温室扢�在站点的室外温度;拿不到返回 null(面板滑杆只做参考)�?*/
1388
- private ambientFor(game: GameState, system: StarSystem | null, site: Site): number | null {
1389
- if (!system) return null;
1390
- const planet = system.planets[site.planetIndex - 1];
1391
- if (!planet || planet.surface.kind !== 'terrestrial') return null;
1392
- const climate = climateAt(
1393
- planet.surface,
1394
- site.latDeg,
1395
- site.lonDeg,
1396
- nowPlanetHours(game, this.now()),
1397
- game.calendar.planetDaysPerYear * 24,
1398
- planet.obliquityDeg,
1399
- );
1400
- return Math.round(climate.tempC * 10) / 10;
1401
- }
1402
-
1403
- /** 面板用的电网摘要:有没有塔��离多远、存了多少��?*/
1404
- private gridPanel(game: GameState): {
1405
- hasTower: boolean;
1406
- reachable: boolean;
1407
- storedKj: number;
1408
- capacityKj: number;
1409
- distanceKm: number;
1410
- towerSite: string | null;
1411
- } {
1412
- const loc = game.location;
1413
- const planetIndex = loc ? loc.planetIndex : game.homePlanetIndex;
1414
- const tower = rectifierAt(game, planetIndex);
1415
- const stored = Math.floor(game.grids[gridKeyFor(planetIndex)] ?? 0);
1416
- const cap = gridCapacityFor(this.system!, game, planetIndex);
1417
- if (!loc || !tower) {
1418
- return { hasTower: tower !== null, reachable: false, storedKj: stored, capacityKj: cap, distanceKm: 0, towerSite: tower?.siteKey ?? null };
1419
- }
1420
- const site = game.sites.find((s) => s.key === tower.siteKey);
1421
- const distance = site ? surfaceDistanceKm(site.latDeg, site.lonDeg, loc.latDeg, loc.lonDeg) : 0;
1422
- return {
1423
- hasTower: true,
1424
- reachable: distance <= GRID_TAP_RANGE_KM,
1425
- storedKj: stored,
1426
- capacityKj: cap,
1427
- distanceKm: Math.round(distance),
1428
- towerSite: tower.siteKey,
1429
- };
1430
- }
1431
-
1432
- private async panelState(): Promise<GenesisPanelState> {
1433
- const system = await this.readSystem();
1434
- const game = system ? this.game : null;
1435
- const monitored = game?.monitors ?? [];
1436
- const planets: GenesisPlanetRow[] = system
1437
- ? system.planets
1438
- .filter((_, index) => monitored.includes(`p${index + 1}`))
1439
- .map((p) => ({
1440
- name: p.name,
1441
- kindLabel: KIND_LABEL[p.kind],
1442
- aAU: p.aAU,
1443
- periodDays: p.periodDays,
1444
- climateLabel: CLIMATE_LABEL[p.climate],
1445
- habitable: p.habitable,
1446
- moons: p.moons.length,
1447
- }))
1448
- : [];
1449
- const bodies: GenesisBody[] = system
1450
- ? system.planets.flatMap((p, index) => {
1451
- const idx = index + 1;
1452
- const list: GenesisBody[] = [];
1453
- if (monitored.includes(`p${idx}`)) {
1454
- list.push({ key: `p${idx}`, label: `${idx} · ${p.name}`, kind: p.surface.kind });
1455
- }
1456
- for (let m = 0; m < p.moons.length; m += 1) {
1457
- if (monitored.includes(`p${idx}-m${m + 1}`)) {
1458
- list.push({ key: `p${idx}-m${m + 1}`, label: `${idx} · ${p.moons[m]!.name}`, kind: 'moon' });
1459
- }
1460
- }
1461
- // 商人卖的星图:还没监测,但已经知道它在那儿,面板要能直接点��去这里」��? const key = `p${idx}`;
1462
- if (!monitored.includes(key) && game && (game.charts ?? []).includes(key)) {
1463
- list.push({
1464
- key,
1465
- label: displayName(game, key),
1466
- kind: p.surface.kind === 'terrestrial' ? 'terrestrial' : 'isobaric',
1467
- charted: true,
1468
- });
1469
- }
1470
- return list;
1471
- })
1472
- : [];
1473
- return {
1474
- locked: system !== null,
1475
- card: system && game ? this.monitoredReport(system, game) : null,
1476
- planets,
1477
- bodies,
1478
- limits: GENESIS_LIMITS,
1479
- defaults: { ...GENESIS_DEFAULTS },
1480
- game: game
1481
- ? {
1482
- time: timeText(game, this.now()),
1483
- where: game.location ? describeLocation(game, game.location) : null,
1484
- transit: game.transit
1485
- ? `移动�?${describeLocation(game, game.transit.to)},还�?${(
1486
- Math.max(0, game.transit.arriveRealMs - this.now()) / game.msPerPlanetHour
1487
- ).toFixed(2)} ${game.calendar.homePlanetName}时`
1488
- : null,
1489
- calendar: describeCalendar(game.calendar),
1490
- }
1491
- : null,
1492
- power: game
1493
- ? {
1494
- energyKj: game.energyKj,
1495
- tungsten: game.tungsten,
1496
- ship: shipSupplyStatus(game),
1497
- grid: this.gridPanel(game),
1498
- sails: game.sails.length,
1499
- generatorKj: sparkPlugOutputKj(game.upgrades.sparkPlug),
1500
- sparkPlug: game.upgrades.sparkPlug,
1501
- capacityKj: energyCapOf(game),
1502
- battery: game.upgrades.battery,
1503
- generatorCooldownMs: Math.max(0, game.lastGeneratorRealMs + GENERATOR_COOLDOWN_MS - this.now()),
1504
- }
1505
- : null,
1506
- monitor: game
1507
- ? {
1508
- monitored,
1509
- starUnlocked: monitored.includes(`p${game.homePlanetIndex}`),
1510
- currentKey: game.location ? bodyKeyOf(game.location) : null,
1511
- currentMonitored: game.location ? monitored.includes(bodyKeyOf(game.location)) : false,
1512
- }
1513
- : null,
1514
- flora: game
1515
- ? {
1516
- credits: game.credits,
1517
- tier: creditTier(game.credits).label,
1518
- energyKj: game.energyKj,
1519
- shopOpen: shopOpen(nowPlanetHours(game, this.now()), game.upgrades.telescope),
1520
- shopWindow: shopWindowText(nowPlanetHours(game, this.now()), game.upgrades.telescope),
1521
- shopLevel: game.upgrades.telescope,
1522
- sites: game.sites.map((s) => {
1523
- const plants = game.plants[s.key] ?? [];
1524
- return {
1525
- key: s.key,
1526
- kind: s.kind === 'water' ? '水边湿地' : '旱地',
1527
- plants: plants.length,
1528
- ripe: plants.filter((p) => p.stage === 'ripe').length,
1529
- latDeg: s.latDeg,
1530
- lonDeg: s.lonDeg,
1531
- };
1532
- }),
1533
- inventory: Object.entries(game.inventory)
1534
- .filter(([, n]) => n > 0)
1535
- .map(([id, n]) => ({
1536
- id,
1537
- name: id === 'survey' ? '测绘数据' : RESOURCE_LABELS[id as keyof typeof RESOURCE_LABELS] ?? id,
1538
- amount: n,
1539
- })),
1540
- bags: game.seedBags.map((b) => ({ id: b.id, name: SPECIES[b.species].name, count: b.count, premium: b.premium })),
1541
- planters: game.structures
1542
- .filter((s) => s.kind === 'planter')
1543
- .map((s) => {
1544
- const key = `planter:${s.id}`;
1545
- const plants = game.plants[key] ?? [];
1546
- const site = game.sites.find((x) => x.key === s.siteKey);
1547
- return {
1548
- key,
1549
- siteKey: s.siteKey,
1550
- plants: plants.length,
1551
- ripe: plants.filter((p) => p.stage === 'ripe').length,
1552
- powered: structurePowered(game, s),
1553
- ambientC: site && system ? this.ambientFor(game, system, site) : null,
1554
- };
1555
- }),
1556
- }
1557
- : null,
1558
- greenhouses: game
1559
- ? game.structures
1560
- .filter((s) => s.kind === 'greenhouse')
1561
- .map((s) => {
1562
- const site = game.sites.find((x) => x.key === s.siteKey);
1563
- const ambient = site ? this.ambientFor(game, system, site) : null;
1564
- const target = s.targetTempC ?? null;
1565
- const delta = ambient !== null && target !== null ? Math.abs(target - ambient) : 0;
1566
- return {
1567
- siteKey: s.siteKey,
1568
- targetC: target,
1569
- ambientC: ambient,
1570
- deltaC: Math.round(delta * 10) / 10,
1571
- realismCores: (s.cores ?? []).filter((c) => c === 'realism').length,
1572
- coldStores: coldStoresAt(game, s.siteKey),
1573
- };
1574
- })
1575
- : [],
1576
- structures: game
1577
- ? game.structures.map((s) => {
1578
- const site = game.sites.find((x) => x.key === s.siteKey);
1579
- const store = game.stores[s.id] ?? {};
1580
- const contents = Object.entries(store)
1581
- .filter(([, kg]) => kg > 0)
1582
- .map(([id, kg]) => ({
1583
- name: id === 'survey' ? '测绘数据' : RESOURCE_LABELS[id as keyof typeof RESOURCE_LABELS] ?? id,
1584
- kg: Math.round(kg * 100) / 100,
1585
- }));
1586
- return {
1587
- id: s.id,
1588
- kind: s.kind,
1589
- label: BUILD_SPECS[s.kind].label,
1590
- siteKey: s.siteKey,
1591
- latDeg: site?.latDeg ?? 0,
1592
- lonDeg: site?.lonDeg ?? 0,
1593
- usedKg: Math.round(storeWeightKg(store) * 100) / 100,
1594
- capKg: storeCapacityKg(s),
1595
- contents,
1596
- sellTarget: s.sellTarget,
1597
- buySpecies: s.buySpecies,
1598
- slot: s.slot,
1599
- feeds: s.feeds,
1600
- routesText: s.kind === 'storage_terminal' ? storageRouteText(game!, s) : undefined,
1601
- armText: s.kind === 'arm'
1602
- ? `入:${(s.inputs ?? []).join('�?) || '�?} �?出:${s.output ?? '�?} · 搬:${s.items?.length ? s.items.join('�?) : '全部'} · ${ARM_KG_PER_HOUR} kg/时`
1603
- : undefined,
1604
- armCycle: s.kind === 'arm' ? armsInCycle(game!).some((a) => a.id === s.id) : undefined,
1605
- dutyText: s.kind === 'duty'
1606
- ? (() => {
1607
- const habitat = game!.structures.find((h) => h.id === s.habitat);
1608
- const hands = Math.floor((habitat?.awake ?? 0) / RESIDENTS_PER_LABOR);
1609
- const powered = structurePowered(game!, s);
1610
- const sites = (s.sites ?? []).length;
1611
- const state = !powered ? '断电停工' : hands <= 0 ? '居所里没人醒睢�' : '在干�?;
1612
- return `�?${hands} 份人手(${habitat?.id ?? '�?})�?收成�?${s.store ?? '�?} · �?${sites} 个站�?· ${state}`;
1613
- })()
1614
- : undefined,
1615
- interiorC: s.kind === 'habitat' && system
1616
- ? Math.round(habitatInteriorC(system, game!, s, this.now()) * 10) / 10
1617
- : undefined,
1618
- comfort: s.kind === 'habitat' && system
1619
- ? (() => {
1620
- const interior = habitatInteriorC(system, game!, s, this.now());
1621
- return interior < HABITAT_COMFORT_C.min ? 'cold' : interior > HABITAT_COMFORT_C.max ? 'hot' : 'ok';
1622
- })()
1623
- : undefined,
1624
- bags: s.kind === 'terminal'
1625
- ? game!.seedBags.filter((b) => b.at === s.id).length
1626
- : undefined,
1627
- };
1628
- })
1629
- : [],
1630
- builds: game
1631
- ? game.builds.map((b) => ({
1632
- kind: b.kind,
1633
- label: buildLabel(b.kind),
1634
- siteKey: b.siteKey,
1635
- leftHomeHours: Math.max(0, b.completeHomeHours - nowPlanetHours(game, this.now())),
1636
- }))
1637
- : [],
1638
- location: game?.location
1639
- ? { bodyKey: bodyKeyOf(game.location), latDeg: game.location.latDeg, lonDeg: game.location.lonDeg }
1640
- : null,
1641
- buildSlots: game ? buildQueueSlots(game) : 1,
1642
- buildQueueFull: game ? buildQueueBlocked(game, this.now()) !== null : false,
1643
- protocol: game ? this.protocolPanel(game) : null,
1644
- habitats: game ? habitatStatus(game).map((h, i) => ({ ...h, nickname: `居所 ${i + 1}` })) : [],
1645
- orders: game ? currentOrders(game, this.now()).map((o) => ({ ...o, species: SPECIES[o.species].name })) : [],
1646
- };
1647
- }
1648
-
1649
- private protocolPanel(game: GameState): GenesisPanelProtocol {
1650
- const rows = protocolStatus(game);
1651
- return {
1652
- tasks: rows.map((t) => ({
1653
- id: t.id,
1654
- chapter: CHAPTER_TITLES[t.chapter],
1655
- title: t.title,
1656
- done: t.done,
1657
- progress: `${Math.floor(t.progress * 100)}%`,
1658
- })),
1659
- done: rows.filter((t) => t.done).length,
1660
- total: rows.length,
1661
- complete: rows.every((t) => t.done),
1662
- awakened: game.awakened,
1663
- };
1664
- }
1665
-
1666
- /** 「协议��面板:三章十二�?+ 居所里的人与补给,好让人类一眼看出卡在哪�?*/
1667
- private protocolPanelState(): GenesisProtocolPanel {
1668
- if (!this.system) throw new Error('还没有创世��先 genesis_create�?);
1669
- if (!this.game) throw new Error('这个存档是旧版本(还没有协议),�?genesis_reset 之后重新创世�?);
1670
- const game = this.game;
1671
- const rows = protocolStatus(game);
1672
- const base = this.protocolPanel(game);
1673
- const chapters: GenesisProtocolPanel['chapters'] = [];
1674
- for (const [id, title] of Object.entries(CHAPTER_TITLES)) {
1675
- const chapter = Number(id);
1676
- const tasks = base.tasks.filter((t) => t.chapter === title);
1677
- chapters.push({
1678
- id: chapter,
1679
- title,
1680
- tasks,
1681
- done: tasks.filter((t) => t.done).length,
1682
- total: tasks.length,
1683
- });
1684
- }
1685
- const status = habitatStatus(game);
1686
- const first = status[0] ?? null;
1687
- return {
1688
- chapters,
1689
- done: base.done,
1690
- total: base.total,
1691
- complete: base.complete,
1692
- ready: rows.filter((t) => t.id !== 'wake' && t.done).length === rows.length - 1,
1693
- awakened: base.awakened,
1694
- habitat: first
1695
- ? { awake: first.awake, dormant: first.dormant, food: first.food, water: first.water, oxygen: first.oxygen, hoursLeft: first.hoursLeft }
1696
- : null,
1697
- population: populationStatus(game),
1698
- };
1699
- }
1700
-
1701
- private resolveBody(system: StarSystem, key: string, game?: GameState): TerrainBody {
1702
- const match = /^p(\d+)(?:-m(\d+))?$/.exec(key);
1703
- if (!match) throw new Error(`不认识的天体�?{key}`);
1704
- const planetIndex = Number(match[1]);
1705
- const planet = system.planets[planetIndex - 1];
1706
- if (!planet) throw new Error(`行星序号 ${planetIndex} 不存在(丢��?${system.planets.length} 颗)。`);
1707
- if (match[2] !== undefined) {
1708
- const moonIndex = Number(match[2]);
1709
- const moon = planet.moons[moonIndex - 1];
1710
- if (!moon) throw new Error(`�?{game ? displayName(game, planet.id) : planet.name}」没有第 ${moonIndex} 颗卫星(丢��?${planet.moons.length} 颗)。`);
1711
- return {
1712
- id: moon.id,
1713
- name: game ? displayName(game, moon.id) : moon.name,
1714
- meanTempK: planet.eqTempK,
1715
- obliquityDeg: 0,
1716
- atmosphere: 'none',
1717
- surface: moon.surface,
1718
- };
1719
- }
1720
- return {
1721
- id: planet.id,
1722
- name: game ? displayName(game, planet.id) : planet.name,
1723
- meanTempK: planet.meanTempK,
1724
- obliquityDeg: planet.obliquityDeg,
1725
- atmosphere: planet.atmosphere,
1726
- surface: planet.surface,
1727
- };
1728
- }
1729
-
1730
- /** 面板地图用:这颗行星上正在改造(或已改完)的格子与它们的目标群系�?*/
1731
- private terraFor(bodyId: string, surface: TerrestrialSurface): Array<{ i: number; j: number; p: number; targetBiome: number }> {
1732
- const game = this.game;
1733
- const match = /^p(\d+)/.exec(bodyId);
1734
- const planetIndex = match ? Number(match[1]) : 0;
1735
- if (!game || !planetIndex) return [];
1736
- return terraCellsFor(game.terra, planetIndex).map((cell) => ({
1737
- ...cell,
1738
- targetBiome: targetBiomeFor(surface, cell.i, cell.j),
1739
- }));
1740
- }
1741
-
1742
- /** 面板地图用:这颗行星上被采掘挖薄的格子(�?0�?)��?*/
1743
- private scarFor(bodyId: string): Array<{ i: number; j: number; v: number }> {
1744
- const game = this.game;
1745
- const match = /^p(\d+)/.exec(bodyId);
1746
- const planetIndex = match ? Number(match[1]) : 0;
1747
- if (!game || !planetIndex) return [];
1748
- const prefix = `p${planetIndex}:`;
1749
- const out: Array<{ i: number; j: number; v: number }> = [];
1750
- for (const [key, value] of Object.entries(game.scar)) {
1751
- if (!key.startsWith(prefix) || value <= 0) continue;
1752
- const parts = key.slice(prefix.length).split(':');
1753
- out.push({ i: Number(parts[0]), j: Number(parts[1]), v: Math.min(1, Math.max(0, value)) });
1754
- }
1755
- return out;
1756
- }
1757
-
1758
- private surfaceMap(input: unknown): GenesisSurfaceMap {
1759
- const system = this.system;
1760
- if (!system) throw new Error('还没有创世��先 genesis_create�?);
1761
- const body = this.resolveBody(system, String(input ?? ''), this.game ?? undefined);
1762
- const surface = body.surface;
1763
- switch (surface.kind) {
1764
- case 'terrestrial':
1765
- return {
1766
- kind: 'terrestrial',
1767
- name: body.name,
1768
- grid: surface.grid,
1769
- meanTempC: surface.meanTempC,
1770
- minElevationM: surface.minElevationM,
1771
- maxElevationM: surface.maxElevationM,
1772
- oceanFraction: surface.oceanFraction,
1773
- biome: surface.biome,
1774
- elevationM: surface.elevationM,
1775
- terra: this.terraFor(body.id, surface),
1776
- scar: this.scarFor(body.id),
1777
- };
1778
- case 'isobaric':
1779
- return {
1780
- kind: 'isobaric',
1781
- name: body.name,
1782
- grid: surface.grid,
1783
- meanTempC: surface.meanTempC,
1784
- minWindMps: surface.minWindMps,
1785
- maxWindMps: surface.maxWindMps,
1786
- biome: surface.biome,
1787
- };
1788
- case 'moon':
1789
- return {
1790
- kind: 'moon',
1791
- name: body.name,
1792
- grid: surface.grid,
1793
- meanTempC: surface.meanTempC,
1794
- biome: surface.biome,
1795
- };
1796
- }
1797
- }
1798
-
1799
- private async createFromPanel(input: unknown): Promise<GenesisPanelState> {
1800
- const draft = input as Partial<GenesisDraft> | undefined;
1801
- const seed = normalizeSeedValue(draft?.seed);
1802
- const spec: GenesisSpec = {
1803
- seed,
1804
- starMass: Number(draft?.starMass ?? GENESIS_DEFAULTS.starMass),
1805
- // 行星数与卫星上限由种子决定,面板不再提供这两个旋钮��? ...deriveGenesisShape(seed),
1806
- };
1807
- await this.ensureWorld(spec, {
1808
- starName: String(draft?.starName ?? '恒星').trim() || '恒星',
1809
- homeName: String(draft?.homeName ?? '母星').trim() || '母星',
1810
- });
1811
- return this.panelState();
1812
- }
1813
-
1814
- /** 创世前的预看:这颗种子会长出几颗行星、每颗几颗卫星��不生成世界,只回答形状�?*/
1815
- private previewShape(input: unknown): { planetCount: number; maxMoons: number; minPlanets: number; maxPlanets: number } {
1816
- const shape = deriveGenesisShape(normalizeSeedValue(input));
1817
- return { ...shape, minPlanets: GENESIS_SHAPE.minPlanets, maxPlanets: GENESIS_SHAPE.maxPlanets };
1818
- }
1819
-
1820
- private async resetFromPanel(input: unknown): Promise<GenesisPanelState> {
1821
- if (String(input ?? '') !== 'DELETE') throw new Error('删档要传 confirm: DELETE�?);
1822
- await this.reset();
1823
- return this.panelState();
1824
- }
1825
-
1826
- /** 面板上的动能发电机:只有人类会按;Agent 没有对应工具�?*/
1827
- private async pressFromPanel(): Promise<GenesisPanelState> {
1828
- await this.sync();
1829
- if (!this.game) throw new Error('还没有创世��?);
1830
- this.game = pressGenerator(this.game, this.now());
1831
- await this.saveGame();
1832
- return this.panelState();
1833
- }
1834
-
1835
- private async monitorFromPanel(input: unknown): Promise<GenesisPanelState> {
1836
- await this.sync();
1837
- const system = this.system;
1838
- const game = this.game;
1839
- if (!system || !game) throw new Error('还没有创世��?);
1840
- const key = String(input ?? '').trim() || (game.location ? bodyKeyOf(game.location) : '');
1841
- if (!key) throw new Error('不知道你站在哪��?);
1842
- if (!game.monitors.includes(key)) {
1843
- this.game = deployMonitor(system, game, this.now(), key);
1844
- await this.saveGame();
1845
- }
1846
- return this.panelState();
1847
- }
1848
-
1849
- private async createSystem(spec: GenesisSpec): Promise<{ created: boolean; system: StarSystem }> {
1850
- // 先校验再读存档:即使已经锁定,越界参数也要报错,而不是悄悄把旧星卡还回去�? validateSpec(spec);
1851
- const result = await this.store.createOnce(spec);
1852
- this.system = result.system;
1853
- if (result.created) {
1854
- await this.push(
1855
- 'genesis.created',
1856
- `创世完成 #${result.system.specHash}�?{result.system.star.spectralClass} 型恒星,${result.system.planets.length} 颗行星��`,
1857
- );
1858
- }
1859
- return { created: result.created, system: result.system };
1860
- }
1861
-
1862
- /**
1863
- * 创世 + 弢�屢�定位�? * - 没存档:生成星系,再�?Agent 放到朢�宜居行星的陆地上,时间从 0 弢�始;
1864
- * - 有星系但没时间轴�?.5.0 的旧档):用这次给的名字把时间轴补上�? * - 都已经有:不覆盖,只报告�? */
1865
- private async ensureWorld(spec: GenesisSpec, names: { starName: string; homeName: string }): Promise<{
1866
- created: boolean;
1867
- started: boolean;
1868
- system: StarSystem;
1869
- }> {
1870
- const result = await this.createSystem(spec);
1871
- if (this.game) return { created: result.created, started: false, system: result.system };
1872
- const game = this.startNewGame(result.system, names);
1873
- this.game = game;
1874
- await this.saveGame();
1875
- this.schedule();
1876
- return { created: result.created, started: true, system: result.system };
1877
- }
1878
-
1879
- private startNewGame(system: StarSystem, names: { starName: string; homeName: string }): GameState {
1880
- return startGame(system, { ...names, seed: system.spec.seed }, this.now());
1881
- }
1882
-
1883
- private async reset(): Promise<boolean> {
1884
- const deleted = await this.store.delete();
1885
- await this.games.delete();
1886
- this.system = null;
1887
- this.game = null;
1888
- if (this.timer) {
1889
- clearTimeout(this.timer);
1890
- this.timer = null;
1891
- }
1892
- if (deleted) await this.push('genesis.reset', '存档已删除,可以重新创世�?);
1893
- return deleted;
1894
- }
1895
-
1896
- private async push(type: string, text: string): Promise<void> {
1897
- const host = this.host;
1898
- if (!host) return;
1899
- try {
1900
- await host.pushEvent({
1901
- type,
1902
- ts: nowIso(this.opts.timezone),
1903
- source: this.id,
1904
- origin: 'internal',
1905
- senderKey: this.id,
1906
- text,
1907
- });
1908
- } catch {
1909
- // 事件推不出去不影响世界本身��? }
1910
- }
1911
-
1912
- // —��?工具 —��?
1913
- /**
1914
- * 把��未抵星�?xxxx」这种混淆编号翻�?p2 / p2-m1�? * 模型只看得到编号(看不到序号),扢�以观星之后拿编号�?target 也得能走�? */
1915
- private resolveBodyKey(system: StarSystem, game: GameState, raw: string): string {
1916
- const text = raw.trim();
1917
- if (!text) return '';
1918
- if (/^p\d+(?:-m\d+)?$/i.test(text)) return text.toLowerCase();
1919
- const probe = text
1920
- .replace(/^�?, '')
1921
- .replace(/�?/, '')
1922
- .replace(/^未抵星体\s*[--��]?\s*/, '')
1923
- .trim()
1924
- .toLowerCase();
1925
- const keys: string[] = [];
1926
- for (const [index, planet] of system.planets.entries()) {
1927
- keys.push(`p${index + 1}`);
1928
- for (let m = 1; m <= planet.moons.length; m++) keys.push(`p${index + 1}-m${m}`);
1929
- }
1930
- for (const key of keys) {
1931
- if (bodyProbeId(game, key) === probe) return key;
1932
- }
1933
- return text;
1934
- }
1935
-
1936
- private menuTool(): ToolDef {
1937
- return {
1938
- ...GENESIS_TOOL_DECLS[0]!,
1939
- handler: async () => {
1940
- const system = await this.readSystem();
1941
- const status = system
1942
- ? `已经有存档(#${system.specHash}),创世已锁定;要重选只�?genesis_reset。`
1943
- : '还没有存档,可以创世�?;
1944
- return `${describeGenesisMenu()}\n\n${status}`;
1945
- },
1946
- };
1947
- }
1948
-
1949
- private createTool(): ToolDef {
1950
- return {
1951
- ...GENESIS_TOOL_DECLS[1]!,
1952
- handler: async (args) => {
1953
- const starName = String(args.starName ?? '').trim();
1954
- const homeName = String(args.homeName ?? '').trim();
1955
- if (!starName || !homeName) {
1956
- return { text: '创世时要把两个名字都定下来:starName 是恒星名,homeName 是母星名(各 1�?2 字)�?, failed: true };
1957
- }
1958
- if (starName.length > 12 || homeName.length > 12) {
1959
- return { text: '名字朢��?12 个字�?, failed: true };
1960
- }
1961
- const spec: GenesisSpec = {
1962
- seed: typeof args.seed === 'string' ? args.seed : Number(args.seed),
1963
- starMass: Number(args.starMass),
1964
- // 行星数与卫星上限由种子决定:工具里还收这两个参数只是为了不打断��调用,真正的��以推导为准�? ...deriveGenesisShape(typeof args.seed === 'string' ? args.seed : Number(args.seed)),
1965
- };
1966
- try {
1967
- const result = await this.ensureWorld(spec, { starName, homeName });
1968
- if (!result.started) {
1969
- // 已经创世:这�?*不能**再回星卡。否则模型只要再调一�?create,就能绕�? // 【环境监测器】看到整张星卡(行星数��距离��气候��宜居��,连种子都会漏出来)��? return {
1970
- text: '这个世界已经创世过了:创世只有一次,这次没有覆盖任何东西,也没有返回星卡�? +
1971
- '想看天体详情,先�?genesis_card 看已监测的;要去没到过的地方了解它,得先过去装一台��环境监测器】��? +
1972
- '要彻底重来(会丢档)请先 genesis_reset�?,
1973
- failed: true,
1974
- };
1975
- }
1976
- const card = this.creationSummary(result.system, starName, this.game ?? undefined);
1977
- const game = this.game!;
1978
- const note = result.created
1979
- ? '已写入存档,自此锁定:再调用 genesis_create 不会覆盖�?
1980
- : '这个旧存档还没有时间轴,这次按你给的两个名字补上了��?;
1981
- return `${card}\n\n${note}\n\n${describeCalendar(game.calendar)}\n\n` +
1982
- `你站在母星��?{game.calendar.homePlanetName}」的陆地上(${game.location!.latDeg.toFixed(1)}°, ${game.location!.lonDeg.toFixed(1)}°),` +
1983
- `此刻记为 ${timeText(game, this.now())}—��从这里弢�始走。\n\n` +
1984
- `电池里还残留睢�迫降前的 ${Math.round(game.energyKj).toLocaleString('en-US')} kJ;太阳能帆坏了,` +
1985
- `要人类在面板上摇【动能发电机】,或��把第一茬作物烧成电。\n` +
1986
- `打印机里还有 ${game.tungsten} 份钨(每座建筑按份消耗,用完了只能去山上挖或找商人买),` +
1987
- `背包里还有三袋应急种子(硅藻、苔藓����生草,�?5 粒)。\n\n` +
1988
- `(远处的东西还看不清:想看哪颗天体的详细属��,得先到那儿装丢�台��环境监测器】��)`;
1989
- } catch (error) {
1990
- const message = error instanceof Error ? error.message : String(error);
1991
- // 创世失败也推丢�条事件:Agent 不该只看到工具回执就以为世界已经诞生�? await this.push('genesis.create_failed', `创世失败�?{message}(世界没有生成,存档也没有写入��)`);
1992
- return { text: message, failed: true };
1993
- }
1994
- },
1995
- };
1996
- }
1997
-
1998
- private cardTool(): ToolDef {
1999
- return {
2000
- ...GENESIS_TOOL_DECLS[2]!,
2001
- handler: async () => {
2002
- const ready = await this.readyState();
2003
- if ('error' in ready) return { text: ready.error, failed: true };
2004
- return this.monitoredReport(ready.system, ready.game);
2005
- },
2006
- };
2007
- }
2008
-
2009
- /** 创世那一刻能看到的东西:恒星概况 + 行星名单 + 母星那一条,不含细节�?*/
2010
- private creationSummary(system: StarSystem, starName: string, game?: GameState): string {
2011
- const home = mostHabitable(system);
2012
- const homeIndex = system.planets.indexOf(home) + 1;
2013
- const lines: string[] = [];
2014
- lines.push(`创世 #${system.specHash} · 种子 ${system.spec.seed}`);
2015
- lines.push(
2016
- `恒星�?{starName}」:${system.star.massSun.toFixed(2)} M�?· ${system.star.spectralClass} �?· ${system.star.luminositySun.toFixed(2)} L☉`,
2017
- );
2018
- lines.push(`行星 ${system.planets.length} 颗:`);
2019
- for (const [i, p] of system.planets.entries()) {
2020
- const mark = i + 1 === homeIndex ? ' �?母星' : '';
2021
- lines.push(` ${i + 1}. ${p.name}�?{KIND_LABEL[p.kind]}�?{p.aAU.toFixed(2)} AU · ${CLIMATE_LABEL[p.climate]}${p.habitable ? ' · 宜居' : ''}${mark}`);
2022
- }
2023
- return lines.join('\n');
2024
- }
2025
-
2026
- /** 已装监测器的天体清单—��这是模型唯丢�能看到��详细属性��的窗口�?*/
2027
- private monitoredReport(system: StarSystem, game: GameState): string {
2028
- const monitors = game.monitors;
2029
- if (monitors.length === 0) {
2030
- return '还没有部署��环境监测器】:现在看不到任何天体的详细属����走到想了解的天体上,或者用 body 指定丢�个已到过的天体,再调�?genesis_monitor�?;
2031
- }
2032
- const homeKey = `p${game.homePlanetIndex}`;
2033
- const lines: string[] = [`已部署��环境监测器】的天体�?{monitors.length}):`];
2034
- if (monitors.includes(homeKey)) {
2035
- lines.push('');
2036
- lines.push('恒星全貌(母星监测器解锁):');
2037
- lines.push(...formatStarBlock(system, game.names.star));
2038
- }
2039
- for (const key of monitors) {
2040
- const match = /^p(\d+)(?:-m(\d+))?$/.exec(key);
2041
- if (!match) continue;
2042
- const planet = system.planets[Number(match[1]) - 1];
2043
- if (!planet) continue;
2044
- lines.push('');
2045
- if (match[2] !== undefined) {
2046
- const moon = planet.moons[Number(match[2]) - 1];
2047
- if (moon) lines.push(`卫星 ${displayName(game, moon.id)}�?{displayName(game, planet.id)} 的第 ${match[2]} 颗):`);
2048
- if (moon) lines.push(formatMoonLine(planet, moon, displayName(game, moon.id)).trimStart());
2049
- continue;
2050
- }
2051
- lines.push(...formatPlanetBlock(planet, false, displayName(game, key)));
2052
- for (const [i, m] of planet.moons.entries()) {
2053
- if (monitors.includes(`${key}-m${i + 1}`)) lines.push(formatMoonLine(planet, m, displayName(game, m.id)));
2054
- }
2055
- }
2056
- return lines.join('\n');
2057
- }
2058
-
2059
- private terrainTool(): ToolDef {
2060
- return {
2061
- ...GENESIS_TOOL_DECLS[3]!,
2062
- handler: async (args) => {
2063
- const ready = await this.readyState();
2064
- if ('error' in ready) return { text: ready.error, failed: true };
2065
- const { system, game } = ready;
2066
- const note = this.transitNote(game);
2067
- if (note) return `${this.transitHead(game)}\n\n${this.departureEnvironment(system, game)}`;
2068
- const loc = game.location;
2069
- if (!loc) return { text: '还不知道自己在哪�?, failed: true };
2070
- const planetArg = args.planetIndex;
2071
- const moonArg = args.moonIndex;
2072
- const looking = planetArg !== undefined && planetArg !== null && String(planetArg) !== '';
2073
- const key = looking
2074
- ? `p${Number(planetArg)}${moonArg !== undefined && moonArg !== null && String(moonArg) !== '' ? `-m${Number(moonArg)}` : ''}`
2075
- : bodyKeyOf(loc);
2076
- const lat = args.lat !== undefined && args.lat !== null ? Number(args.lat) : looking ? 0 : loc.latDeg;
2077
- const lon = args.lon !== undefined && args.lon !== null ? Number(args.lon) : looking ? 0 : loc.lonDeg;
2078
- // 只有脚下这块地��和装了【环境监测器】的天体看得到����远处的东西不靠猜��? const here = bodyKeyOf(loc);
2079
- if (key !== here && !(game.monitors ?? []).includes(key)) {
2080
- return {
2081
- text: `这里没有【环境监测器】,你也还不�?{displayName(game, key)}—��看不到那片地形。先到那儿,或��在已监测的天体上看。`,
2082
- failed: true,
2083
- };
2084
- }
2085
- let body: TerrainBody;
2086
- try {
2087
- body = this.resolveBody(system, key, game);
2088
- } catch (error) {
2089
- return { text: error instanceof Error ? error.message : String(error), failed: true };
2090
- }
2091
- const radiusKm = this.opts.cfg.viewBaseKm * planetVisibility(body.atmosphere);
2092
- return terrainPatchText(terrainPatch(body, lat, lon, radiusKm));
2093
- },
2094
- };
2095
- }
2096
-
2097
- private timeTool(): ToolDef {
2098
- return {
2099
- ...GENESIS_TOOL_DECLS[4]!,
2100
- handler: async () => {
2101
- const ready = await this.readyState();
2102
- if ('error' in ready) return ready.error;
2103
- return `${this.timeLine(ready.game)}\n${this.energyLine(ready.game)}`;
2104
- },
2105
- };
2106
- }
2107
-
2108
- private energyLine(game: GameState): string {
2109
- const ship = shipSupplyStatus(game);
2110
- const pod =
2111
- ship.sleepers > 0
2112
- ? `\n睢�陆舱:粮 ${ship.food} kg、水 ${ship.water} L、氧 ${ship.oxygen} kg—��?{ship.sleepers} 个人睡着,大约还�?${ship.hoursLeft ?? 0} 母星时��`
2113
- : '';
2114
- return `能量�?{game.energyKj.toLocaleString('en-US')} / ${energyCapOf(game).toLocaleString('en-US')} kJ · 钨:${game.tungsten} 份(${game.sails.length} 台太阳能帆)�?{pod}`;
2115
- }
2116
-
2117
- /** 本地电网那一段:有没有塔、离多远、存了多少��能不能搬��?*/
2118
- private gridLine(game: GameState): string {
2119
- const loc = game.location;
2120
- if (!loc) return '本地电网:你还没有站到任何一颗星上��?;
2121
- const planetIndex = loc.planetIndex;
2122
- const tower = rectifierAt(game, planetIndex);
2123
- const key = gridKeyFor(planetIndex);
2124
- const stored = Math.floor(game.grids[key] ?? 0);
2125
- if (!tower) {
2126
- return `本地电网:这颗星还没有��整流电塔������帆发的电直接进电池,设备也没法在本地取电��`;
2127
- }
2128
- const site = game.sites.find((s) => s.key === tower.siteKey);
2129
- let distance = 0;
2130
- if (site) {
2131
- distance = surfaceDistanceKm(site.latDeg, site.lonDeg, loc.latDeg, loc.lonDeg);
2132
- }
2133
- const cap = gridCapacityFor(this.system!, game, planetIndex);
2134
- const reachable = distance <= GRID_TAP_RANGE_KM;
2135
- const head = `本地电网�?{stored.toLocaleString('en-US')} / ${cap.toLocaleString('en-US')} kJ`;
2136
- return reachable
2137
- ? `${head}(电塔就�?${distance.toFixed(0)} km 外,可以申请搬电:每 ${GRID_TAP_HOME_HOURS} 母星时最�?${GRID_TAP_KJ_PER_CALL.toLocaleString('en-US')} kJ,损�?10%)��`
2138
- : `${head}(电塔在 ${tower.siteKey},离�?${distance.toFixed(0)} km—��走�?${GRID_TAP_RANGE_KM} km 以内才能搬电)��`;
2139
- }
2140
-
2141
- private stargazeTool(): ToolDef {
2142
- return {
2143
- ...GENESIS_TOOL_DECLS[5]!,
2144
- handler: async () => {
2145
- const ready = await this.readyState();
2146
- if ('error' in ready) return { text: ready.error, failed: true };
2147
- const { system, game } = ready;
2148
- const note = this.transitNote(game);
2149
- if (note) return note;
2150
- if (!game.location) return { text: '还不知道自己在哪�?, failed: true };
2151
- const visibility = this.visibilityOf(system, game.location);
2152
- const result = stargazeAt(system, game, this.now());
2153
- if (!result.result) {
2154
- return `此刻大气能见�?${visibility.toFixed(2)},太浑浊了,看不到星星(观星霢�要大�?0.5)��`;
2155
- }
2156
- this.game = result.state;
2157
- await this.saveGame();
2158
- const text = stargazeText(result.result, (key) => displayName(result.state, key));
2159
- const windowHours = 1;
2160
- return `${text}\n\n(从现在�?${windowHours} ${game.calendar.homePlanetName}时内可以选择星际航行;` +
2161
- `过了这个窗口就要重新观星。)`;
2162
- },
2163
- };
2164
- }
2165
-
2166
- private moveTool(): ToolDef {
2167
- return {
2168
- ...GENESIS_TOOL_DECLS[6]!,
2169
- handler: async (args) => {
2170
- const ready = await this.readyState();
2171
- if ('error' in ready) return { text: ready.error, failed: true };
2172
- const { system, game } = ready;
2173
- const note = this.transitNote(game);
2174
- if (note) return note;
2175
- const kind = String(args.kind ?? '');
2176
- try {
2177
- let result: { state: GameState; event: { type: string; text: string } };
2178
- if (kind === 'surface') {
2179
- if (args.lat === undefined || args.lon === undefined) {
2180
- return { text: '地表移动要给目标坐标:lat �?lon�?, failed: true };
2181
- }
2182
- result = beginSurfaceMove(system, game, Number(args.lat), Number(args.lon), this.now());
2183
- } else if (kind === 'interstellar') {
2184
- const target = this.resolveBodyKey(system, game, String(args.target ?? ''));
2185
- if (!target) return { text: '星际航行要给目标:target(比�?p2、p2-m1,或者观星看到的【未抵星�?xxxx】)�?, failed: true };
2186
- result = beginInterstellar(system, game, target, this.now());
2187
- } else if (kind === 'home') {
2188
- result = returnHome(system, game, this.now());
2189
- } else {
2190
- return { text: `不认识的移动方式�?{kind}。kind 只能�?surface / interstellar / home。`, failed: true };
2191
- }
2192
- this.game = result.state;
2193
- await this.saveGame();
2194
- this.schedule();
2195
- const leftMs = result.state.transit!.arriveRealMs - this.now();
2196
- const leftHours = leftMs / result.state.msPerPlanetHour;
2197
- return `${result.event.text}\n预计 ${leftHours.toFixed(2)} ${game.calendar.homePlanetName}时后再到` +
2198
- `(现�?${(leftMs / REAL_MS_PER_HOUR).toFixed(2)} 小时)��移动��中看不到环境,到了会自动收到��已到达】��`;
2199
- } catch (error) {
2200
- return { text: error instanceof Error ? error.message : String(error), failed: true };
2201
- }
2202
- },
2203
- };
2204
- }
2205
-
2206
- private nameTool(): ToolDef {
2207
- return {
2208
- ...GENESIS_TOOL_DECLS[7]!,
2209
- handler: async (args) => {
2210
- const ready = await this.readyState();
2211
- if ('error' in ready) return { text: ready.error, failed: true };
2212
- const { system, game } = ready;
2213
- const note = this.transitNote(game);
2214
- if (note) return note;
2215
- const target = String(args.target ?? '').trim() || (game.location ? bodyKeyOf(game.location) : '');
2216
- try {
2217
- const result = nameBody(game, system, target, String(args.name ?? ''));
2218
- this.game = result.state;
2219
- await this.saveGame();
2220
- const automatic = target.includes('-m');
2221
- return automatic
2222
- ? `这颗卫星按模板叫�?{result.name}」��`
2223
- : `这里从此叫��?{result.name}」��`;
2224
- } catch (error) {
2225
- return { text: error instanceof Error ? error.message : String(error), failed: true };
2226
- }
2227
- },
2228
- };
2229
- }
2230
-
2231
- private installTool(): ToolDef {
2232
- return {
2233
- ...GENESIS_TOOL_DECLS[18]!,
2234
- handler: async (args) => {
2235
- const ready = await this.readyState();
2236
- if ('error' in ready) return { text: ready.error, failed: true };
2237
- const { system, game } = ready;
2238
- const note = this.transitNote(game);
2239
- if (note) return note;
2240
- const id = String(args.id ?? '').trim();
2241
- try {
2242
- if (id === 'monitor') {
2243
- const key = String(args.body ?? '').trim() || (game.location ? bodyKeyOf(game.location) : '');
2244
- if (!key) return { text: '不知道你站在哪;�?body 指定丢�个天体(比如 p2)��?, failed: true };
2245
- const already = game.monitors.includes(key);
2246
- let next = game;
2247
- if (!already) {
2248
- next = deployMonitor(system, game, this.now(), key);
2249
- this.game = next;
2250
- await this.saveGame();
2251
- }
2252
- const head = already ? '' : '装上了��环境监测器】:花费 150,000 kJ,过�?0.1 母星时��\n\n';
2253
- return `${head}${this.monitoredReport(system, next)}\n\n${this.energyLine(next)}`;
2254
- }
2255
- if (id === 'counter') {
2256
- const next = deployCounter(system, game, this.now());
2257
- this.game = next;
2258
- await this.saveGame();
2259
- return `装上了��凌日计数器】:花费 1,000,000 kJ,过�?0.1 母星时��现�?genesis_transit 能告诉你脚下是第几颗行星。\n${this.energyLine(next)}`;
2260
- }
2261
- if (id === 'sail') {
2262
- const next = deploySail(system, game, this.now());
2263
- this.game = next;
2264
- await this.saveGame();
2265
- const planet = system.planets[next.location!.planetIndex - 1]!;
2266
- const here = next.sails.filter((s) => s.bodyKey === `p${next.location!.planetIndex}`).length;
2267
- return `太阳能帆已部署:${displayName(next, planet.id)} �?(${next.location!.latDeg.toFixed(1)}°, ${next.location!.lonDeg.toFixed(1)}°),扣 6,000 kJ。这颗行星现在有 ${here} 台帆。` +
2268
- `它所在的纬度决定每天照多久:白天每母星时�?7,000 kJ,夜里不产��\n${this.energyLine(next)}`;
2269
- }
2270
- if (id === 'greenhouse' || id === 'biome_changer' || id === 'pump' || id === 'warehouse' || id === 'rocket'
2271
- || id === 'kiln' || id === 'purifier' || id === 'sealer' || id === 'atmo_extractor'
2272
- || id === 'habitat' || id === 'mutation_room' || id === 'cold_store' || id === 'inert_room'
2273
- || id === 'miner' || id === 'rectifier' || id === 'terminal' || id === 'storage_terminal' || id === 'arm'
2274
- || id === 'planter' || id === 'duty' || id === 'carrier' || id === 'wind' || id === 'fire' || id === 'converter') {
2275
- const rawSite = typeof args.site === 'string' ? args.site.trim() : '';
2276
- const siteKey = rawSite.startsWith('carrier:')
2277
- ? rawSite
2278
- : id === 'carrier'
2279
- ? 'sky:' + String(game.location?.planetIndex ?? 1)
2280
- : this.resolveSite(game, args.site);
2281
- const target = typeof args.target === 'string' && args.target.trim() ? args.target.trim() : undefined;
2282
- const buySpecies = typeof args.buySpecies === 'string' && args.buySpecies.trim()
2283
- ? (args.buySpecies.trim() as SpeciesId)
2284
- : undefined;
2285
- const feeds = typeof args.feeds === 'string' && args.feeds.trim() ? args.feeds.trim() : undefined;
2286
- const inputs = Array.isArray(args.inputs) ? args.inputs.map((v) => String(v).trim()).filter(Boolean) : undefined;
2287
- const output = typeof args.output === 'string' && args.output.trim() ? args.output.trim() : undefined;
2288
- const items = Array.isArray(args.items) ? args.items.map((v) => String(v).trim()).filter(Boolean) : undefined;
2289
- const habitatId = typeof args.habitat === 'string' && args.habitat.trim() ? args.habitat.trim() : undefined;
2290
- const storeId = typeof args.store === 'string' && args.store.trim() ? args.store.trim() : undefined;
2291
- const dutySites = Array.isArray(args.sites) ? args.sites.map((v) => String(v).trim()).filter(Boolean) : undefined;
2292
- const extractGas = typeof args.extractGas === 'string' && args.extractGas.trim() ? args.extractGas.trim() : undefined;
2293
- const recipes = Array.isArray(args.recipes) ? args.recipes.map((v) => String(v).trim()).filter(Boolean) : undefined;
2294
- const result = buildStructure(
2295
- system, game, id, siteKey, this.now(), undefined, target, buySpecies, feeds, inputs, output, items,
2296
- habitatId, storeId, dutySites, extractGas, recipes,
2297
- );
2298
- this.game = result.state;
2299
- await this.saveGame();
2300
- const extra = id === 'arm'
2301
- ? `\n它会�?${(inputs ?? []).join('�?)} 的散货按槽位顺序搬进 ${output}�?{ARM_KG_PER_HOUR} kg/母星时,臂展 ${ARM_RANGE_KM} km。要改线�?genesis_link。`
2302
- : id === 'duty'
2303
- ? (() => {
2304
- const habitat = result.state.structures.find((s) => s.id === habitatId);
2305
- const hands = Math.floor((habitat?.awake ?? 0) / RESIDENTS_PER_LABOR);
2306
- return `\n它会�?${habitatId} �?${hands} 份人手(�?${RESIDENTS_PER_LABOR} 人一份),收成进 ${storeId},管 ${(dutySites ?? []).length} 个站点��` +
2307
- (hands > 0 ? '' : '\n�?这座居所现在没人醒着—��先叫醒他们,班组才上工。要改绑定用 genesis_duty�?);
2308
- })()
2309
- : id === 'carrier'
2310
- ? '\n它现在是空的:货�?300 kg�?0 袋位�? 个挂载位。子建筑�?site �?carrier:<母舰 id>;叫醒人时把它当 structureId�?
2311
- : id === 'habitat'
2312
- ? (() => {
2313
- const site = result.state.sites.find((entry) => entry.key === siteKey);
2314
- if (!site) return '';
2315
- const probe = { id: 'pending-habitat', kind: 'habitat' as const, siteKey, planetIndex: site.planetIndex, builtHomeHours: 0 };
2316
- const interior = habitatInteriorC(system, result.state, probe, this.now());
2317
- const ok = interior >= HABITAT_COMFORT_C.min && interior <= HABITAT_COMFORT_C.max;
2318
- return ok
2319
- ? `\n这里室内大约 ${Math.round(interior)}℃,人住得下。`
2320
- : `\n�?这里室内大约 ${Math.round(interior)}℃����人只接�?${HABITAT_COMFORT_C.min}�?{HABITAT_COMFORT_C.max}℃,叫醒他们之前得挪地方,或者先把群系改过来。`;
2321
- })()
2322
- : '';
2323
- return `${result.text}${extra}\n${this.energyLine(result.state)}`;
2324
- }
2325
- if (id === 'drone_cluster') {
2326
- const siteKey = this.resolveSite(game, args.site);
2327
- const serves = String(args.serves ?? '').trim();
2328
- const result = buildStructure(system, game, 'drone_cluster', siteKey, this.now(), serves);
2329
- this.game = result.state;
2330
- await this.saveGame();
2331
- return `${result.text}\n现在只要在同丢�个行星上,就能用 100 kJ/kg 远程调这个仓库��\n${this.energyLine(result.state)}`;
2332
- }
2333
- if (id === 'realism') {
2334
- const siteKey = this.resolveSite(game, args.site);
2335
- const result = installCore(game, 'realism', siteKey);
2336
- this.game = result.state;
2337
- await this.saveGame();
2338
- return `${result.text}\n${this.energyLine(result.state)}`;
2339
- }
2340
- if (id === 'setpoint') {
2341
- const siteKey = this.resolveSite(game, args.site);
2342
- const raw = typeof args.tempC === 'number' ? args.tempC : null;
2343
- const result = setGreenhouseTarget(game, raw, siteKey);
2344
- this.game = result.state;
2345
- await this.saveGame();
2346
- return result.text;
2347
- }
2348
- if (id === 'cooler' || id === 'heater') {
2349
- const siteKey = this.resolveSite(game, args.site);
2350
- const result = installCore(game, id, siteKey);
2351
- this.game = result.state;
2352
- await this.saveGame();
2353
- return `${result.text}\n${this.energyLine(result.state)}`;
2354
- }
2355
- } catch (error) {
2356
- return { text: error instanceof Error ? error.message : String(error), failed: true };
2357
- }
2358
- return {
2359
- text: 'id 只能�?monitor / counter / sail / greenhouse / biome_changer / cooler / heater / pump / warehouse / drone_cluster / rocket / kiln / purifier / sealer / atmo_extractor / habitat / mutation_room / cold_store / inert_room / realism / setpoint / miner / rectifier�?,
2360
- failed: true,
2361
- };
2362
- },
2363
- };
2364
- }
2365
-
2366
- private sunTool(): ToolDef {
2367
- return {
2368
- ...GENESIS_TOOL_DECLS[8]!,
2369
- handler: async () => {
2370
- const ready = await this.readyState();
2371
- if ('error' in ready) return { text: ready.error, failed: true };
2372
- const { system, game } = ready;
2373
- const note = this.transitNote(game);
2374
- if (note) return note;
2375
- const loc = game.location;
2376
- if (!loc) return { text: '还不知道自己在哪�?, failed: true };
2377
- const sun = sunAt(system, game, this.now(), loc.latDeg, loc.lonDeg);
2378
- return `太阳:高度角 ${sun.altitudeDeg.toFixed(1)}°,方位角 ${sun.azimuthDeg.toFixed(1)}°,` +
2379
- `当地太阳�?${sun.localSolarHours.toFixed(2)} 点,${sun.isDay ? '白天' : '夜里'}。\n` +
2380
- `�? 时是弢�屢�那个经纬度的午夜;换到别处或换颗星以后,0 时不丢�定还是午夜����判断昼夜看这里的太阳高度角。)`;
2381
- },
2382
- };
2383
- }
2384
-
2385
- private transitTool(): ToolDef {
2386
- return {
2387
- ...GENESIS_TOOL_DECLS[9]!,
2388
- handler: async () => {
2389
- const ready = await this.readyState();
2390
- if ('error' in ready) return { text: ready.error, failed: true };
2391
- const { system, game } = ready;
2392
- const label = transitLabel(system, game);
2393
- if (!label) return '未安装凌日计数器�?;
2394
- return `你在${label}。`;
2395
- },
2396
- };
2397
- }
2398
-
2399
- /** 当前脚下朢�近的站点(没有就 null)��?*/
2400
- private currentSiteKey(game: GameState): string | null {
2401
- const loc = game.location;
2402
- if (!loc) return null;
2403
- const onPlanet = game.sites.filter((s) => s.planetIndex === loc.planetIndex);
2404
- if (onPlanet.length === 0) return null;
2405
- const exact = onPlanet.find((s) => s.key === siteKeyOf(loc.planetIndex, loc.latDeg, loc.lonDeg));
2406
- if (exact) return exact.key;
2407
- let best = onPlanet[0]!;
2408
- let bestDist = Number.POSITIVE_INFINITY;
2409
- for (const site of onPlanet) {
2410
- const dLat = site.latDeg - loc.latDeg;
2411
- const dLon = (site.lonDeg - loc.lonDeg) * Math.cos((loc.latDeg * Math.PI) / 180);
2412
- const dist = dLat * dLat + dLon * dLon;
2413
- if (dist < bestDist) {
2414
- bestDist = dist;
2415
- best = site;
2416
- }
2417
- }
2418
- return best.key;
2419
- }
2420
-
2421
- private resolveSite(game: GameState, raw: unknown): string {
2422
- const asked = String(raw ?? '').trim();
2423
- if (asked) {
2424
- if (asked.startsWith('planter:')) {
2425
- const id = asked.slice('planter:'.length);
2426
- if (!game.structures.some((s) => s.kind === 'planter' && s.id === id)) throw new Error(`没有这只种植盆:${id}`);
2427
- return asked;
2428
- }
2429
- if (!game.sites.some((s) => s.key === asked)) throw new Error(`没有这个站点�?{asked}`);
2430
- return asked;
2431
- }
2432
- const here = this.currentSiteKey(game);
2433
- if (!here) throw new Error('你脚下还没有站点,先�?genesis_site 建一个��?);
2434
- return here;
2435
- }
2436
-
2437
- private floraLines(game: GameState, only?: string): string {
2438
- const sites = only ? game.sites.filter((s) => s.key === only) : game.sites;
2439
- if (sites.length === 0) return '还没有站点��用 genesis_site 在脚下建丢�个,再用 genesis_plant 把种子种下去�?;
2440
- const lines: string[] = [];
2441
- for (const site of sites) {
2442
- const plants = game.plants[site.key] ?? [];
2443
- const ripe = plants.filter((p) => p.stage === 'ripe').length;
2444
- lines.push(`�?{site.key}�?{site.kind === 'water' ? '水边湿地' : '旱地'}�?{plants.length} �?群(可收 ${ripe})`);
2445
- for (const plant of plants) {
2446
- const spec = SPECIES[plant.species];
2447
- lines.push(
2448
- ` ${plant.id} · ${spec.name} · ${(plant.progress * 100).toFixed(0)}%` +
2449
- `${plant.stage === 'ripe' ? ' · 能收�? : ''} · 健康 ${plant.health}${plant.stress ? '(应濢��? : ''} · ${plant.biomassKg} kg`,
2450
- );
2451
- }
2452
- }
2453
- lines.push(this.inventoryLine(game));
2454
- if (game.seedBags.length > 0) {
2455
- lines.push(`种子袋:${game.seedBags.map((b) => `${b.id}�?{SPECIES[b.species].name} ×${b.count}${b.premium ? ',高�? : ''})`).join('�?)}`);
2456
- }
2457
- return lines.join('\n');
2458
- }
2459
-
2460
- private inventoryLine(game: GameState): string {
2461
- const parts = Object.entries(game.inventory)
2462
- .filter(([, n]) => n > 0)
2463
- .map(([k, n]) => `${k === 'survey' ? '测绘数据' : RESOURCE_LABELS[k as keyof typeof RESOURCE_LABELS]} ${n}`);
2464
- return `仓库�?{parts.length > 0 ? parts.join('�?) : '�?} · ${game.credits} 信用点(${creditTier(game.credits).label})�?${Math.floor(game.energyKj)} kJ`;
2465
- }
2466
-
2467
- private shopLines(system: StarSystem, game: GameState): string {
2468
- const hours = nowPlanetHours(game, this.now());
2469
- const planet = homePlanetOf(system, game);
2470
- const level = game.upgrades.telescope;
2471
- const open = shopOpen(hours, level);
2472
- const table = sellPriceTable(dayIndexOf(hours), level);
2473
- const lines = [
2474
- level === 0
2475
- ? `商人�?{displayName(game, planet.id)}?不—��母星上还没有商店����射电望远镜阵列】还没修好,星际商人听不到你的信号(genesis_upgrade �?id: "telescope")��`
2476
- : `商人�?{displayName(game, planet.id)}�?{open ? '正在营业' : '现在不在'}—��?{telescopeWindow(level)}。`,
2477
- this.inventoryLine(game),
2478
- '【收�? + table.map((g) => `${g.name} ${g.price} 信用�?${g.unit}(今天最�?${Number.isFinite(g.limit) ? g.limit : '不限'} ${g.unit})`).join('�?) +
2479
- '。今天的价会±15% 浮动�?,
2480
- '【卖�? +
2481
- BUY_GOODS.map((g) =>
2482
- g.stub
2483
- ? `${g.name}:这条贸易线还没弢�通`
2484
- : g.currency === 'kj'
2485
- ? `${g.name}�?{g.note})`
2486
- : `${g.name}(要余额 ${g.minCredits},每�?${g.dailyLimit} 袋)`,
2487
- ).join('�?),
2488
- ];
2489
- if (game.seedBags.length > 0) {
2490
- lines.push(`种子袋:${game.seedBags.map((b) => `${b.id}�?{SPECIES[b.species].name} ×${b.count})`).join('�?)}`);
2491
- }
2492
- return lines.join('\n');
2493
- }
2494
-
2495
- private shopTool(): ToolDef {
2496
- return {
2497
- ...GENESIS_TOOL_DECLS[10]!,
2498
- handler: async (args) => {
2499
- const ready = await this.readyState();
2500
- if ('error' in ready) return { text: ready.error, failed: true };
2501
- const { system, game } = ready;
2502
- const note = this.transitNote(game);
2503
- if (note) return note;
2504
- const sell = String(args.sell ?? '').trim();
2505
- if (!sell) return this.shopLines(system, game);
2506
- try {
2507
- const result = sellToMerchant(game, sell as never, Number(args.amount ?? 1), this.now());
2508
- this.game = result.state;
2509
- await this.saveGame();
2510
- return `${result.text}\n${this.shopLines(system, result.state)}`;
2511
- } catch (error) {
2512
- return { text: error instanceof Error ? error.message : String(error), failed: true };
2513
- }
2514
- },
2515
- };
2516
- }
2517
-
2518
- private buyTool(): ToolDef {
2519
- return {
2520
- ...GENESIS_TOOL_DECLS[11]!,
2521
- handler: async (args) => {
2522
- const ready = await this.readyState();
2523
- if ('error' in ready) return { text: ready.error, failed: true };
2524
- const { system, game } = ready;
2525
- const note = this.transitNote(game);
2526
- if (note) return note;
2527
- const kind = String(args.kind ?? '');
2528
- if (kind === 'giant_plant') return { text: '这条贸易线还没开通��?, failed: true };
2529
- if (kind === 'cylinder') {
2530
- const count = Math.max(1, Math.floor(Number(args.count ?? 1)));
2531
- try {
2532
- const bought = buyCylinders(game, count, this.now());
2533
- this.game = bought.state;
2534
- await this.saveGame();
2535
- return `${bought.text}\n${this.inventoryLine(bought.state)}`;
2536
- } catch (error) {
2537
- return { text: error instanceof Error ? error.message : String(error), failed: true };
2538
- }
2539
- }
2540
- if (kind === 'chart') {
2541
- try {
2542
- const bought = buyChart(system, game, this.now());
2543
- this.game = bought.state;
2544
- await this.saveGame();
2545
- return bought.text;
2546
- } catch (error) {
2547
- return { text: error instanceof Error ? error.message : String(error), failed: true };
2548
- }
2549
- }
2550
- if (kind === 'energy' || kind === 'tungsten') {
2551
- try {
2552
- const bought = buyMerchandise(game, kind, this.now());
2553
- this.game = bought.state;
2554
- await this.saveGame();
2555
- return `${bought.text}\n${this.inventoryLine(bought.state)}`;
2556
- } catch (error) {
2557
- return { text: error instanceof Error ? error.message : String(error), failed: true };
2558
- }
2559
- }
2560
- if (kind !== 'random' && kind !== 'premium') {
2561
- return { text: 'kind 只能�?random、premium、cylinder、energy、tungsten、chart �?giant_plant�?, failed: true };
2562
- }
2563
- const species = String(args.species ?? 'grass') as SpeciesId;
2564
- if (!SPECIES[species]) return { text: `没有这种植物�?{species}`, failed: true };
2565
- try {
2566
- const result = buySeeds(game, kind, species, this.now());
2567
- this.game = result.state;
2568
- await this.saveGame();
2569
- return `${result.text}\n${this.inventoryLine(result.state)}`;
2570
- } catch (error) {
2571
- return { text: error instanceof Error ? error.message : String(error), failed: true };
2572
- }
2573
- },
2574
- };
2575
- }
2576
-
2577
- private surveyTool(): ToolDef {
2578
- return {
2579
- ...GENESIS_TOOL_DECLS[12]!,
2580
- handler: async (args) => {
2581
- const ready = await this.readyState();
2582
- if ('error' in ready) return { text: ready.error, failed: true };
2583
- const { game } = ready;
2584
- const note = this.transitNote(game);
2585
- if (note) return note;
2586
- try {
2587
- const siteKey = this.resolveSite(game, args.site);
2588
- const system = await this.readSystem();
2589
- if (!system) return { text: '还没有创世��?, failed: true };
2590
- const result = surveySite(system, game, siteKey, this.now());
2591
- this.game = result.state;
2592
- await this.saveGame();
2593
- return `${result.text}\n${this.inventoryLine(result.state)}`;
2594
- } catch (error) {
2595
- return { text: error instanceof Error ? error.message : String(error), failed: true };
2596
- }
2597
- },
2598
- };
2599
- }
2600
-
2601
- private siteTool(): ToolDef {
2602
- return {
2603
- ...GENESIS_TOOL_DECLS[13]!,
2604
- handler: async (args) => {
2605
- const ready = await this.readyState();
2606
- if ('error' in ready) return { text: ready.error, failed: true };
2607
- const { system, game } = ready;
2608
- const note = this.transitNote(game);
2609
- if (note) return note;
2610
- const loc = game.location;
2611
- if (!loc) return { text: '还不知道自己在哪�?, failed: true };
2612
- const lat = typeof args.lat === 'number' ? args.lat : loc.latDeg;
2613
- const lon = typeof args.lon === 'number' ? args.lon : loc.lonDeg;
2614
- try {
2615
- const result = foundSite(system, game, lat, lon, this.now());
2616
- this.game = result.state;
2617
- await this.saveGame();
2618
- return result.text;
2619
- } catch (error) {
2620
- return { text: error instanceof Error ? error.message : String(error), failed: true };
2621
- }
2622
- },
2623
- };
2624
- }
2625
-
2626
- private plantTool(): ToolDef {
2627
- return {
2628
- ...GENESIS_TOOL_DECLS[14]!,
2629
- handler: async (args) => {
2630
- const ready = await this.readyState();
2631
- if ('error' in ready) return { text: ready.error, failed: true };
2632
- const { system, game } = ready;
2633
- const note = this.transitNote(game);
2634
- if (note) return note;
2635
- const bag = String(args.bag ?? '').trim();
2636
- if (!bag) return { text: '要种哪一袋?种子袋的 id �?genesis_shop / genesis_flora 里能看到�?, failed: true };
2637
- try {
2638
- const siteKey = this.resolveSite(game, args.site);
2639
- const count = typeof args.count === 'number' ? args.count : 5;
2640
- const result = sowAt(system, game, siteKey, bag, count, this.now());
2641
- this.game = result.state;
2642
- await this.saveGame();
2643
- return `${result.text}\n${this.floraLines(result.state, siteKey)}`;
2644
- } catch (error) {
2645
- return { text: error instanceof Error ? error.message : String(error), failed: true };
2646
- }
2647
- },
2648
- };
2649
- }
2650
-
2651
- private floraTool(): ToolDef {
2652
- return {
2653
- ...GENESIS_TOOL_DECLS[15]!,
2654
- handler: async (args) => {
2655
- const ready = await this.readyState();
2656
- if ('error' in ready) return { text: ready.error, failed: true };
2657
- const { game } = ready;
2658
- const only = String(args.site ?? '').trim() || undefined;
2659
- if (only && !game.sites.some((s) => s.key === only)) return { text: `没有这个站点�?{only}`, failed: true };
2660
- return this.floraLines(game, only);
2661
- },
2662
- };
2663
- }
2664
-
2665
- private harvestTool(): ToolDef {
2666
- return {
2667
- ...GENESIS_TOOL_DECLS[16]!,
2668
- handler: async (args) => {
2669
- const ready = await this.readyState();
2670
- if ('error' in ready) return { text: ready.error, failed: true };
2671
- const { system, game } = ready;
2672
- const note = this.transitNote(game);
2673
- if (note) return note;
2674
- const plantId = String(args.plant ?? '').trim();
2675
- if (!plantId) return { text: '要收哪一�?哪一群?', failed: true };
2676
- const asked = String(args.site ?? '').trim();
2677
- const siteKey = asked || game.sites.find((s) => (game.plants[s.key] ?? []).some((p) => p.id === plantId))?.key;
2678
- if (!siteKey) return { text: `找不到这株作物:${plantId}`, failed: true };
2679
- try {
2680
- const result = harvestAt(system, game, siteKey, plantId);
2681
- this.game = result.state;
2682
- await this.saveGame();
2683
- return `${result.text}\n${this.inventoryLine(result.state)}`;
2684
- } catch (error) {
2685
- return { text: error instanceof Error ? error.message : String(error), failed: true };
2686
- }
2687
- },
2688
- };
2689
- }
2690
-
2691
- private burnTool(): ToolDef {
2692
- return {
2693
- ...GENESIS_TOOL_DECLS[17]!,
2694
- handler: async (args) => {
2695
- const ready = await this.readyState();
2696
- if ('error' in ready) return { text: ready.error, failed: true };
2697
- const { game } = ready;
2698
- try {
2699
- const result = burnBiomass(game, Number(args.kg ?? 0));
2700
- this.game = result.state;
2701
- await this.saveGame();
2702
- return `${result.text}\n${this.energyLine(result.state)}`;
2703
- } catch (error) {
2704
- return { text: error instanceof Error ? error.message : String(error), failed: true };
2705
- }
2706
- },
2707
- };
2708
- }
2709
-
2710
- private async floraAction(method: string, args: unknown[]): Promise<GenesisPanelState> {
2711
- await this.sync();
2712
- const system = this.system;
2713
- const game = this.game;
2714
- if (!system || !game) throw new Error('还没有创世��?);
2715
- try {
2716
- let next: { state: GameState; text: string } | null = null;
2717
- if (method === 'sell') {
2718
- next = sellToMerchant(game, String(args[0]) as never, Number(args[1] ?? 1), this.now());
2719
- } else if (method === 'site') {
2720
- const loc = game.location;
2721
- if (!loc) throw new Error('还不知道自己在哪�?);
2722
- next = foundSite(system, game, loc.latDeg, loc.lonDeg, this.now());
2723
- } else if (method === 'plant') {
2724
- next = sowAt(system, game, this.resolveSite(game, args[1]), String(args[0]), 5, this.now());
2725
- } else if (method === 'harvest') {
2726
- const raw = String(args[0] ?? '');
2727
- let site: string | undefined;
2728
- let plantId = raw;
2729
- if (raw.includes('@')) {
2730
- site = raw;
2731
- plantId = (game.plants[raw] ?? []).find((p) => p.stage === 'ripe')?.id ?? '';
2732
- if (!plantId) throw new Error(`${raw} 现在没有能收的作物��`);
2733
- } else {
2734
- const asked = String(args[1] ?? '').trim();
2735
- site = asked
2736
- || (raw.startsWith('planter:') ? raw : undefined)
2737
- || game.sites.find((s) => (game.plants[s.key] ?? []).some((p) => p.id === raw))?.key;
2738
- }
2739
- if (!site) throw new Error(`找不到这株作物:${plantId}`);
2740
- next = harvestAt(system, game, site, plantId);
2741
- } else if (method === 'burn') {
2742
- next = burnBiomass(game, Number(args[0] ?? 0));
2743
- } else if (method === 'build') {
2744
- next = buildStructure(system, game, String(args[0]) as 'greenhouse' | 'biome_changer', this.resolveSite(game, args[1]), this.now());
2745
- }
2746
- if (next) {
2747
- this.game = next.state;
2748
- await this.saveGame();
2749
- }
2750
- } catch (error) {
2751
- throw new Error(error instanceof Error ? error.message : String(error));
2752
- }
2753
- return this.panelState();
2754
- }
2755
-
2756
- /** 仓库/火箭:存、取、拆、以及一张��览�?*/
2757
- private storeTool(): ToolDef {
2758
- return {
2759
- ...GENESIS_TOOL_DECLS[19]!,
2760
- handler: async (args) => {
2761
- const ready = await this.readyState();
2762
- if ('error' in ready) return { text: ready.error, failed: true };
2763
- const { game } = ready;
2764
- const action = String(args.action ?? '').trim();
2765
- try {
2766
- if (action === 'list') return this.storeList(game);
2767
- if (action === 'grid') {
2768
- return { text: this.gridLine(game) };
2769
- }
2770
- if (action === 'grid_in' || action === 'grid_out') {
2771
- const kj = typeof args.kj === 'number' ? args.kj : GRID_TAP_KJ_PER_CALL;
2772
- const moved = transferGridEnergy(this.system!, game, this.now(), action === 'grid_in' ? 'in' : 'out', kj);
2773
- this.game = moved.state;
2774
- await this.saveGame();
2775
- return { text: moved.text + '\n\n' + this.gridLine(this.game) };
2776
- }
2777
- if (action === 'dry') {
2778
- const siteKey = this.resolveSite(game, args.site);
2779
- const kg = typeof args.kg === 'number' ? args.kg : 10;
2780
- const result = dryFood(game, siteKey, kg);
2781
- this.game = result.state;
2782
- await this.saveGame();
2783
- return result.text + '\n\n' + this.storeList(this.game);
2784
- }
2785
- if (action === 'use') {
2786
- const resource = String(args.resource ?? '').trim();
2787
- const amount = typeof args.kg === 'number' && args.kg > 0 ? Math.floor(args.kg) : 1;
2788
- const siteKey = this.resolveSite(game, undefined);
2789
- try {
2790
- const used = useCanned(game, siteKey, resource, amount);
2791
- this.game = used.state;
2792
- await this.saveGame();
2793
- return used.text;
2794
- } catch (error) {
2795
- return { text: error instanceof Error ? error.message : String(error), failed: true };
2796
- }
2797
- }
2798
- const building = String(args.building ?? '').trim();
2799
- if (!building) return { text: '要指�?building(仓库或火箭的建�?id;用 action: "list" 先看有哪些)�?, failed: true };
2800
- if (action === 'bags') {
2801
- const container = game.structures.find((s) => s.id === building);
2802
- if (!container || containerBagSlots(container) === 0) {
2803
- return { text: `${building} 不是能装种子的容器:仓库、冷库��惰性气体室和交易终端才有袋位��`, failed: true };
2804
- }
2805
- const bags = bagsInContainer(game, building);
2806
- const label = container.kind === 'terminal' ? '终端缓冲' : `${BUILD_SPECS[container.kind].label}里的种子`;
2807
- if (bags.length === 0) {
2808
- return {
2809
- text: `${label}是空的(0/${CONTAINER_BAG_SLOTS} 袋)�?{container.kind === 'terminal' ? '装上 buySpecies 或让商人送种子过来��? : '用机械臂或手�?deposit 把袋子放进来�?}`,
2810
- };
2811
- }
2812
- const lines = bags.map(
2813
- (b, i) => ` ${i + 1}. ${b.premium ? '高级' : '随机'}${SPECIES[b.species].name} ×${b.count} 粒(${b.id}�?{bagWeightKg(b).toFixed(3)} kg)`,
2814
- );
2815
- return { text: `${label}�?{bags.length}/${CONTAINER_BAG_SLOTS} 袋):\n${lines.join('\n')}\n取一袋:action: "take",building 传这个容�?id,bag 传括号里�?id。` };
2816
- }
2817
- if (action === 'take') {
2818
- const bagId = typeof args.bag === 'string' && args.bag.trim() ? args.bag.trim() : undefined;
2819
- let result: { state: typeof game; text: string };
2820
- try {
2821
- result = takeBagFromContainer(game, building, bagId);
2822
- } catch (error) {
2823
- return { text: error instanceof Error ? error.message : String(error), failed: true };
2824
- }
2825
- this.game = result.state;
2826
- await this.saveGame();
2827
- return result.text;
2828
- }
2829
- if (action === 'demolish') {
2830
- const text = demolishStructure(game, building);
2831
- const structures = game.structures.filter((s) => s.id !== building);
2832
- const stores = { ...game.stores };
2833
- delete stores[building];
2834
- this.game = { ...game, structures, stores };
2835
- await this.saveGame();
2836
- return text;
2837
- }
2838
- const resource = String(args.resource ?? '').trim();
2839
- const kg = Number(args.kg);
2840
- if (!resource) return { text: '要指�?resource(例�?biomass / ash / survey)��?, failed: true };
2841
- if (!Number.isFinite(kg) || kg <= 0) return { text: 'kg 要是大于 0 的数字��?, failed: true };
2842
- const result = action === 'deposit'
2843
- ? depositTo(game, building, resource, kg)
2844
- : action === 'withdraw'
2845
- ? withdrawFrom(game, building, resource, kg)
2846
- : null;
2847
- if (!result) return { text: 'action 只能�?deposit / withdraw / demolish / list�?, failed: true };
2848
- this.game = result.state;
2849
- await this.saveGame();
2850
- return `${result.text}\n\n${this.storeList(result.state)}`;
2851
- } catch (error) {
2852
- return { text: error instanceof Error ? error.message : String(error), failed: true };
2853
- }
2854
- },
2855
- };
2856
- }
2857
-
2858
- /** 扢�有容器的丢�行摘要:id、位置��装了什么��还剩多少空间��?*/
2859
- private storeList(game: GameState): string {
2860
- const containers = game.structures.filter((s) => storeCapacityKg(s) > 0);
2861
- const lines = [`背包�?{this.inventoryLine(game)}`];
2862
- if (containers.length === 0) {
2863
- lines.push('(还没有仓库或火箭��仓库用 genesis_install id: "warehouse" 建在陆地站点上��)');
2864
- return lines.join('\n');
2865
- }
2866
- for (const c of containers) {
2867
- const store = game.stores[c.id] ?? {};
2868
- const used = storeWeightKg(store);
2869
- const cap = storeCapacityKg(c);
2870
- const stuff = Object.entries(store).map(([k, v]) => `${RESOURCE_LABELS[k as keyof typeof RESOURCE_LABELS] ?? k} ${v} kg`).join('�?) || '空的';
2871
- const where = c.kind === 'rocket' ? `停在 p${c.dockedPlanetIndex ?? c.planetIndex}` : c.siteKey;
2872
- const drone = game.structures.some((s) => s.kind === 'drone_cluster' && s.serves === c.id) ? ' · 有无人机集群' : '';
2873
- lines.push(`�?{c.id}�?{where}${drone}�?{stuff}�?{used} / ${cap} kg)`);
2874
- }
2875
- return lines.join('\n');
2876
- }
2877
-
2878
- /** 丢�张表看全扢�有建筑与作物的成�?产出,模型不用猜�?*/
2879
- private recipesTool(): ToolDef {
2880
- return {
2881
- ...GENESIS_TOOL_DECLS[20]!,
2882
- handler: async () => {
2883
- const ready = await this.readyState();
2884
- // 还没创世也能看表:它不依赖存档,只是少了当前那条�?
2885
- if ('error' in ready) {
2886
- // 继续徢�下,用静态表回答�? }
2887
- const lines = ['建��与设备(kJ / 母星�?/ 维护 kJ每母星时 / 容量 / 钨)�?];
2888
- for (const [kind, spec] of Object.entries(BUILD_SPECS)) {
2889
- const cap = kind === 'warehouse' ? '1,000 kg' : kind === 'rocket' ? '250 kg' : '�?;
2890
- lines.push(
2891
- `- ${spec.label}(id: ${kind}):${spec.costKj.toLocaleString('en-US')} kJ · ${spec.buildHours} 母星�?· ` +
2892
- `维护 ${spec.upkeepKjPerHour.toLocaleString('en-US')} · 容量 ${cap} · �?${spec.tungsten} 份`,
2893
- );
2894
- }
2895
- lines.push(
2896
- '- 环境监测�?/ 凌日计数器:150,000 kJ + 2 份钨 · 0.1 母星�?,
2897
- '- 太阳能帆�?,000 kJ + 1 份钨 · 不��时 · 白天 7,000 kJ/母星�?· 每星上限 10',
2898
- '- 制冷核心 10,000 kJ + 1 份钨 · 维护 1,500 · 再降 33℃;制热核心同价 · 维护 400 · 再升 33�?,
2899
- '- 拟真核心 60,000 kJ + 1 份钨 · 维护 1,200 · 人工气��的惩罚减半(最多两座)',
2900
- '- 蓝图结构优化(升级)�?00,000 kJ + 3 份钨 + 2 kg 纤维 · 之后每座建筑�?25% 的钨�? 份的不省�?,
2901
- '',
2902
- '作物(物�?· 生境 · 适温 · 周期 · 单株/单群产量 · 资源 · 霢�要的氮磷钾微量)�?,
2903
- );
2904
- for (const id of SPECIES_IDS) {
2905
- const s = SPECIES[id];
2906
- const need = NUTRIENT_NEEDS[id];
2907
- lines.push(
2908
- `- ${s.name}�?{id}):${s.medium === 'water' ? '水生' : '陆生'} · ${s.tempMinC}�?{s.tempMaxC}℃(朢��?${s.tempOptC})�?` +
2909
- `${s.cycleHomeHours} 母星�?· ${s.yieldKg} kg · ${RESOURCE_LABELS[s.resource]} · ` +
2910
- `N/P/K/微量 ${need.n}/${need.p}/${need.k}/${need.trace}`,
2911
- );
2912
- }
2913
- lines.push('', '商人收购价(信用�?kg,括号内是每日限购)�?);
2914
- for (const good of SELL_GOODS) {
2915
- lines.push(`- ${good.name}�?{good.basePrice}${good.dailyLimit > 0 ? `(每�?${good.dailyLimit} ${good.unit})` : '(不限量�?}`);
2916
- }
2917
- return lines.join('\n');
2918
- },
2919
- };
2920
- }
2921
-
2922
- /** 此刻、这里,丢�段话�?*/
2923
- private lookTool(): ToolDef {
2924
- return {
2925
- ...GENESIS_TOOL_DECLS[21]!,
2926
- handler: async () => {
2927
- const ready = await this.readyState();
2928
- if ('error' in ready) return { text: ready.error, failed: true };
2929
- try {
2930
- return lookAround(ready.system, ready.game, this.now()).text;
2931
- } catch (error) {
2932
- return { text: errorText(error), failed: true };
2933
- }
2934
- },
2935
- };
2936
- }
2937
-
2938
- /** 原地等:�?1 母星时步进,事件逐条收��?*/
2939
- private waitTool(): ToolDef {
2940
- return {
2941
- ...GENESIS_TOOL_DECLS[22]!,
2942
- handler: async (args) => {
2943
- const ready = await this.readyState();
2944
- if ('error' in ready) return { text: ready.error, failed: true };
2945
- const hours = typeof args.hours === 'number' ? args.hours : undefined;
2946
- const until = typeof args.until === 'string' ? (args.until as WaitUntil) : undefined;
2947
- try {
2948
- const result = waitFor(ready.system, ready.game, this.now(), { hours, until });
2949
- this.game = result.state;
2950
- await this.saveGame();
2951
- for (const event of result.events) await this.push(event.type, event.text);
2952
- const realHours = (result.advancedHomeHours * result.state.msPerPlanetHour) / REAL_MS_PER_HOUR;
2953
- const lines = [
2954
- `等了 ${result.advancedHomeHours.toFixed(1)} 母星时(现实�?${realHours.toFixed(1)} 小时)��?{result.reason}`,
2955
- ];
2956
- if (result.events.length > 0) {
2957
- lines.push('', '期间发生�?, ...result.events.map((e) => `- ${e.text}`));
2958
- }
2959
- lines.push('', this.timeLine(this.game));
2960
- try {
2961
- lines.push('', lookAround(ready.system, this.game!, this.now()).text);
2962
- } catch {
2963
- // 移动途中看不了环境,timeLine 已经说了在移动��? }
2964
- return lines.join('\n');
2965
- } catch (error) {
2966
- return { text: errorText(error), failed: true };
2967
- }
2968
- },
2969
- };
2970
- }
2971
-
2972
- /** 船上的升级:列清单,或修机动核心 / 射电望远镜阵列��?*/
2973
- private upgradeTool(): ToolDef {
2974
- return {
2975
- ...GENESIS_TOOL_DECLS[23]!,
2976
- handler: async (args) => {
2977
- const ready = await this.readyState();
2978
- if ('error' in ready) return { text: ready.error, failed: true };
2979
- const id = typeof args.id === 'string' ? args.id : '';
2980
- if (!id) return this.upgradeListText(ready.game);
2981
- try {
2982
- const result =
2983
- id === 'mobility_core'
2984
- ? beginMobilityRepair(ready.game, this.now())
2985
- : id === 'telescope'
2986
- ? beginTelescopeUpgrade(ready.game, this.now())
2987
- : id === 'spark_plug'
2988
- ? beginSparkPlugUpgrade(ready.game, this.now())
2989
- : id === 'battery'
2990
- ? beginBatteryUpgrade(ready.game, this.now())
2991
- : id === 'subagent'
2992
- ? beginSubagentUpgrade(ready.game, this.now())
2993
- : id === 'blueprints'
2994
- ? beginBlueprintsUpgrade(ready.game, this.now())
2995
- : id === 'spectrometer'
2996
- ? beginSpectrometerUpgrade(ready.game, this.now())
2997
- : null;
2998
- if (!result) return { text: `船上没有这个可升级的东西�?{id}(能修的�?mobility_core / telescope / spark_plug / battery / subagent / blueprints / spectrometer)��`, failed: true };
2999
- this.game = result.state;
3000
- await this.saveGame();
3001
- return result.text;
3002
- } catch (error) {
3003
- return { text: errorText(error), failed: true };
3004
- }
3005
- },
3006
- };
3007
- }
3008
-
3009
- private upgradeListText(game: GameState): string {
3010
- const lines = ['船上能修的东西:'];
3011
-
3012
- const repairingCore = game.builds.find((b) => b.kind === 'mobility_core');
3013
- if (mobilityCoreReady(game)) {
3014
- lines.push('- 机动核心:已经修好了。海面能过,气��行星的大气也能进��?);
3015
- } else if (repairingCore) {
3016
- const left = Math.max(0, repairingCore.completeHomeHours - nowPlanetHours(game, this.now()));
3017
- lines.push(`- 机动核心:正在修,还�?${left.toFixed(1)} 母星时��`);
3018
- } else {
3019
- lines.push('- 机动核心:烧坏了。海面过不去,气态行星的大气也进不去�?);
3020
- lines.push(` 要修它:${MOBILITY_CORE_COST_KJ.toLocaleString('en-US')} kJ,加�?` +
3021
- mobilityCoreMaterials(game).map((m) => `${m.name} ${m.needKg} kg(现�?${m.haveKg} kg)`).join('�?) +
3022
- ',��时 0.5 母星时��?);
3023
- lines.push(` 能量�?{Math.floor(game.energyKj).toLocaleString('en-US')} kJ。` +
3024
- (canRepairMobilityCore(game) ? '够了—��genesis_upgrade �?id: "mobility_core" 就能弢�工��? : '还不够��?));
3025
- }
3026
-
3027
- const telescope = telescopeCard(game);
3028
- const repairingScope = game.builds.find((b) => b.kind === 'telescope');
3029
- lines.push('');
3030
- if (telescope.level === 0) {
3031
- lines.push('- 射电望远镜阵列:还没修好,所以母星上没有商店,星际商人听不到你的信号�?);
3032
- } else {
3033
- lines.push(`- 射电望远镜阵列:lv${telescope.level} / lv${telescope.maxLevel}�?{telescope.window}`);
3034
- }
3035
- if (repairingScope) {
3036
- const left = Math.max(0, repairingScope.completeHomeHours - nowPlanetHours(game, this.now()));
3037
- lines.push(` 正在修下丢�级,还剩 ${left.toFixed(1)} 母星时��`);
3038
- } else if (telescope.next) {
3039
- const next = telescope.next;
3040
- lines.push(` 修到 lv${next.level}�?{next.costKj.toLocaleString('en-US')} kJ,加�?` +
3041
- telescope.materials.map((m) => `${m.name} ${m.needKg} kg(现�?${m.haveKg} kg)`).join('�?) +
3042
- `,��时 ${next.homeHours} 母星时��收益:${next.summary}`);
3043
- lines.push(' ' + (telescope.canBuild
3044
- ? '够了—��genesis_upgrade �?id: "telescope" 就能弢�工��?
3045
- : telescope.blockers.join(' ')));
3046
- } else {
3047
- lines.push(' 已经到顶(lv3),没有下一级了�?);
3048
- }
3049
-
3050
- const spark = sparkPlugCard(game, this.now());
3051
- const repairingSpark = game.builds.find((b) => b.kind === 'spark_plug');
3052
- lines.push('');
3053
- lines.push(`- 火花塞:lv${spark.level} / lv${spark.maxLevel},人类手摇一�?${spark.outputKj} kJ。`);
3054
- if (repairingSpark) {
3055
- const left = Math.max(0, repairingSpark.completeHomeHours - nowPlanetHours(game, this.now()));
3056
- lines.push(` 正在修下丢�级,还剩 ${left.toFixed(1)} 母星时��`);
3057
- } else if (spark.next) {
3058
- const next = spark.next;
3059
- lines.push(` 修到 lv${next.level}�?{next.costKj.toLocaleString('en-US')} kJ` +
3060
- (spark.materials.length > 0
3061
- ? `,加�?${spark.materials.map((m) => `${m.name} ${m.needKg} kg(现�?${m.haveKg} kg)`).join('�?)}`
3062
- : '') +
3063
- `,��时 ${next.homeHours} 母星时��收益:${next.summary}`);
3064
- lines.push(' ' + (spark.canBuild
3065
- ? '够了—��genesis_upgrade �?id: "spark_plug" 就能弢�工��?
3066
- : spark.blockers.join(' ')));
3067
- } else {
3068
- lines.push(' 已经到顶(lv3),没有下一级了�?);
3069
- }
3070
-
3071
- const battery = batteryCard(game, this.now());
3072
- const repairingBattery = game.builds.find((b) => b.kind === 'battery');
3073
- lines.push('');
3074
- lines.push(`- 蓄电池:lv${battery.level} / lv${battery.maxLevel},能量上�?${battery.capacityKj.toLocaleString('en-US')} kJ。`);
3075
- if (repairingBattery) {
3076
- const left = Math.max(0, repairingBattery.completeHomeHours - nowPlanetHours(game, this.now()));
3077
- lines.push(` 正在扩,还剩 ${left.toFixed(1)} 母星时��`);
3078
- } else if (battery.next) {
3079
- const next = battery.next;
3080
- lines.push(` 扩到 lv${next.level}�?{next.costKj.toLocaleString('en-US')} kJ` +
3081
- (battery.materials.length > 0
3082
- ? `,加�?${battery.materials.map((m) => `${m.name} ${m.needKg} kg(现�?${m.haveKg} kg)`).join('�?)}`
3083
- : '') +
3084
- `,��时 ${next.homeHours} 母星时��收益:${next.summary}`);
3085
- lines.push(' ' + (battery.canBuild
3086
- ? '够了—��genesis_upgrade �?id: "battery" 就能弢�工��?
3087
- : battery.blockers.join(' ')));
3088
- } else {
3089
- lines.push(' 已经到顶(lv3),没有下一级了�?);
3090
- }
3091
-
3092
- const subagent = subagentCard(game, this.now());
3093
- const repairingSub = game.builds.find((b) => b.kind === 'subagent');
3094
- lines.push('');
3095
- lines.push(`- 子代理:lv${subagent.level} / lv${subagent.maxLevel},现在能同时弢� ${buildQueueSlots(game)} 条施工队列��`);
3096
- if (repairingSub) {
3097
- const left = Math.max(0, repairingSub.completeHomeHours - nowPlanetHours(game, this.now()));
3098
- lines.push(` 正在接下丢�组,还剩 ${left.toFixed(1)} 母星时��`);
3099
- } else if (subagent.next) {
3100
- const next = subagent.next;
3101
- lines.push(` 接到 lv${next.level}�?{next.costKj.toLocaleString('en-US')} kJ` +
3102
- (subagent.materials.length > 0
3103
- ? `,加�?${subagent.materials.map((m) => `${m.name} ${m.needKg} kg(现�?${m.haveKg} kg)`).join('�?)}`
3104
- : '') +
3105
- `,��时 ${next.homeHours} 母星时��收益:${next.summary}`);
3106
- lines.push(' ' + (subagent.canBuild
3107
- ? '够了—��genesis_upgrade �?id: "subagent" 就能弢�工��?
3108
- : subagent.blockers.join(' ')));
3109
- } else {
3110
- lines.push(' 已经全接上了(lv3),没有下一组了�?);
3111
- }
3112
-
3113
- const plans = blueprintsCard(game, this.now());
3114
- const repairingPlans = game.builds.find((b) => b.kind === 'blueprints');
3115
- lines.push('');
3116
- lines.push(`- 蓝图结构优化�?{plans.level > 0 ? '已经优化过,打印机每座建筑省 25% 的钨�? 份的不省)��? : '还没做����做了以后每座建筑省 25% 的钨�?}`);
3117
- if (repairingPlans) {
3118
- const left = Math.max(0, repairingPlans.completeHomeHours - nowPlanetHours(game, this.now()));
3119
- lines.push(` 正在做,还剩 ${left.toFixed(1)} 母星时��`);
3120
- } else if (plans.level === 0) {
3121
- lines.push(` ${plans.costKj.toLocaleString('en-US')} kJ,加�?${plans.materials.map((m) => `${m.label} ${m.need}(现�?${round3(m.have)})`).join('�?)},��时 ${plans.homeHours} 母星时��`);
3122
- lines.push(' ' + (plans.canBuild ? '够了—��genesis_upgrade �?id: "blueprints" 就能弢�工��? : plans.blockers.join(' ')));
3123
- }
3124
-
3125
- const spec = spectrometerCard(game, this.now());
3126
- const repairingSpec = game.builds.find((b) => b.kind === 'spectrometer');
3127
- lines.push('');
3128
- lines.push(`- 质谱仪:${spec.level > 0 ? '装好了����genesis_veins 能扫附近的钨含量,每 6 母星时一次��? : '还没装����装好才能扫矿��找富矿放采矿机�?}`);
3129
- if (repairingSpec) {
3130
- const left = Math.max(0, repairingSpec.completeHomeHours - nowPlanetHours(game, this.now()));
3131
- lines.push(` 正在装,还剩 ${left.toFixed(1)} 母星时��`);
3132
- } else if (spec.level === 0) {
3133
- lines.push(` ${spec.costKj.toLocaleString('en-US')} kJ,加�?${spec.materials.map((m) => `${m.label} ${m.need}(现�?${round3(m.have)})`).join('�?)},��时 ${spec.homeHours} 母星时��`);
3134
- lines.push(' ' + (spec.canBuild ? '够了—��genesis_upgrade �?id: "spectrometer" 就能弢�工��? : spec.blockers.join(' ')));
3135
- }
3136
- return lines.join('\n');
3137
- }
3138
-
3139
- /** 升级面板的数据:机动核心 + 射电望远镜阵�?+ 火花塞��?*/
3140
- private upgradeState(): unknown {
3141
- const game = this.game;
3142
- if (!game) return { locked: true, energyKj: 0, cards: [] };
3143
- const repairingCore = game.builds.find((b) => b.kind === 'mobility_core');
3144
- const telescope = telescopeCard(game);
3145
- const repairingScope = game.builds.find((b) => b.kind === 'telescope');
3146
- const spark = sparkPlugCard(game, this.now());
3147
- const repairingSpark = game.builds.find((b) => b.kind === 'spark_plug');
3148
- const battery = batteryCard(game, this.now());
3149
- const repairingBattery = game.builds.find((b) => b.kind === 'battery');
3150
- const subagent = subagentCard(game, this.now());
3151
- const repairingSub = game.builds.find((b) => b.kind === 'subagent');
3152
- const plans = blueprintsCard(game, this.now());
3153
- const repairingPlans = game.builds.find((b) => b.kind === 'blueprints');
3154
- const spec = spectrometerCard(game, this.now());
3155
- const repairingSpec = game.builds.find((b) => b.kind === 'spectrometer');
3156
- return {
3157
- locked: false,
3158
- energyKj: Math.round(game.energyKj),
3159
- cards: [
3160
- {
3161
- id: 'mobility_core',
3162
- label: '机动核心',
3163
- status: mobilityCoreReady(game) ? 'ready' : repairingCore ? 'repairing' : 'broken',
3164
- costKj: MOBILITY_CORE_COST_KJ,
3165
- buildHours: 0.5,
3166
- leftHomeHours: repairingCore
3167
- ? Math.max(0, repairingCore.completeHomeHours - nowPlanetHours(game, this.now()))
3168
- : 0,
3169
- materials: mobilityCoreMaterials(game),
3170
- canRepair: canRepairMobilityCore(game),
3171
- blockers: canRepairMobilityCore(game) ? [] : this.mobilityBlockers(game),
3172
- flavor: this.mobilityFlavor(game),
3173
- },
3174
- {
3175
- id: 'telescope',
3176
- label: '射电望远镜阵�?,
3177
- status: telescope.level >= telescope.maxLevel ? 'maxed' : repairingScope ? 'repairing' : telescope.level > 0 ? 'ready' : 'broken',
3178
- level: telescope.level,
3179
- maxLevel: telescope.maxLevel,
3180
- window: telescope.window,
3181
- limitFactor: telescope.limitFactor,
3182
- costKj: telescope.next?.costKj ?? 0,
3183
- buildHours: telescope.next?.homeHours ?? 0,
3184
- leftHomeHours: repairingScope
3185
- ? Math.max(0, repairingScope.completeHomeHours - nowPlanetHours(game, this.now()))
3186
- : 0,
3187
- materials: telescope.materials,
3188
- canRepair: telescope.canBuild,
3189
- blockers: telescope.blockers,
3190
- benefits: telescope.next ? telescope.next.summary : '已经到顶:每�?12:00�?3:00 营业,每日限�?×1.7�?,
3191
- flavor: this.telescopeFlavor(game),
3192
- },
3193
- {
3194
- id: 'spark_plug',
3195
- label: '火花�?,
3196
- status: spark.level >= spark.maxLevel ? 'maxed' : repairingSpark ? 'repairing' : spark.level > 0 ? 'ready' : 'broken',
3197
- level: spark.level,
3198
- maxLevel: spark.maxLevel,
3199
- costKj: spark.next?.costKj ?? 0,
3200
- buildHours: spark.next?.homeHours ?? 0,
3201
- leftHomeHours: repairingSpark
3202
- ? Math.max(0, repairingSpark.completeHomeHours - nowPlanetHours(game, this.now()))
3203
- : 0,
3204
- materials: spark.materials,
3205
- canRepair: spark.canBuild,
3206
- blockers: spark.blockers,
3207
- benefits: spark.next ? spark.next.summary : `已经到顶:手摇一�?${spark.outputKj} kJ。`,
3208
- flavor: this.sparkPlugFlavor(game),
3209
- },
3210
- {
3211
- id: 'battery',
3212
- label: '蓄电�?,
3213
- status: battery.level >= battery.maxLevel ? 'maxed' : repairingBattery ? 'repairing' : battery.level > 0 ? 'ready' : 'broken',
3214
- level: battery.level,
3215
- maxLevel: battery.maxLevel,
3216
- costKj: battery.next?.costKj ?? 0,
3217
- buildHours: battery.next?.homeHours ?? 0,
3218
- leftHomeHours: repairingBattery
3219
- ? Math.max(0, repairingBattery.completeHomeHours - nowPlanetHours(game, this.now()))
3220
- : 0,
3221
- materials: battery.materials,
3222
- canRepair: battery.canBuild,
3223
- blockers: battery.blockers,
3224
- benefits: battery.next ? battery.next.summary : `已经到顶:上�?${battery.capacityKj.toLocaleString('en-US')} kJ。`,
3225
- flavor: this.batteryFlavor(game),
3226
- },
3227
- {
3228
- id: 'subagent',
3229
- label: '子代�?,
3230
- status: subagent.level >= subagent.maxLevel ? 'maxed' : repairingSub ? 'repairing' : subagent.level > 0 ? 'ready' : 'broken',
3231
- level: subagent.level,
3232
- maxLevel: subagent.maxLevel,
3233
- costKj: subagent.next?.costKj ?? 0,
3234
- buildHours: subagent.next?.homeHours ?? 0,
3235
- leftHomeHours: repairingSub
3236
- ? Math.max(0, repairingSub.completeHomeHours - nowPlanetHours(game, this.now()))
3237
- : 0,
3238
- materials: subagent.materials,
3239
- canRepair: subagent.canBuild,
3240
- blockers: subagent.blockers,
3241
- benefits: subagent.next ? subagent.next.summary : `已经全接上:${buildQueueSlots(game)} 条施工队列��`,
3242
- flavor: this.subagentFlavor(game),
3243
- },
3244
- {
3245
- id: 'blueprints',
3246
- label: '蓝图结构优化',
3247
- status: plans.level > 0 ? 'maxed' : repairingPlans ? 'repairing' : 'broken',
3248
- level: plans.level,
3249
- maxLevel: plans.maxLevel,
3250
- costKj: plans.costKj,
3251
- buildHours: plans.homeHours,
3252
- leftHomeHours: repairingPlans
3253
- ? Math.max(0, repairingPlans.completeHomeHours - nowPlanetHours(game, this.now()))
3254
- : 0,
3255
- materials: plans.materials.map((m) => ({ name: m.label, needKg: m.need, haveKg: round3(m.have) })),
3256
- canRepair: plans.canBuild,
3257
- blockers: plans.blockers,
3258
- benefits: '以后每座建筑少用 25% 的钨�? 份的不省�?�?�?�?�?�?�?�?)��?,
3259
- flavor: this.blueprintsFlavor(game),
3260
- },
3261
- {
3262
- id: 'spectrometer',
3263
- label: '质谱�?,
3264
- status: spec.level > 0 ? 'maxed' : repairingSpec ? 'repairing' : 'broken',
3265
- level: spec.level,
3266
- maxLevel: spec.maxLevel,
3267
- costKj: spec.costKj,
3268
- buildHours: spec.homeHours,
3269
- leftHomeHours: repairingSpec
3270
- ? Math.max(0, repairingSpec.completeHomeHours - nowPlanetHours(game, this.now()))
3271
- : 0,
3272
- materials: spec.materials.map((m) => ({ name: m.label, needKg: m.need, haveKg: round3(m.have) })),
3273
- canRepair: spec.canBuild,
3274
- blockers: spec.blockers,
3275
- benefits: '能扫 2,000 km 内的钨含量(�?6 母星时一次),找富矿再放采矿机����富矿一格能挖出好几倍的钨��?,
3276
- flavor: this.spectrometerFlavor(game),
3277
- },
3278
- ],
3279
- };
3280
- }
3281
-
3282
- private spectrometerFlavor(game: GameState): string {
3283
- if (game.builds.some((b) => b.kind === 'spectrometer')) {
3284
- return '探头还在校准。屏幕上丢�条一条的线,像心电图�?;
3285
- }
3286
- if ((game.upgrades.spectrometer ?? 0) > 0) {
3287
- return '探头贴着地面,把地下的金属味翻译成数字��这丢�片底下有没有东西,现在你看得见了�?;
3288
- }
3289
- return '你看不见地底下有仢�么��采矿机放错了地方,挖的只是丢�堆普通石头��?;
3290
- }
3291
-
3292
- private blueprintsFlavor(game: GameState): string {
3293
- if (game.builds.some((b) => b.kind === 'blueprints')) {
3294
- return '打印机的图纸在重排����子密密麻麻,但你看得懂—��少丢�圈支撑,少半份钨�?;
3295
- }
3296
- if ((game.upgrades.blueprints ?? 0) > 0) {
3297
- return '同样的骨架,现在只吃四分之三的料。打印机吐东西的时��,声音都轻了一点��?;
3298
- }
3299
- return '打印机每次都在浪费:骨架比需要的更厚。你可以先花时间把图纸改瘦,再动手建�?;
3300
- }
3301
-
3302
- private mobilityBlockers(game: GameState): string[] { if (mobilityCoreReady(game)) return ['已经修好了��?];
3303
- if (game.builds.length >= buildQueueSlots(game)) return ['施工队列满了,先等一条空出来�?];
3304
- const missing = mobilityCoreMaterials(game).filter((m) => m.haveKg + 1e-9 < m.needKg);
3305
- const blockers = missing.map((m) => `${m.name}还差 ${(m.needKg - m.haveKg).toFixed(2)} kg`);
3306
- if (game.energyKj < MOBILITY_CORE_COST_KJ) {
3307
- blockers.push(`能量还差 ${Math.ceil(MOBILITY_CORE_COST_KJ - game.energyKj).toLocaleString('en-US')} kJ`);
3308
- }
3309
- return blockers;
3310
- }
3311
-
3312
- private telescopeFlavor(game: GameState): string {
3313
- const level = game.upgrades.telescope;
3314
- if (level === 0) {
3315
- return '阵列基座还在,天线面却塌了大半��你把最后一块配重焊回去,才敢把功率推上去��?;
3316
- }
3317
- if (game.builds.some((b) => b.kind === 'telescope')) {
3318
- return '你在校准阵元的相位��远处的杂音里,慢慢浮出丢�段规律的电波—��有人在听��?;
3319
- }
3320
- if (level === 1) return '第一天联系上商人:只要两小时的窗口,够了�?;
3321
- if (level === 2) return '阵列能撑到傍晚了。商人开始多留一会儿,价钱也肯多让一点��?;
3322
- return '整面阵列都在转��现在它可以丢�直听到深夜����像丢�艘船终于有了自己的港口��?;
3323
- }
3324
-
3325
- private async repairFromPanel(id: string): Promise<unknown> {
3326
- await this.sync();
3327
- if (!this.game) throw new Error('还没有创世��?);
3328
- const result =
3329
- id === 'telescope'
3330
- ? beginTelescopeUpgrade(this.game, this.now())
3331
- : id === 'spark_plug'
3332
- ? beginSparkPlugUpgrade(this.game, this.now())
3333
- : id === 'battery'
3334
- ? beginBatteryUpgrade(this.game, this.now())
3335
- : id === 'subagent'
3336
- ? beginSubagentUpgrade(this.game, this.now())
3337
- : beginMobilityRepair(this.game, this.now());
3338
- this.game = result.state;
3339
- await this.saveGame();
3340
- return this.upgradeState();
3341
- }
3342
-
3343
- private subagentFlavor(game: GameState): string {
3344
- const level = game.upgrades.subagent;
3345
- if (level === 0) {
3346
- return '施工网上只剩你一条手臂在动��别的子代理都停在半路,灯是暗的—��你只能丢�件一件来�?;
3347
- }
3348
- if (game.builds.some((b) => b.kind === 'subagent')) {
3349
- return '你在给一排休眠节点重新上电��灯丢�盏一盏亮起来,像有人在黑暗里应了你一声��?;
3350
- }
3351
- if (level === 1) return '终于有第二只手了:一边等温室,一边还能修别的�?;
3352
- if (level === 2) return '三条队列同时在跑。你弢�始能「安排����不是��排队��了�?;
3353
- return '四条队列全开的时候,船坞里久违地有了动静—��像这艘船终于又活过来一点��?;
3354
- }
3355
-
3356
- private batteryFlavor(game: GameState): string { const level = game.upgrades.battery;
3357
- if (level === 0) {
3358
- return '电池组只剩一层壳。夜里发电机丢�停,面板上的数字就往下掉—��它连一块帆的收成都存不住��?;
3359
- }
3360
- if (game.builds.some((b) => b.kind === 'battery')) {
3361
- return '你把新的电芯丢�排排码进去,旧的那几节烫得厉害��?;
3362
- }
3363
- if (level === 1) return '多出来的丢�格电芯让灯稳住了。上�?300,000 kJ�?;
3364
- if (level === 2) return '电池仓扩到了原来的两倍多。上�?700,000 kJ�?;
3365
- return '整排电芯安静地亮睢�。上�?1,500,000 kJ—��够它把丢�台监测器搬上天了�?;
3366
- }
3367
-
3368
- private sparkPlugFlavor(game: GameState): string {
3369
- const level = game.upgrades.sparkPlug;
3370
- if (level === 0) {
3371
- return '手摇曲柄转起来很吃力,火花塞早就烧蚀了����现在一次只�?5 kJ�?;
3372
- }
3373
- if (game.builds.some((b) => b.kind === 'spark_plug')) {
3374
- return '你把手伸进发电机的腹腔,旧火花塞还卡在螺纹里。人类的工具比你的手臂细得多�?;
3375
- }
3376
- if (level === 1) return '换了新的火花塞,曲柄轻了丢�点��一�?15 kJ�?;
3377
- if (level === 2) return '点火提前角对上了。一�?30 kJ,手背不那么酸了�?;
3378
- return '火花塞烧得干凢�利落。一�?50 kJ—��这台机器终于肯替你出力了��?;
3379
- }
3380
-
3381
- /** 剧情:四段,随机动核心的状��推进��?*/
3382
- private mobilityFlavor(game: GameState): string {
3383
- if (mobilityCoreReady(game)) {
3384
- return '第一次,你听见了海的声音。船身不再瘸了����从坠地那天起,你一直等睢�能再飞一次��?;
3385
- }
3386
- if (game.builds.some((b) => b.kind === 'mobility_core')) {
3387
- return '你在龙骨里重新接上那几层密封。外面下睢�雨,船壳在慢慢变冷��?;
3388
- }
3389
- const done = mobilityCoreMaterials(game).filter((m) => m.haveKg + 1e-9 >= m.needKg).length;
3390
- if (done > 0) {
3391
- return '外壳还能用,缺的是里面那几层密封。你手里的纤维,正好是它要的�?;
3392
- }
3393
- return '船是迫降的��机动核心在坠落时烧穿了外壳,剩下的部分还卡在龙骨里�?;
3394
- }
3395
-
3396
- private guideTool(): ToolDef {
3397
- return {
3398
- ...GENESIS_TOOL_DECLS[24]!,
3399
- handler: async (args) => {
3400
- const topic = typeof args.topic === 'string' && args.topic.trim() !== '' ? args.topic.trim() : undefined;
3401
- try {
3402
- return guideText(topic);
3403
- } catch (error) {
3404
- return { text: errorText(error), failed: true };
3405
- }
3406
- },
3407
- };
3408
- }
3409
-
3410
- private infoTool(): ToolDef {
3411
- return {
3412
- ...GENESIS_TOOL_DECLS[34]!,
3413
- handler: async (args) => {
3414
- const query = typeof args.query === 'string' ? args.query : '';
3415
- try {
3416
- return infoText(query);
3417
- } catch (error) {
3418
- return { text: errorText(error), failed: true };
3419
- }
3420
- },
3421
- };
3422
- }
3423
-
3424
- private protocolTool(): ToolDef {
3425
- return {
3426
- ...GENESIS_TOOL_DECLS[25]!,
3427
- handler: async () => {
3428
- const ready = await this.readyState();
3429
- if ('error' in ready) return { text: ready.error, failed: true };
3430
- await this.sync();
3431
- return protocolText(ready.game);
3432
- },
3433
- };
3434
- }
3435
-
3436
- private ordersTool(): ToolDef {
3437
- return {
3438
- ...GENESIS_TOOL_DECLS[26]!,
3439
- handler: async (args) => {
3440
- const ready = await this.readyState();
3441
- if ('error' in ready) return { text: ready.error, failed: true };
3442
- await this.sync();
3443
- const now = this.now();
3444
- const orderId = typeof args.order === 'string' ? args.order.trim() : '';
3445
- try {
3446
- if (orderId !== '') {
3447
- const delivered = deliverOrder(ready.game, orderId, now);
3448
- this.game = delivered.state;
3449
- await this.saveGame();
3450
- return delivered.text;
3451
- }
3452
- const orders = currentOrders(ready.game, now);
3453
- const lines = orders.map((o) => orderText(o, SPECIES[o.species].name));
3454
- return `今天的基因订单(${orders.length} 张):\n${lines.join('\n')}\n(订单每天刷新��交货用 genesis_orders �?order。)`;
3455
- } catch (error) {
3456
- return { text: errorText(error), failed: true };
3457
- }
3458
- },
3459
- };
3460
- }
3461
-
3462
- private mutateTool(): ToolDef {
3463
- return {
3464
- ...GENESIS_TOOL_DECLS[27]!,
3465
- handler: async (args) => {
3466
- const ready = await this.readyState();
3467
- if ('error' in ready) return { text: ready.error, failed: true };
3468
- await this.sync();
3469
- const bag = typeof args.bag === 'string' ? args.bag.trim() : '';
3470
- try {
3471
- const mutated = mutateBag(ready.game, bag, this.now());
3472
- this.game = mutated.state;
3473
- await this.saveGame();
3474
- return mutated.text;
3475
- } catch (error) {
3476
- return { text: errorText(error), failed: true };
3477
- }
3478
- },
3479
- };
3480
- }
3481
-
3482
- private wakeTool(): ToolDef {
3483
- return {
3484
- ...GENESIS_TOOL_DECLS[28]!,
3485
- handler: async (args) => {
3486
- const ready = await this.readyState();
3487
- if ('error' in ready) return { text: ready.error, failed: true };
3488
- await this.sync();
3489
- const system = await this.readSystem();
3490
- if (!system || !this.game) return { text: '还没有创世��?, failed: true };
3491
- try {
3492
- const woke = wakeHumans(system, this.game, typeof args.habitat === 'string' ? args.habitat : undefined, this.now());
3493
- this.game = woke.state;
3494
- await this.saveGame();
3495
- return woke.text;
3496
- } catch (error) {
3497
- return { text: errorText(error), failed: true };
3498
- }
3499
- },
3500
- };
3501
- }
3502
-
3503
- private veinsTool(): ToolDef {
3504
- return {
3505
- ...GENESIS_TOOL_DECLS[29]!,
3506
- handler: async () => {
3507
- const ready = await this.readyState();
3508
- if ('error' in ready) return { text: ready.error, failed: true };
3509
- await this.sync();
3510
- try {
3511
- const scanned = spectrometerScan(ready.system, this.game!, this.now());
3512
- this.game = scanned.state;
3513
- await this.saveGame();
3514
- return scanned.text;
3515
- } catch (error) {
3516
- return { text: errorText(error), failed: true };
3517
- }
3518
- },
3519
- };
3520
- }
3521
-
3522
- private routeTool(): ToolDef {
3523
- return {
3524
- ...GENESIS_TOOL_DECLS[30]!,
3525
- handler: async (args) => {
3526
- const ready = await this.readyState();
3527
- if ('error' in ready) return { text: ready.error, failed: true };
3528
- await this.sync();
3529
- const game = this.game!;
3530
- const storageId = typeof args.storage === 'string' && args.storage.trim()
3531
- ? args.storage.trim()
3532
- : (game.structures.find((s) => s.kind === 'storage_terminal' && s.planetIndex === game.homePlanetIndex)?.id
3533
- ?? game.structures.find((s) => s.kind === 'storage_terminal')?.id);
3534
- if (!storageId) {
3535
- return { text: '这颗行星上还没有【仓储终端������先建一座,再编排序号��?, failed: true };
3536
- }
3537
- const storageRec = game.structures.find((s) => s.id === storageId)!;
3538
- const planet = storageRec.planetIndex;
3539
- const raw = String(args.container ?? '').trim();
3540
- const container = /^\d+$/.test(raw)
3541
- ? game.structures.find((s) => s.planetIndex === planet && String(s.slot) === raw)
3542
- : game.structures.find((s) => s.id === raw);
3543
- if (!container) {
3544
- const known = game.structures
3545
- .filter((s) => s.planetIndex === planet && s.slot !== undefined)
3546
- .map((s) => `${s.slot}=${s.id}`)
3547
- .join('�?);
3548
- return { text: `没有这个容器�?{raw}(这颗行星上的槽位:${known || '丢�个都没有'})`, failed: true };
3549
- }
3550
- const priority = Number(args.priority);
3551
- try {
3552
- const result = routeContainer(game, storageId, container.id, priority);
3553
- this.game = result.state;
3554
- await this.saveGame();
3555
- const storage = result.state.structures.find((s) => s.id === storageId)!;
3556
- return `${result.text}\n${storageRouteText(result.state, storage)}`;
3557
- } catch (error) {
3558
- return { text: errorText(error), failed: true };
3559
- }
3560
- },
3561
- };
3562
- }
3563
-
3564
- private linkTool(): ToolDef {
3565
- return {
3566
- ...GENESIS_TOOL_DECLS[31]!,
3567
- handler: async (args) => {
3568
- const ready = await this.readyState();
3569
- if ('error' in ready) return { text: ready.error, failed: true };
3570
- await this.sync();
3571
- const game = this.game!;
3572
- const armId = typeof args.id === 'string' && args.id.trim()
3573
- ? args.id.trim()
3574
- : (game.structures.find((s) => s.kind === 'arm' && s.planetIndex === game.homePlanetIndex)?.id
3575
- ?? game.structures.find((s) => s.kind === 'arm')?.id);
3576
- if (!armId) return { text: '这颗行星上还没有【机械臂】����先建一座(genesis_install �?id: "arm")��?, failed: true };
3577
- const patch: { inputs?: string[]; output?: string; items?: string[] } = {};
3578
- if (Array.isArray(args.inputs)) patch.inputs = args.inputs.map((v) => String(v).trim()).filter(Boolean);
3579
- if (typeof args.output === 'string' && args.output.trim()) patch.output = args.output.trim();
3580
- if (Array.isArray(args.items)) patch.items = args.items.map((v) => String(v).trim()).filter(Boolean);
3581
- try {
3582
- const result = relinkArm(ready.system, game, armId, patch);
3583
- this.game = result.state;
3584
- await this.saveGame();
3585
- const arm = result.state.structures.find((s) => s.id === armId)!;
3586
- const cycling = armsInCycle(result.state).some((a) => a.id === armId);
3587
- return `${result.text}${cycling ? '\n注意:这条线接成环了—��货会在这里绕圈,白烧电�? : ''}`;
3588
- } catch (error) {
3589
- return { text: errorText(error), failed: true };
3590
- }
3591
- },
3592
- };
3593
- }
3594
-
3595
- private dutyTool(): ToolDef {
3596
- return {
3597
- ...GENESIS_TOOL_DECLS[32]!,
3598
- handler: async (args) => {
3599
- const ready = await this.readyState();
3600
- if ('error' in ready) return { text: ready.error, failed: true };
3601
- await this.sync();
3602
- const game = this.game!;
3603
- const dutyId = typeof args.id === 'string' && args.id.trim()
3604
- ? args.id.trim()
3605
- : (game.structures.find((s) => s.kind === 'duty' && s.planetIndex === game.homePlanetIndex)?.id
3606
- ?? game.structures.find((s) => s.kind === 'duty')?.id);
3607
- if (!dutyId) return { text: '这颗行星上还没有【��班终端】����先建一座(genesis_install �?id: "duty")��?, failed: true };
3608
- const patch: { habitat?: string; store?: string; sites?: string[] } = {};
3609
- if (typeof args.habitat === 'string' && args.habitat.trim()) patch.habitat = args.habitat.trim();
3610
- if (typeof args.store === 'string' && args.store.trim()) patch.store = args.store.trim();
3611
- if (Array.isArray(args.sites)) patch.sites = args.sites.map((v) => String(v).trim()).filter(Boolean);
3612
- try {
3613
- const result = relinkDuty(ready.system, game, dutyId, patch);
3614
- this.game = result.state;
3615
- await this.saveGame();
3616
- return result.text;
3617
- } catch (error) {
3618
- return { text: errorText(error), failed: true };
3619
- }
3620
- },
3621
- };
3622
- }
3623
-
3624
- private resetTool(): ToolDef {
3625
- return {
3626
- ...GENESIS_TOOL_DECLS[33]!,
3627
- handler: async (args) => {
3628
- if (String(args.confirm ?? '') !== 'DELETE') {
3629
- return { text: '要删档重弢�请传 confirm: "DELETE"�?, failed: true };
3630
- }
3631
- const deleted = await this.reset();
3632
- return deleted ? '存档已删除,可以重新创世�? : '本来就没有存档��?;
3633
- },
3634
- };
3635
- }
3636
- }