-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1330 lines (1172 loc) · 54.4 KB
/
script.js
File metadata and controls
1330 lines (1172 loc) · 54.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// =====================================================================================
// 1. GAME STATE & CORE ELEMENTS
// =====================================================================================
const gameOutput = document.getElementById('game-output');
const commandInput = document.getElementById('command-input');
const submitButton = document.getElementById('submit-command');
// Player Data
const player = {
health: 100,
maxHealth: 100,
stamina: 50, // NEW: For special combat abilities
maxStamina: 50, // NEW: For special combat abilities
inventory: {
wood: 0,
stone: 0,
ironOre: 0,
leather: 0,
fish: 0,
coal: 0,
healthPotion: 0, // NEW: Added Health Potion for 'use' command
// Crafted items / Tools
woodenAxe: 0,
stonePickaxe: 0,
ironSword: 0,
fishingRod: 0
},
equippedWeapon: null,
stats: {
strength: 1, // Base damage multiplier
gatheringEfficiency: 1, // Resource gain multiplier
luck: 1 // Chance for rare drops, etc.
},
location: 'forest', // Starting location
currentEnemy: null, // Holds the enemy object if in combat
factories: {}, // Stores data for built factories
isBlocking: false, // NEW: State for 'block' command
cooldowns: { // NEW: Object to track ability cooldowns in turns (0 means ready)
strongAttack: 0,
stun: 0,
// Add more abilities here
}
};
// =====================================================================================
// 2. GAME DATA DEFINITIONS (Highly Modular - Add/Modify easily)
// =====================================================================================
// --- Locations ---
// Define locations and what can be done there, and where you can go from there.
const locations = {
forest: {
name: "Forest",
description: "A dense forest. You can 'chop' trees here or 'explore' for secrets.",
actions: ['chop', 'explore'],
canGoTo: ['clearing', 'mountain_path']
},
clearing: {
name: "Clearing",
description: "A peaceful clearing. A good place to 'rest' or 'explore'. You see a river nearby.",
actions: ['rest', 'explore', 'fish', 'buildBridge'], // NEW: Added buildBridge action
canGoTo: ['forest', 'river']
// 'town_center' will be added here dynamically
},
mountain_path: {
name: "Mountain Path",
description: "A rugged path leading up a mountain. You can 'mine' rocks here.",
actions: ['mine', 'explore'],
canGoTo: ['forest', 'mountain_peak']
},
mountain_peak: {
name: "Mountain Peak",
description: "The windy peak of the mountain. You can 'mine' rare ores here, but it's dangerous.",
actions: ['mine', 'explore'],
canGoTo: ['mountain_path']
},
river: {
name: "River",
description: "A calm river flows here. You might be able to 'fish'.",
actions: ['fish', 'explore'],
canGoTo: ['clearing']
},
town_center: { // NEW: A locked location
name: "Town Center",
description: "A bustling town, full of merchants and opportunities.",
actions: ['explore', 'rest'],
canGoTo: ['clearing']
}
// Add more locations here!
// town: { ... }
};
// --- Recipes ---
// Define what items can be crafted, their requirements, and what they give.
const recipes = {
woodenAxe: {
name: "Wooden Axe",
requires: { wood: 5 },
gives: { woodenAxe: 1 },
description: "A basic axe for chopping wood more efficiently.",
type: 'tool'
},
stonePickaxe: {
name: "Stone Pickaxe",
requires: { wood: 3, stone: 5 },
gives: { stonePickaxe: 1 },
description: "A sturdy pickaxe for mining rocks.",
type: 'tool'
},
ironSword: {
name: "Iron Sword",
requires: { ironOre: 5, wood: 2 },
gives: { ironSword: 1 },
description: "A decent iron sword for combat.",
type: 'weapon',
damage: 15 // Base damage for this weapon
},
basicFishingRod: {
name: "Basic Fishing Rod",
requires: { wood: 4, leather: 1 },
gives: { fishingRod: 1 },
description: "A simple rod for catching fish."
},
healthPotion: { // NEW: Health Potion recipe
name: "Health Potion",
requires: { fish: 1, wood: 1 }, // Simple ingredients for now
gives: { healthPotion: 1 },
description: "A simple potion that restores some health.",
type: 'consumable'
}
// Add more recipes here!
};
// --- Enemies ---
// Define enemy types, their stats, and what they drop.
const enemies = {
goblin: {
name: "Goblin",
health: 20,
damage: 5,
drops: { wood: 1, stone: 1 },
description: "A small, mischievous creature.",
spawnChance: 0.3 // Chance to encounter when exploring
},
wolf: {
name: "Wolf",
health: 30,
damage: 8,
drops: { leather: 2 },
description: "A hungry, aggressive wolf.",
spawnChance: 0.2
},
rockGolem: {
name: "Rock Golem",
health: 50,
damage: 12,
drops: { stone: 5, ironOre: 1 },
description: "A creature made of solid rock. Found in mountains.",
spawnChance: 0.1,
canSpawnIn: ['mountain_path', 'mountain_peak'] // Specific spawn location
}
// Add more enemies here!
};
// --- Items (for general properties, not just crafting) ---
const items = {
wood: { name: "Wood", type: "resource" },
stone: { name: "Stone", type: "resource" },
ironOre: { name: "Iron Ore", type: "resource" },
leather: { name: "Leather", type: "resource" },
fish: { name: "Fish", type: "resource" },
coal: { name: "Coal", type: "resource" },
healthPotion: { name: "Health Potion", type: "consumable", heals: 30 }, // NEW: Health Potion item
woodenAxe: { name: "Wooden Axe", type: "tool", efficiencyBonus: 1.5, toolFor: 'chop' },
stonePickaxe: { name: "Stone Pickaxe", type: "tool", efficiencyBonus: 1.8, toolFor: 'mine' },
ironSword: { name: "Iron Sword", type: "weapon", damage: 15 },
fishingRod: { name: "Fishing Rod", type: "tool", toolFor: 'fish' }
// Add more item details if needed (e.g., value, healing properties)
};
// --- Factories ---
// Define types of factories, their costs, and what they passively produce
const factories = {
lumberMill: {
name: "Lumber Mill",
description: "Produces wood over time.",
buildRequires: { wood: 50, stone: 20 },
produces: { wood: 10 },
productionTimeMinutes: 1,
builtInLocation: ['forest', 'clearing']
},
stoneQuarry: {
name: "Stone Quarry",
description: "Produces stone over time.",
buildRequires: { wood: 30, stone: 50, ironOre: 5 },
produces: { stone: 15 },
productionTimeMinutes: 2,
builtInLocation: ['mountain_path', 'mountain_peak']
},
coalMine: {
name: "Coal Mine",
description: "Produces coal passively.",
buildRequires: { wood: 70, stone: 70, ironOre: 10 },
produces: { coal: 5 },
productionTimeMinutes: 3,
builtInLocation: ['mountain_path', 'mountain_peak']
}
};
// --- Unlocked Areas Data (NEW) ---
// Define new areas that can be unlocked by giving resources.
const unlockedAreas = {
town_center: {
name: "Town Center Path", // Name used in command (e.g., 'buildBridge town_center')
description: "Building a bridge to unlock the main Town.",
requires: { wood: 100, stone: 50, ironOre: 10 },
unlocksLocation: 'town_center',
unlockingLocation: 'clearing', // Where this can be done
unlocked: false // Player state, set to true after unlocking
}
// Add more unlockable areas here!
// ancient_temple: { name: "Ancient Temple Entrance", requires: { gold: 20 }, unlocksLocation: 'ancient_temple', unlockingLocation: 'desert', unlocked: false }
};
// --- Combat Abilities (NEW) ---
// Define special combat moves.
const combatAbilities = {
strongAttack: {
name: "Strong Attack",
description: "A powerful blow that deals more damage.",
staminaCost: 20,
damageMultiplier: 1.5,
cooldown: 3, // Cooldown in turns
effects: [] // Can add status effects here later
},
block: {
name: "Block",
description: "You brace yourself, heavily reducing incoming damage next turn.",
staminaCost: 10,
cooldown: 2 // Cannot block every turn
},
stun: {
name: "Stun",
description: "Attempt to stun the enemy, making them lose a turn. Low chance.",
staminaCost: 30,
cooldown: 5,
successChance: 0.3 // 30% chance to stun
},
focus: { // This one acts as a counter-intuitive healing option
name: "Focus",
description: "Regain stamina and reduce cooldowns, but leaves you vulnerable.",
staminaGain: 20,
vulnerability: 0.5, // Enemy deals 50% more damage next turn
cooldown: 4
}
// 'sprint' (new flee) does not need an entry here, it's a direct action
};
// =====================================================================================
// 3. UTILITY FUNCTIONS
// =====================================================================================
// Display messages in the game output area
function output(text, type = 'info') {
const p = document.createElement('p');
p.classList.add(`text-${type}`);
p.textContent = `> ${text}`;
gameOutput.appendChild(p);
gameOutput.scrollTop = gameOutput.scrollHeight; // Auto-scroll to bottom
}
// Clear the input field after command
function clearInput() {
commandInput.value = '';
}
// Get player's current weapon damage
function getPlayerDamage() {
let baseDamage = player.stats.strength * 5; // Base damage from strength
if (player.equippedWeapon && recipes[player.equippedWeapon] && recipes[player.equippedWeapon].damage) {
baseDamage += recipes[player.equippedWeapon].damage;
} else {
baseDamage += 2; // Bare hands damage
}
return baseDamage;
}
// Function to check if player has a required tool for an action
function hasTool(actionType) {
for (const toolKey in player.inventory) {
if (player.inventory[toolKey] > 0 && items[toolKey] && items[toolKey].toolFor === actionType) {
return toolKey; // Return the key of the tool found
}
}
return null; // No suitable tool found
}
// Get tool efficiency bonus
function getToolEfficiency(actionType) {
const tool = hasTool(actionType);
if (tool && items[tool] && items[tool].efficiencyBonus) {
return items[tool].efficiencyBonus;
}
return 1; // No bonus if no tool or tool has no efficiencyBonus
}
// Helper to find data key (recipe, item, factory, etc.) by case-insensitive name
function findDataKey(inputName, dataObject) {
const lowerInput = inputName.toLowerCase();
for (const key in dataObject) {
if (key.toLowerCase() === lowerInput || (dataObject[key].name && dataObject[key].name.toLowerCase() === lowerInput)) {
return key; // Return the actual key (e.g., 'basicFishingRod', 'lumberMill', 'ironSword')
}
}
return null; // Not found
}
// --- Combat Specific Utilities (NEW) ---
// Handles the enemy's turn in combat
function enemyTurn() {
if (!player.currentEnemy) return; // Should not happen if called correctly
// Decrement player's active cooldowns
for (const ability in player.cooldowns) {
if (player.cooldowns[ability] > 0) {
player.cooldowns[ability]--;
}
}
// Handle effects like stun
if (player.currentEnemy.isStunned) {
output(`The ${player.currentEnemy.name} is stunned and skips its turn!`, 'highlight');
player.currentEnemy.isStunned = false; // Stun wears off after one turn
return; // Skip enemy attack
}
// Calculate enemy damage
let enemyDamage = player.currentEnemy.damage;
if (player.isBlocking) {
enemyDamage = Math.max(1, enemyDamage - Math.floor(player.maxHealth * 0.2)); // Reduce damage by 20% of max health, minimum 1
output(`Your block reduces the ${player.currentEnemy.name}'s attack!`, 'info');
player.isBlocking = false; // Block only lasts for one turn
}
if (player.isVulnerable) { // For 'focus' vulnerability
enemyDamage = Math.floor(enemyDamage * (1 + combatAbilities.focus.vulnerability));
output(`Your focus leaves you open! The ${player.currentEnemy.name} deals more damage!`, 'warning');
player.isVulnerable = false; // Vulnerability lasts one turn
}
player.health -= enemyDamage;
output(`The ${player.currentEnemy.name} attacks you for ${enemyDamage} damage! Your health: ${player.health}/${player.maxHealth}.`, 'danger');
// Check if player died
if (player.health <= 0) {
output("You have been defeated...", 'danger');
output("GAME OVER", 'danger');
output("Type 'start' to play again.", 'highlight');
endCombat();
commandInput.disabled = true;
submitButton.disabled = true;
return;
}
}
// Ends the current combat encounter
function endCombat() {
if (player.currentEnemy) {
output(`Combat with ${player.currentEnemy.name} has ended.`, 'highlight');
player.currentEnemy = null; // Clear enemy
}
player.isBlocking = false; // Clear any combat-related flags
player.isVulnerable = false;
// Keep cooldowns, they are based on turns and persist
}
// Central function to be called after a player combat action (like attack, block, etc.)
function startCombatTurn() {
// Check if enemy died from player's action
if (player.currentEnemy.health <= 0) {
output(`You defeated the ${player.currentEnemy.name}!`, 'success');
output("--- Loot ---", 'highlight');
let droppedAny = false;
for (const dropItem in player.currentEnemy.drops) {
const amount = player.currentEnemy.drops[dropItem];
player.inventory[dropItem] = (player.inventory[dropItem] || 0) + amount;
output(`You gained ${amount} ${items[dropItem]?.name || dropItem}.`, 'info');
droppedAny = true;
}
if (!droppedAny) {
output("The enemy dropped nothing.", 'info');
}
endCombat();
return; // Combat over, no enemy turn
}
// If enemy is not defeated, it's their turn
enemyTurn();
}
// =====================================================================================
// 4. GAME ACTIONS (Highly Modular - Add new commands here)
// =====================================================================================
const gameActions = {
// --- BASIC COMMANDS ---
help: (args) => {
output("Available commands:", 'highlight');
output(" 'help' - Shows this list.", 'info');
output(" 'status' - Check your health, stamina, and location.", 'info');
output(" 'inventory' or 'inv' - Check your resources and items.", 'info');
output(" 'go <location_name>' - Travel to a new location (e.g., 'go clearing').", 'info');
output(" 'look' - Get a description of your current location.", 'info');
output(" 'clear' - Clear the game log.", 'info');
output(" 'craft <recipe_name>' - Create an item (e.g., 'craft woodenAxe').", 'info');
output(" 'recipes' - See all craftable recipes.", 'info');
output(" 'equip <weapon_name>' - Equip a weapon from your inventory (e.g., 'equip ironSword').", 'info');
output(" 'unequip' - Unequip your current weapon.", 'info');
output(" 'use <item_name>' - Use a consumable item (e.g., 'use healthPotion').", 'info');
output(" 'build <factory_name>' - Build a passive resource factory.", 'info');
output(" 'factories' - See your built factories and their production status.", 'info');
output(" 'collect <factory_name>' - Collect resources from a built factory.", 'info');
const currentLoc = locations[player.location];
if (currentLoc && currentLoc.actions) {
output(`\nActions available in ${currentLoc.name}:`, 'highlight');
currentLoc.actions.forEach(action => {
let description = '';
if (action === 'chop') description = 'chop trees';
else if (action === 'mine') description = 'mine rocks';
else if (action === 'explore') description = 'explore area';
else if (action === 'rest') description = 'recover health and stamina';
else if (action === 'fish') description = 'try to catch fish';
else if (action === 'buildBridge') description = 'try to build a bridge to a new area'; // NEW help for unlock
if (description) {
output(` '${action}' - ${description}.`, 'info');
} else {
output(` '${action}' - Perform this action.`, 'info'); // Fallback for undefined actions
}
});
}
if (player.currentEnemy) {
output("\nCombat commands (only available in combat):", 'highlight');
output(" 'attack' - Attack the current enemy.", 'info');
output(" 'block' - Reduce incoming damage this turn (costs stamina, has cooldown).", 'info'); // NEW
output(" 'strongattack' - A powerful attack (costs stamina, has cooldown).", 'info'); // NEW
output(" 'stun' - Attempt to stun the enemy (costs stamina, has cooldown, low chance).", 'info'); // NEW
output(" 'inspect' - Get more info about the enemy (no turn cost).", 'info'); // NEW
output(" 'focus' - Regain stamina, but take more damage next turn (has cooldown).", 'info'); // NEW
output(" 'sprint' - Escape from combat (guaranteed flee, takes a turn, no cooldown).", 'info'); // NEW
}
},
status: (args) => {
output("--- Your Status ---", 'highlight');
output(`Health: ${player.health}/${player.maxHealth}`, player.health < player.maxHealth / 4 ? 'danger' : 'info');
output(`Stamina: ${player.stamina}/${player.maxStamina}`, player.stamina < player.maxStamina / 4 ? 'warning' : 'info'); // NEW
output(`Location: ${locations[player.location]?.name || 'Unknown'}`, 'info');
output(`Equipped: ${player.equippedWeapon ? items[player.equippedWeapon]?.name || player.equippedWeapon : 'None'}`, 'info');
output(`Strength: ${player.stats.strength}`, 'info');
output(`Gathering Efficiency: ${player.stats.gatheringEfficiency}`, 'info');
output(`Luck: ${player.stats.luck}`, 'info');
let cooldownInfo = '';
for (const ability in player.cooldowns) {
if (player.cooldowns[ability] > 0) {
if (cooldownInfo) cooldownInfo += ', ';
cooldownInfo += `${combatAbilities[ability]?.name || ability}: ${player.cooldowns[ability]} turns`;
}
}
if (cooldownInfo) {
output(`Cooldowns: ${cooldownInfo}`, 'info');
}
output("-------------------", 'highlight');
},
inventory: (args) => {
output("--- Your Inventory ---", 'highlight');
let empty = true;
for (const item in player.inventory) {
if (player.inventory[item] > 0) {
output(`${items[item]?.name || item}: ${player.inventory[item]}`, 'info');
empty = false;
}
}
if (empty) {
output("Your inventory is empty.", 'info');
}
output("--------------------", 'highlight');
},
inv: (args) => gameActions.inventory(args), // Alias for inventory
look: (args) => {
const currentLoc = locations[player.location];
if (currentLoc) {
output(`You are in the ${currentLoc.name}.`, 'highlight');
output(currentLoc.description, 'info');
const exits = currentLoc.canGoTo.map(loc => locations[loc]?.name || loc).join(', ');
output(`From here, you can go to: ${exits}.`, 'info');
} else {
output("You are in an unknown place.", 'danger');
}
},
clear: (args) => {
gameOutput.innerHTML = ''; // Clears the output log
output("Game log cleared.", 'info');
},
// --- MOVEMENT COMMANDS ---
go: (args) => {
if (player.currentEnemy) {
output("You can't move while in combat! 'sprint' to flee or 'attack'.", 'warning');
return;
}
const targetLocationKey = args[0]; // Already lowercased from processCommand
if (!targetLocationKey) {
output("Go where? (e.g., 'go forest')", 'warning');
return;
}
const currentLoc = locations[player.location];
if (!currentLoc) {
output("Your current location is unknown.", 'danger');
return;
}
if (currentLoc.canGoTo.includes(targetLocationKey) && locations[targetLocationKey]) {
player.location = targetLocationKey;
output(`You travel to the ${locations[targetLocationKey].name}.`, 'success');
gameActions.look(); // Show description of new location
} else {
output(`You cannot go to '${targetLocationKey}' from here.`, 'warning');
}
},
// --- GATHERING COMMANDS ---
chop: (args) => {
if (player.currentEnemy) { output("You can't gather while in combat!", 'warning'); return; }
const currentLoc = locations[player.location];
if (!currentLoc || !currentLoc.actions.includes('chop')) {
output("You can't chop trees here.", 'warning');
return;
}
const tool = hasTool('chop');
if (!tool) {
output("You need an axe to chop trees effectively! Craft one with 'craft woodenAxe'.", 'warning');
return;
}
const amount = Math.floor(5 * player.stats.gatheringEfficiency * getToolEfficiency('chop'));
player.inventory.wood += amount;
output(`You chop some trees and gain ${amount} wood. You now have ${player.inventory.wood} wood.`, 'success');
},
mine: (args) => {
if (player.currentEnemy) { output("You can't gather while in combat!", 'warning'); return; }
const currentLoc = locations[player.location];
if (!currentLoc || !currentLoc.actions.includes('mine')) {
output("You can't mine rocks here.", 'warning');
return;
}
const tool = hasTool('mine');
if (!tool) {
output("You need a pickaxe to mine rocks effectively! Craft one with 'craft stonePickaxe'.", 'warning');
return;
}
const amount = Math.floor(3 * player.stats.gatheringEfficiency * getToolEfficiency('mine'));
player.inventory.stone += amount;
output(`You mine some rocks and gain ${amount} stone. You now have ${player.inventory.stone} stone.`, 'success');
if (player.location.includes('mountain')) {
if (Math.random() < 0.2 * player.stats.luck) {
const ironAmount = Math.floor(1 * player.stats.gatheringEfficiency * getToolEfficiency('mine'));
player.inventory.ironOre += ironAmount;
output(`You found ${ironAmount} Iron Ore while mining!`, 'highlight');
}
}
},
fish: (args) => {
if (player.currentEnemy) { output("You can't gather while in combat!", 'warning'); return; }
const currentLoc = locations[player.location];
if (!currentLoc || !currentLoc.actions.includes('fish')) {
output("There's no water to fish in here.", 'warning');
return;
}
const tool = hasTool('fish');
if (!tool) {
output("You need a fishing rod to fish! Craft one with 'craft basicFishingRod'.", 'warning');
return;
}
if (Math.random() < 0.7) {
const fishAmount = Math.floor(1 + Math.random() * player.stats.gatheringEfficiency);
player.inventory.fish += fishAmount;
output(`You cast your line and catch ${fishAmount} fish! You now have ${player.inventory.fish} fish.`, 'success');
} else {
output("You waited patiently, but nothing bit this time.", 'info');
}
},
rest: (args) => {
if (player.currentEnemy) { output("You can't rest while in combat!", 'warning'); return; }
const currentLoc = locations[player.location];
if (!currentLoc || !currentLoc.actions.includes('rest')) {
output("You can't rest here.", 'warning');
return;
}
const healthRecovered = Math.min(player.maxHealth - player.health, 20);
player.health += healthRecovered;
const staminaRecovered = Math.min(player.maxStamina - player.stamina, 20); // NEW: Recover stamina
player.stamina += staminaRecovered;
if (healthRecovered > 0 || staminaRecovered > 0) {
output(`You rest for a while and recover ${healthRecovered} health and ${staminaRecovered} stamina.`, 'success');
output(`Your health: ${player.health}/${player.maxHealth}. Your stamina: ${player.stamina}/${player.maxStamina}.`, 'info');
} else {
output("You are already at full health and stamina.", 'info');
}
// Clear all cooldowns for resting
for (const ability in player.cooldowns) {
player.cooldowns[ability] = 0;
}
if (healthRecovered > 0 || staminaRecovered > 0) {
output("All combat cooldowns are reset after resting.", 'highlight');
}
},
// --- CRAFTING & EQUIPMENT COMMANDS ---
recipes: (args) => {
output("--- Available Recipes ---", 'highlight');
let anyRecipes = false;
for (const recipeKey in recipes) {
anyRecipes = true;
const recipe = recipes[recipeKey];
output(`\n** ${recipe.name} **`, 'special');
output(` ${recipe.description}`, 'info');
let requiresText = " Requires: ";
const requiredItems = [];
for (const reqItemKey in recipe.requires) {
const requiredAmount = recipe.requires[reqItemKey];
const itemName = items[reqItemKey]?.name || reqItemKey;
requiredItems.push(`${requiredAmount} ${itemName} (you have ${player.inventory[reqItemKey] || 0})`);
}
output(requiresText + (requiredItems.length > 0 ? requiredItems.join(', ') : 'None'), 'info');
let givesText = " Gives: ";
const givesItems = [];
for (const giveItemKey in recipe.gives) {
const givenAmount = recipe.gives[giveItemKey];
const itemName = items[giveItemKey]?.name || giveItemKey;
givesItems.push(`${givenAmount} ${itemName}`);
}
output(givesText + givesItems.join(', '), 'info');
}
if (!anyRecipes) {
output("No recipes are defined.", 'warning');
}
output("\n--------------------", 'highlight');
output("Use 'craft <recipe_name>' (e.g., 'craft woodenAxe').", 'info');
},
craft: (args) => {
if (player.currentEnemy) { output("You can't craft while in combat!", 'warning'); return; }
const inputRecipeName = args[0];
if (!inputRecipeName) {
output("What do you want to craft? (e.g., 'craft woodenAxe')", 'warning');
output("Type 'recipes' to see all available recipes.", 'info');
return;
}
const recipeKey = findDataKey(inputRecipeName, recipes);
if (!recipeKey) {
output(`Unknown recipe: '${inputRecipeName}'. Type 'recipes' to see options.`, 'danger');
return;
}
const recipe = recipes[recipeKey];
output(`Attempting to craft ${recipe.name}...`, 'info');
let canCraft = true;
for (const resource in recipe.requires) {
if ((player.inventory[resource] || 0) < recipe.requires[resource]) {
output(`You need ${recipe.requires[resource]} ${items[resource]?.name || resource}, but you only have ${player.inventory[resource] || 0}.`, 'danger');
canCraft = false;
}
}
if (canCraft) {
for (const resource in recipe.requires) {
player.inventory[resource] -= recipe.requires[resource];
}
for (const item in recipe.gives) {
player.inventory[item] = (player.inventory[item] || 0) + recipe.gives[item];
output(`You successfully crafted a ${recipe.name}!`, 'success');
}
} else {
output(`Failed to craft ${recipe.name}. Missing resources.`, 'warning');
}
},
equip: (args) => {
if (player.currentEnemy) { output("You can't equip while in combat!", 'warning'); return; }
const itemName = args[0];
if (!itemName) {
output("What do you want to equip? (e.g., 'equip ironSword')", 'warning');
return;
}
const itemToEquipKey = findDataKey(itemName, items);
if (!itemToEquipKey) {
output(`Unknown item: '${itemName}'.`, 'danger');
return;
}
const itemToEquip = items[itemToEquipKey];
if (itemToEquip.type !== 'weapon') {
output(`You can't equip '${itemToEquip.name}' or it's not a weapon.`, 'warning');
return;
}
if (player.inventory[itemToEquipKey] === 0) {
output(`You don't have a '${itemToEquip.name}' in your inventory.`, 'warning');
return;
}
player.equippedWeapon = itemToEquipKey;
output(`You equipped the ${itemToEquip.name}.`, 'success');
},
unequip: (args) => {
if (player.currentEnemy) { output("You can't unequip while in combat!", 'warning'); return; }
if (!player.equippedWeapon) {
output("You don't have anything equipped.", 'info');
return;
}
output(`You unequipped your ${items[player.equippedWeapon]?.name || player.equippedWeapon}.`, 'success');
player.equippedWeapon = null;
},
use: (args) => {
const itemName = args[0];
if (!itemName) {
output("What do you want to use? (e.g., 'use healthPotion')", 'warning');
return;
}
const itemToUseKey = findDataKey(itemName, items);
if (!itemToUseKey) {
output(`Unknown item: '${itemName}'.`, 'danger');
return;
}
const itemToUse = items[itemToUseKey];
if (player.inventory[itemToUseKey] === 0) {
output(`You don't have any '${itemToUse.name}'.`, 'warning');
return;
}
// --- Handle consumable type items ---
if (itemToUse.type === 'consumable') {
if (itemToUse.heals) {
const amountHealed = Math.min(itemToUse.heals, player.maxHealth - player.health);
if (amountHealed <= 0) {
output("You are already at full health.", 'info');
return;
}
player.health += amountHealed;
player.inventory[itemToUseKey]--;
output(`You used a ${itemToUse.name} and recovered ${amountHealed} health! Your health is now ${player.health}/${player.maxHealth}.`, 'success');
// If in combat, this consumes a turn
if (player.currentEnemy) {
output(`(Using the ${itemToUse.name} takes your turn)`, 'info');
startCombatTurn();
}
} else {
output(`You can't 'use' the '${itemToUse.name}' in that way.`, 'warning');
}
} else {
output(`You can't 'use' the '${itemToUse.name}'. It's not a consumable item.`, 'warning');
}
},
// --- FACTORY COMMANDS ---
build: (args) => {
if (player.currentEnemy) { output("You can't build while in combat!", 'warning'); return; }
const inputFactoryName = args[0];
if (!inputFactoryName) {
output("What do you want to build? (e.g., 'build lumberMill')", 'warning');
output("\n--- Buildable Factories ---", 'highlight');
let anyFactories = false;
for (const factoryKey in factories) {
anyFactories = true;
const factory = factories[factoryKey];
let requiresText = "Requires: ";
const requiredItems = [];
for (const reqItemKey in factory.buildRequires) {
const requiredAmount = factory.buildRequires[reqItemKey];
const itemName = items[reqItemKey]?.name || reqItemKey;
requiredItems.push(`${requiredAmount} ${itemName} (you have ${player.inventory[reqItemKey] || 0})`);
}
output(`\n** ${factory.name} ** (${factory.description})`, 'special');
output(` ${requiresText} ${requiredItems.join(', ')}`, 'info');
output(` Can be built in: ${factory.builtInLocation.map(loc => locations[loc]?.name || loc).join(', ')}`, 'info');
output(` Produces: ${factory.produces ? Object.keys(factory.produces).map(res => `${factory.produces[res]} ${items[res]?.name || res}`).join(', ') : 'Nothing'} every ${factory.productionTimeMinutes} min.`, 'info');
}
if (!anyFactories) {
output("No factories are defined to build.", 'warning');
}
output("--------------------------", 'highlight');
return;
}
const factoryKey = findDataKey(inputFactoryName, factories);
if (!factoryKey) {
output(`Unknown factory type: '${inputFactoryName}'.`, 'danger');
return;
}
const factoryToBuild = factories[factoryKey];
if (player.factories[factoryKey]) {
output(`You already have a ${factoryToBuild.name}! You can only build one of each type.`, 'warning');
return;
}
if (!factoryToBuild.builtInLocation.includes(player.location)) {
output(`You cannot build a ${factoryToBuild.name} in the ${locations[player.location]?.name || 'current location'}. It can only be built in: ${factoryToBuild.builtInLocation.map(loc => locations[loc]?.name || loc).join(', ')}.`, 'warning');
return;
}
output(`Attempting to build a ${factoryToBuild.name}...`, 'info');
let canBuild = true;
for (const resource in factoryToBuild.buildRequires) {
if ((player.inventory[resource] || 0) < factoryToBuild.buildRequires[resource]) {
output(`You need ${factoryToBuild.buildRequires[resource]} ${items[resource]?.name || resource}, but you only have ${player.inventory[resource] || 0}.`, 'danger');
canBuild = false;
}
}
if (canBuild) {
for (const resource in factoryToBuild.buildRequires) {
player.inventory[resource] -= factoryToBuild.buildRequires[resource];
}
player.factories[factoryKey] = {
builtTime: Date.now(),
lastCollectedTime: Date.now() // Start collection timer now
};
output(`You successfully built a ${factoryToBuild.name}! It has begun passive production.`, 'success');
} else {
output(`Failed to build ${factoryToBuild.name}. Missing resources.`, 'warning');
}
},
factories: (args) => {
output("--- Your Factories ---", 'highlight');
let empty = true;
for (const factoryKey in player.factories) {
empty = false;
const factoryStatus = player.factories[factoryKey];
const factoryDef = factories[factoryKey];
if (!factoryDef) continue; // Should not happen if data is consistent
output(`\n** ${factoryDef.name} **`, 'special');
const now = Date.now();
const elapsedTimeMillis = now - factoryStatus.lastCollectedTime;
const cycleMillis = factoryDef.productionTimeMinutes * 60 * 1000;
const cyclesCompleted = Math.floor(elapsedTimeMillis / cycleMillis);
let producedInfo = [];
if (cyclesCompleted > 0) {
for (const prodItem in factoryDef.produces) {
const totalProduced = factoryDef.produces[prodItem] * cyclesCompleted;
producedInfo.push(`${totalProduced} ${items[prodItem]?.name || prodItem}`);
}
output(` Ready to collect: ${producedInfo.join(', ')}`, 'highlight');
} else {
const millisUntilNext = cycleMillis - (elapsedTimeMillis % cycleMillis);
const secondsUntilNext = Math.ceil(millisUntilNext / 1000);
output(` Next collection ready in: ${Math.floor(secondsUntilNext / 60)} min ${secondsUntilNext % 60} sec.`, 'info');
output(` (Collects: ${Object.keys(factoryDef.produces).map(res => `${factoryDef.produces[res]} ${items[res]?.name || res}`).join(', ')})`, 'info');
}
output(` Last Collected: ${new Date(factoryStatus.lastCollectedTime).toLocaleString()}`, 'info');
}
if (empty) {
output("You have not built any factories yet.", 'info');
output("Use 'build' to see available options.", 'info');
}
output("\n--------------------", 'highlight');
},
collect: (args) => {
if (player.currentEnemy) { output("You can't collect while in combat!", 'warning'); return; }
const inputFactoryName = args[0];
if (!inputFactoryName) {
output("Collect from which factory? (e.g., 'collect lumberMill')", 'warning');
output("Use 'factories' to see your built factories.", 'info');
return;
}
const factoryKey = findDataKey(inputFactoryName, factories);
if (!factoryKey) {
output(`Unknown factory: '${inputFactoryName}'.`, 'danger');
return;
}
const factoryDef = factories[factoryKey];
const factoryStatus = player.factories[factoryKey];
if (!factoryStatus) {
output(`You don't own a ${factoryDef.name}. Build it first with 'build ${factoryKey}'.`, 'warning');
return;
}
const now = Date.now();
const elapsedTimeMillis = now - factoryStatus.lastCollectedTime;
const cycleMillis = factoryDef.productionTimeMinutes * 60 * 1000;
const cyclesCompleted = Math.floor(elapsedTimeMillis / cycleMillis);
if (cyclesCompleted === 0) {
const millisUntilNext = cycleMillis - (elapsedTimeMillis % cycleMillis);
const secondsUntilNext = Math.ceil(millisUntilNext / 1000);
output(`Your ${factoryDef.name} is not ready for collection yet. Next ready in ${Math.floor(secondsUntilNext / 60)} min ${secondsUntilNext % 60} sec.`, 'info');
return;
}
output(`Collecting from your ${factoryDef.name}...`, 'info');
let collectedAny = false;
for (const prodItem in factoryDef.produces) {
const totalProduced = factoryDef.produces[prodItem] * cyclesCompleted;
player.inventory[prodItem] = (player.inventory[prodItem] || 0) + totalProduced;
output(`You collected ${totalProduced} ${items[prodItem]?.name || prodItem}.`, 'success');
collectedAny = true;
}
if (collectedAny) {
player.factories[factoryKey].lastCollectedTime = factoryStatus.lastCollectedTime + (cyclesCompleted * cycleMillis);
output(`${cyclesCompleted} production cycles collected!`, 'success');
} else {
output(`Your ${factoryDef.name} produced nothing this time.`, 'info');
}
},
// --- AREA UNLOCKING COMMANDS (NEW) ---
buildBridge: (args) => {
if (player.currentEnemy) { output("You can't do that while in combat!", 'warning'); return; }
if (player.location !== unlockedAreas.town_center.unlockingLocation) {
output(`You need to be in the ${locations[unlockedAreas.town_center.unlockingLocation].name} to do this.`, 'warning');
return;
}
const areaToUnlock = unlockedAreas.town_center; // Only one unlockable for now
if (areaToUnlock.unlocked) {
output(`The path to ${locations[areaToUnlock.unlocksLocation].name} is already clear!`, 'info');
return;
}
output(`You consider building a bridge to the ${locations[areaToUnlock.unlocksLocation].name}.`, 'info');
let requiresText = "This requires: ";
const requiredItems = [];
let canPay = true;
for (const reqItemKey in areaToUnlock.requires) {
const requiredAmount = areaToUnlock.requires[reqItemKey];
const itemName = items[reqItemKey]?.name || reqItemKey;
requiredItems.push(`${requiredAmount} ${itemName} (you have ${player.inventory[reqItemKey] || 0})`);
if ((player.inventory[reqItemKey] || 0) < requiredAmount) {
canPay = false;
}
}
output(requiresText + requiredItems.join(', '), 'highlight');
if (!canPay) {
output("You don't have enough resources to build the bridge yet.", 'danger');
return;
}
output("Are you sure you want to spend these resources to build the bridge? (Type 'yes' to confirm)", 'warning');
commandInput.value = ''; // Clear for user confirmation