-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
1311 lines (1119 loc) · 47.7 KB
/
game.js
File metadata and controls
1311 lines (1119 loc) · 47.7 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
// Main game logic
// Game Manager class
class GameManager {
constructor() {
// Game properties
this.drillPower = 1;
this.drillSpeed = 1000; // ms between drill operations
this.energyRechargeRate = 0.5; // energy per second
this.maxDepth = 100;
this.currentDepth = 0;
this.isDrilling = false;
this.drillInterval = null;
this.currentLayer = 1;
this.soundEnabled = localStorage.getItem('miningTycoonSoundEnabled') !== 'false'; // Default to true unless explicitly set to false
this.visualEffectsEnabled = localStorage.getItem('miningTycoonEffectsEnabled') !== 'false'; // Default to true unless explicitly set to false
this.particleSystem = new ParticleSystem();
this.floatingTexts = [];
this.researchManager = null; // Will be initialized after resource manager
// Initialize managers
this.resourceManager = new ResourceManager();
this.upgradeManager = new UpgradeManager(this.resourceManager, this);
this.researchManager = new ResearchManager(this.resourceManager, this);
// Canvas setup
this.canvas = document.getElementById('mining-canvas');
this.ctx = this.canvas.getContext('2d');
// Grid setup
this.gridSize = 20; // Size of each grid cell
this.gridWidth = Math.floor(this.canvas.width / this.gridSize);
this.gridHeight = Math.floor(this.canvas.height / this.gridSize);
this.grid = this.initializeGrid();
// Load saved game if available
this.loadGame();
// Initialize game
this.setupEventListeners();
this.startEnergyRecharge();
this.upgradeManager.updateUpgradesDisplay();
this.resourceManager.updateDisplay();
this.researchManager.updateResearchDisplay();
this.render();
// Start auto-save
this.startAutoSave();
// Start animation loop
this.startAnimationLoop();
}
// Initialize the grid with empty cells
initializeGrid() {
const grid = [];
for (let y = 0; y < this.gridHeight; y++) {
const row = [];
for (let x = 0; x < this.gridWidth; x++) {
row.push({
type: null,
revealed: false
});
}
grid.push(row);
}
return grid;
}
// Set up event listeners
setupEventListeners() {
// Drill button
document.getElementById('drill-btn').addEventListener('click', () => {
this.toggleDrilling();
});
// Sell resources button
document.getElementById('sell-btn').addEventListener('click', () => {
this.resourceManager.sellResources();
});
// Save game button
document.getElementById('save-btn').addEventListener('click', () => {
this.saveGame();
showNotification("Game saved successfully!");
});
// Restart game button
document.getElementById('restart-btn').addEventListener('click', () => {
document.getElementById('restart-modal').classList.add('show');
});
// Confirm restart button
document.getElementById('confirm-restart').addEventListener('click', () => {
this.restartGame();
document.getElementById('restart-modal').classList.remove('show');
});
// Cancel restart button
document.getElementById('cancel-restart').addEventListener('click', () => {
document.getElementById('restart-modal').classList.remove('show');
});
// Toggle sound button
document.getElementById('sound-btn').addEventListener('click', () => {
this.soundEnabled = !this.soundEnabled;
document.getElementById('sound-btn').textContent =
this.soundEnabled ? "🔊 Sound: ON" : "🔇 Sound: OFF";
// Store sound preference in localStorage to persist it
localStorage.setItem('miningTycoonSoundEnabled', this.soundEnabled.toString());
});
// Toggle visual effects button
document.getElementById('effects-btn').addEventListener('click', () => {
this.visualEffectsEnabled = !this.visualEffectsEnabled;
document.getElementById('effects-btn').textContent =
this.visualEffectsEnabled ? "✨ Effects: ON" : "❌ Effects: OFF";
// Store effects preference in localStorage to persist it
localStorage.setItem('miningTycoonEffectsEnabled', this.visualEffectsEnabled.toString());
});
// Canvas click for manual drilling
this.canvas.addEventListener('click', (e) => {
const rect = this.canvas.getBoundingClientRect();
const x = Math.floor((e.clientX - rect.left) / this.gridSize);
const y = Math.floor((e.clientY - rect.top) / this.gridSize);
// Only allow drilling in valid cells
if (this.isValidDrillTarget(x, y)) {
this.drillAt(x, y);
}
});
}
// Restart the game
restartGame() {
// Clear local storage
localStorage.removeItem('miningTycoonSave');
// Show notification
showNotification("Game restarted! Starting fresh...");
// Play sound if enabled
if (this.soundEnabled) {
this.playSound('restart');
}
// Reset all game values
this.drillPower = 1;
this.drillSpeed = 1000;
this.energyRechargeRate = 0.5;
this.maxDepth = 100;
this.currentDepth = 0;
this.currentLayer = 1;
this.isDrilling = false;
if (this.drillInterval) {
clearInterval(this.drillInterval);
this.drillInterval = null;
}
// Reset resource manager
this.resourceManager.money = 0;
this.resourceManager.totalMoneyEarned = 0;
this.resourceManager.energy = 100;
this.resourceManager.maxEnergy = 100;
this.resourceManager.storage = 0;
this.resourceManager.maxStorage = 100;
Object.keys(this.resourceManager.inventory).forEach(resource => {
this.resourceManager.inventory[resource] = 0;
});
// Reset upgrade manager
Object.keys(this.upgradeManager.upgradeLevels).forEach(upgrade => {
this.upgradeManager.upgradeLevels[upgrade] = 0;
});
// Reset research manager
this.researchManager.researchPoints = 0;
this.researchManager.researchRate = 0.1;
this.researchManager.activeResearch = null;
this.researchManager.researchProgress = {};
this.researchManager.completedResearch = [];
// Reset grid
this.grid = this.initializeGrid();
// Update displays
this.resourceManager.updateDisplay();
this.upgradeManager.updateUpgradesDisplay();
this.researchManager.updateResearchDisplay();
this.render();
// Add visual effect
if (this.visualEffectsEnabled) {
// Create particles across the screen
for (let i = 0; i < 30; i++) {
const x = Math.random() * this.canvas.width;
const y = Math.random() * this.canvas.height;
const colors = ['#FFD700', '#FF5722', '#4CAF50', '#2196F3', '#9C27B0'];
const color = colors[Math.floor(Math.random() * colors.length)];
this.particleSystem.createParticles(x, y, color, 15);
}
}
}
// Check if a cell is a valid drill target
isValidDrillTarget(x, y) {
// Check if coordinates are within bounds
if (x < 0 || x >= this.gridWidth || y < 0 || y >= this.gridHeight) {
return false;
}
// Check if cell is already revealed
if (this.grid[y][x].revealed) {
return false;
}
// Check if there's a revealed cell adjacent to this one
// For the first cell, we'll allow drilling at the top row
if (y === 0) {
return true;
}
// Check adjacent cells (up, down, left, right)
const adjacentCells = [
{ x, y: y - 1 }, // up
{ x, y: y + 1 }, // down
{ x: x - 1, y }, // left
{ x: x + 1, y } // right
];
return adjacentCells.some(cell => {
const { x: adjX, y: adjY } = cell;
return (
adjX >= 0 && adjX < this.gridWidth &&
adjY >= 0 && adjY < this.gridHeight &&
this.grid[adjY][adjX].revealed
);
});
}
// Toggle automatic drilling
toggleDrilling() {
if (this.isDrilling) {
this.stopDrilling();
document.getElementById('drill-btn').textContent = 'Start Drilling';
} else {
this.startDrilling();
document.getElementById('drill-btn').textContent = 'Stop Drilling';
}
}
// Start automatic drilling
startDrilling() {
if (this.isDrilling) return;
this.isDrilling = true;
this.drillInterval = setInterval(() => {
this.autoDrill();
}, this.drillSpeed);
}
// Stop automatic drilling
stopDrilling() {
if (!this.isDrilling) return;
this.isDrilling = false;
clearInterval(this.drillInterval);
}
// Automatic drilling logic
autoDrill() {
// Find valid drill targets
const targets = [];
for (let y = 0; y < this.gridHeight; y++) {
for (let x = 0; x < this.gridWidth; x++) {
if (this.isValidDrillTarget(x, y)) {
targets.push({ x, y });
}
}
}
// If there are valid targets, drill at a random one
if (targets.length > 0) {
const target = targets[Math.floor(Math.random() * targets.length)];
this.drillAt(target.x, target.y);
} else {
// Generate a new layer when all cells are drilled
this.generateNewLayer();
}
}
// Generate a new layer when all cells are drilled
generateNewLayer() {
// Increase layer count
this.currentLayer++;
showNotification(`Drilling to layer ${this.currentLayer}!`, false);
// Increase max depth for the new layer
this.maxDepth += 100;
// Reset the grid but keep the top row for continuity
const topRow = this.grid[0].slice();
this.grid = this.initializeGrid();
this.grid[0] = topRow;
// Increase research points as reward for completing a layer
this.researchManager.researchPoints += 10 * this.currentLayer;
this.researchManager.researchRate += 0.1;
// Add some visual effects for layer transition
this.animateLayerTransition();
// Update display
this.render();
this.researchManager.updateResearchDisplay();
showNotification(`Research points +${10 * this.currentLayer}!`, false);
}
// Animate the transition to a new layer
animateLayerTransition() {
if (!this.visualEffectsEnabled) return;
// Flash effect on the canvas
this.canvas.classList.add('layer-transition');
setTimeout(() => {
this.canvas.classList.remove('layer-transition');
}, 1000);
// Create explosion particles across the canvas
for (let i = 0; i < 20; i++) {
const x = Math.random() * this.canvas.width;
const y = Math.random() * this.canvas.height;
const colors = ['#FFD700', '#FF5722', '#4CAF50', '#2196F3', '#9C27B0'];
const color = colors[Math.floor(Math.random() * colors.length)];
this.particleSystem.createParticles(x, y, color, 15);
}
// Add screen shake with more intensity
this.addScreenShake(10, 500);
// Play sound effect if enabled
if (this.soundEnabled) {
this.playSound('layer-transition');
}
// Add floating text animation
this.addFloatingText(`Layer ${this.currentLayer}!`, this.canvas.width / 2, this.canvas.height / 2, '#FFD700', 36);
}
// Start animation loop
startAnimationLoop() {
const animate = () => {
this.render();
requestAnimationFrame(animate);
};
requestAnimationFrame(animate);
}
// Drill at a specific location
drillAt(x, y) {
// Check if we have enough energy
if (!this.resourceManager.useEnergy(1, true)) {
return;
}
// Calculate depth based on y position and current layer
const depth = Math.floor((y / this.gridHeight) * this.maxDepth) + ((this.currentLayer - 1) * 100);
// Apply lucky chance from upgrades
let luckyBonus = 0;
if (this.luckyChance && Math.random() < this.luckyChance) {
luckyBonus = 0.2; // 20% better chance for rare resources
if (this.visualEffectsEnabled) {
this.addFloatingText("Lucky! 🍀",
x * this.gridSize + this.gridSize / 2,
y * this.gridSize - 10,
'#4CAF50',
16
);
}
}
// Get a random resource based on depth with lucky bonus
const resourceType = this.resourceManager.getRandomResource(depth, luckyBonus);
// Update the grid
this.grid[y][x] = {
type: resourceType,
revealed: true
};
// Check for double resources from upgrade
let resourceAmount = 1;
if (this.doubleChance && Math.random() < this.doubleChance) {
resourceAmount = 2;
if (this.visualEffectsEnabled) {
this.addFloatingText("Double! ×2",
x * this.gridSize + this.gridSize / 2,
y * this.gridSize - 10,
'#FFC107',
16
);
}
}
// Add the resource to inventory
this.resourceManager.addResource(resourceType, resourceAmount);
// Update the current depth if this is deeper
if (depth > this.currentDepth) {
this.currentDepth = depth;
}
// Check for treasure (special bonus) from treasure hunter upgrade
if (this.treasureChance && Math.random() < this.treasureChance) {
this.findTreasure(x, y);
}
// Add visual effects if enabled
if (this.visualEffectsEnabled) {
// Rainbow effect from upgrade
let particleColor = RESOURCES[resourceType].color;
if (this.rainbowEffect) {
const rainbow = ['#FF0000', '#FF7F00', '#FFFF00', '#00FF00', '#0000FF', '#4B0082', '#9400D3'];
particleColor = rainbow[Math.floor(Math.random() * rainbow.length)];
}
this.particleSystem.createParticles(
x * this.gridSize + this.gridSize / 2,
y * this.gridSize + this.gridSize / 2,
particleColor
);
// Add screen shake effect
this.addScreenShake();
// Add floating text showing resource value
const value = RESOURCES[resourceType].value * resourceAmount;
this.addFloatingText(
`+$${value}`,
x * this.gridSize + this.gridSize / 2,
y * this.gridSize - 10,
value >= 100 ? '#FFD700' : value >= 50 ? '#FFFFFF' : '#AAAAAA',
value >= 100 ? 16 : 12
);
}
// Play sound if enabled
if (this.soundEnabled) {
// Different sounds based on resource value
if (RESOURCES[resourceType].value >= 100) {
this.playSound('rare');
} else if (RESOURCES[resourceType].value >= 20) {
this.playSound('uncommon');
} else {
this.playSound('drill');
}
}
// Add research points based on resource value (1% of value)
this.researchManager.researchPoints += RESOURCES[resourceType].value * resourceAmount * 0.01;
// Check for auto-sell if storage is full and upgrade is purchased
if (this.autoSell && this.resourceManager.storage >= this.resourceManager.maxStorage * 0.9) {
this.resourceManager.sellResources();
}
// Check if storage is full and update upgrade buttons
if (this.resourceManager.storage >= this.resourceManager.maxStorage) {
// Update upgrade buttons in case user wants to upgrade storage
this.upgradeManager.updateUpgradesDisplay();
}
// Render the updated grid
this.render();
}
// Find a treasure (from treasure hunter upgrade)
findTreasure(x, y) {
// Random treasure value between 100-1000
const treasureValue = Math.floor(Math.random() * 900) + 100;
// Add money directly
this.resourceManager.money += treasureValue;
this.resourceManager.totalMoneyEarned += treasureValue; // Add to total money earned
// Visual and sound effects
if (this.visualEffectsEnabled) {
// Create special particles
this.particleSystem.createStarParticles(
x * this.gridSize + this.gridSize / 2,
y * this.gridSize + this.gridSize / 2,
20
);
// Add floating text
this.addFloatingText(
`TREASURE! +$${treasureValue}`,
x * this.gridSize + this.gridSize / 2,
y * this.gridSize - 20,
'#FFD700',
18
);
}
if (this.soundEnabled) {
this.playSound('treasure');
}
showNotification(`Found a treasure worth $${treasureValue}!`);
// Update display
this.resourceManager.updateDisplay();
// Update upgrade buttons after finding treasure
this.upgradeManager.updateUpgradesDisplay();
}
// Add screen shake effect
addScreenShake(intensity = 3, duration = 200) {
if (!this.visualEffectsEnabled) return;
const originalTransform = this.canvas.style.transform;
// Create shake animation
const startTime = Date.now();
const shake = () => {
const elapsed = Date.now() - startTime;
if (elapsed < duration) {
const xShake = Math.random() * intensity - intensity/2;
const yShake = Math.random() * intensity - intensity/2;
this.canvas.style.transform = `translate(${xShake}px, ${yShake}px)`;
requestAnimationFrame(shake);
} else {
this.canvas.style.transform = originalTransform;
}
};
requestAnimationFrame(shake);
}
// Add floating text animation
addFloatingText(text, x, y, color = '#ffffff', size = 20) {
if (!this.visualEffectsEnabled) return;
const floatingText = {
text,
x,
y,
color,
size,
opacity: 1,
life: 60 // frames
};
this.floatingTexts.push(floatingText);
}
// Play sound effects
playSound(type) {
// Simple sound implementation - can be expanded with actual audio files
const sounds = {
'drill': { frequency: 300, duration: 100 },
'uncommon': { frequency: 400, duration: 150 },
'rare': { frequency: 600, duration: 300, type: 'sine' },
'sell': { frequency: 500, duration: 200 },
'jackpot': { frequency: [600, 700, 800], duration: 500, type: 'sine' },
'upgrade': { frequency: 800, duration: 150 },
'layer-transition': { frequency: 200, duration: 500, type: 'sawtooth' },
'research-complete': { frequency: 700, duration: 400, type: 'sine' },
'treasure': { frequency: [400, 600, 800], duration: 600, type: 'sine' },
'restart': { frequency: [200, 300, 400, 500], duration: 800, type: 'sine' }
};
if (sounds[type] && window.AudioContext) {
try {
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
// For chord sounds (multiple frequencies)
if (Array.isArray(sounds[type].frequency)) {
sounds[type].frequency.forEach((freq, index) => {
const oscillator = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
oscillator.type = sounds[type].type || 'square';
oscillator.frequency.value = freq;
oscillator.connect(gainNode);
gainNode.connect(audioCtx.destination);
gainNode.gain.value = 0.05; // Lower volume for chords
oscillator.start();
// Create a fade out effect
gainNode.gain.exponentialRampToValueAtTime(
0.001,
audioCtx.currentTime + sounds[type].duration / 1000
);
setTimeout(() => {
oscillator.stop();
}, sounds[type].duration);
});
} else {
// Single frequency sounds
const oscillator = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
oscillator.type = sounds[type].type || 'square';
oscillator.frequency.value = sounds[type].frequency;
oscillator.connect(gainNode);
gainNode.connect(audioCtx.destination);
gainNode.gain.value = 0.1;
oscillator.start();
// Create a fade out effect
gainNode.gain.exponentialRampToValueAtTime(
0.001,
audioCtx.currentTime + sounds[type].duration / 1000
);
setTimeout(() => {
oscillator.stop();
}, sounds[type].duration);
}
} catch (e) {
console.log('Sound playback error:', e);
}
}
}
// Start energy recharge timer
startEnergyRecharge() {
// Energy recharge timer (gain energy every 1 second)
setInterval(() => {
this.resourceManager.rechargeEnergy(this.energyRechargeRate);
}, 1000);
// Energy consumption timer when drilling (use energy every 1.5 seconds)
setInterval(() => {
if (this.isDrilling) {
// Only consume energy if drilling is active
this.resourceManager.useEnergy(1, false); // false means don't stop drilling if energy is low
}
}, 1500);
}
// Save game to local storage
saveGame() {
const gameData = {
// Game state
drillPower: this.drillPower,
drillSpeed: this.drillSpeed,
energyRechargeRate: this.energyRechargeRate,
maxDepth: this.maxDepth,
currentDepth: this.currentDepth,
currentLayer: this.currentLayer,
// Resource manager state
money: this.resourceManager.money,
totalMoneyEarned: this.resourceManager.totalMoneyEarned,
energy: this.resourceManager.energy,
maxEnergy: this.resourceManager.maxEnergy,
storage: this.resourceManager.storage,
maxStorage: this.resourceManager.maxStorage,
inventory: this.resourceManager.inventory,
// Upgrade levels
upgradeLevels: this.upgradeManager.upgradeLevels,
// Research progress
researchProgress: this.researchManager.researchProgress,
activeResearch: this.researchManager.activeResearch,
completedResearch: this.researchManager.completedResearch,
// Grid state - simplified to save space
grid: this.grid.map(row =>
row.map(cell => ({
t: cell.type,
r: cell.revealed
}))
)
};
localStorage.setItem('miningTycoonSave', JSON.stringify(gameData));
}
// Load game from local storage
loadGame() {
const savedGame = localStorage.getItem('miningTycoonSave');
if (!savedGame) {
return false;
}
try {
const gameData = JSON.parse(savedGame);
// Load game state
this.drillPower = gameData.drillPower || this.drillPower;
this.drillSpeed = gameData.drillSpeed || this.drillSpeed;
this.energyRechargeRate = gameData.energyRechargeRate || this.energyRechargeRate;
this.maxDepth = gameData.maxDepth || this.maxDepth;
this.currentDepth = gameData.currentDepth || this.currentDepth;
this.currentLayer = gameData.currentLayer || this.currentLayer;
// Load resource manager state
this.resourceManager.money = gameData.money || this.resourceManager.money;
this.resourceManager.totalMoneyEarned = gameData.totalMoneyEarned || this.resourceManager.totalMoneyEarned;
this.resourceManager.energy = gameData.energy || this.resourceManager.energy;
this.resourceManager.maxEnergy = gameData.maxEnergy || this.resourceManager.maxEnergy;
this.resourceManager.storage = gameData.storage || this.resourceManager.storage;
this.resourceManager.maxStorage = gameData.maxStorage || this.resourceManager.maxStorage;
if (gameData.inventory) {
this.resourceManager.inventory = gameData.inventory;
}
// Load upgrade levels
if (gameData.upgradeLevels) {
this.upgradeManager.upgradeLevels = gameData.upgradeLevels;
this.upgradeManager.applyUpgradeEffects();
}
// Load research progress
if (gameData.researchProgress) {
this.researchManager.researchProgress = gameData.researchProgress;
}
if (gameData.activeResearch) {
this.researchManager.activeResearch = gameData.activeResearch;
}
if (gameData.completedResearch) {
this.researchManager.completedResearch = gameData.completedResearch;
this.researchManager.applyResearchEffects();
}
// Load grid state
if (gameData.grid) {
this.grid = gameData.grid.map(row =>
row.map(cell => ({
type: cell.t,
revealed: cell.r
}))
);
}
showNotification("Game loaded successfully!");
return true;
} catch (e) {
console.error("Error loading saved game:", e);
showNotification("Error loading saved game!", true);
return false;
}
}
// Start auto-save timer
startAutoSave() {
setInterval(() => {
this.saveGame();
console.log("Game auto-saved");
}, 60000); // Auto-save every minute
}
// Render the game
render() {
// Clear the canvas
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
// Draw the grid
for (let y = 0; y < this.gridHeight; y++) {
for (let x = 0; x < this.gridWidth; x++) {
const cell = this.grid[y][x];
if (cell.revealed) {
// Draw revealed cell with resource color
this.ctx.fillStyle = RESOURCES[cell.type].color;
// Add glow effect for valuable resources
if (RESOURCES[cell.type].value >= 100 && this.visualEffectsEnabled) {
this.ctx.shadowColor = RESOURCES[cell.type].color;
this.ctx.shadowBlur = 5 + Math.sin(Date.now() / 200) * 3;
} else {
this.ctx.shadowBlur = 0;
}
} else {
// Draw unrevealed cell
this.ctx.fillStyle = '#e0e0e0';
this.ctx.shadowBlur = 0;
}
// Draw cell with a small gap between cells
this.ctx.fillRect(
x * this.gridSize + 1,
y * this.gridSize + 1,
this.gridSize - 2,
this.gridSize - 2
);
// Reset shadow for text
this.ctx.shadowBlur = 0;
// If the cell is revealed and has a resource, draw the resource icon
if (cell.revealed) {
this.ctx.fillStyle = '#fff';
this.ctx.font = `${this.gridSize * 0.7}px Arial`;
this.ctx.textAlign = 'center';
this.ctx.textBaseline = 'middle';
this.ctx.fillText(
RESOURCES[cell.type].icon,
x * this.gridSize + this.gridSize / 2,
y * this.gridSize + this.gridSize / 2
);
}
}
}
// Update depth indicator in the DOM instead of drawing on canvas
const depthValueElement = document.querySelector('.depth-value');
const layerValueElement = document.querySelector('.layer-value');
if (depthValueElement) {
depthValueElement.textContent = `Depth: ${this.currentDepth}m`;
}
if (layerValueElement) {
layerValueElement.textContent = `Layer: ${this.currentLayer}`;
}
// Draw particles if enabled
if (this.visualEffectsEnabled) {
this.particleSystem.update();
this.particleSystem.draw(this.ctx);
// Update and draw floating texts
this.updateFloatingTexts();
this.drawFloatingTexts();
}
}
// Update floating texts
updateFloatingTexts() {
for (let i = this.floatingTexts.length - 1; i >= 0; i--) {
const text = this.floatingTexts[i];
text.y -= 1; // Move up
text.life -= 1; // Decrease life
text.opacity = text.life / 60; // Fade out
if (text.life <= 0) {
this.floatingTexts.splice(i, 1); // Remove dead texts
}
}
}
// Draw floating texts
drawFloatingTexts() {
this.floatingTexts.forEach(text => {
this.ctx.font = `${text.size}px Arial`;
this.ctx.fillStyle = text.color;
this.ctx.globalAlpha = text.opacity;
this.ctx.textAlign = 'center';
this.ctx.fillText(text.text, text.x, text.y);
});
this.ctx.globalAlpha = 1;
}
}
// Particle system for visual effects
class ParticleSystem {
constructor() {
this.particles = [];
}
createParticles(x, y, color, count = 10) {
for (let i = 0; i < count; i++) {
this.particles.push({
x,
y,
vx: (Math.random() - 0.5) * 3,
vy: (Math.random() - 0.5) * 3,
size: Math.random() * 3 + 1,
color,
life: 30,
type: 'normal'
});
}
}
createMoneyParticles(x, y, count = 15) {
const symbols = ['$', '💰', '💎', '🪙'];
for (let i = 0; i < count; i++) {
this.particles.push({
x,
y,
vx: (Math.random() - 0.5) * 5,
vy: -Math.random() * 5 - 2, // Always move up initially
size: Math.random() * 5 + 15,
color: '#FFD700',
life: 60,
type: 'money',
symbol: symbols[Math.floor(Math.random() * symbols.length)],
rotation: Math.random() * 360,
rotationSpeed: (Math.random() - 0.5) * 10
});
}
}
createStarParticles(x, y, count = 20) {
const colors = ['#FFD700', '#FFFFFF', '#FFC107', '#FFEB3B'];
for (let i = 0; i < count; i++) {
const angle = Math.random() * Math.PI * 2;
const speed = Math.random() * 3 + 2;
this.particles.push({
x,
y,
vx: Math.cos(angle) * speed,
vy: Math.sin(angle) * speed,
size: Math.random() * 4 + 2,
color: colors[Math.floor(Math.random() * colors.length)],
life: 40,
type: 'star'
});
}
}
update() {
this.particles = this.particles.filter(p => p.life > 0);
this.particles.forEach(p => {
p.x += p.vx;
p.y += p.vy;
p.life--;
// Add gravity for money particles
if (p.type === 'money') {
p.vy += 0.1;
p.rotation += p.rotationSpeed;
}
// Make stars twinkle
if (p.type === 'star' && p.life % 5 === 0) {
p.size = Math.random() * 4 + 2;
}
});
}
draw(ctx) {
this.particles.forEach(p => {
ctx.globalAlpha = p.life / (p.type === 'money' ? 60 : 30);
if (p.type === 'normal' || p.type === 'star') {
ctx.fillStyle = p.color;
ctx.beginPath();
if (p.type === 'star' && Math.random() > 0.5) {
// Draw a star shape
this.drawStar(ctx, p.x, p.y, 5, p.size, p.size / 2);
} else {
// Draw a circle
ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
}
ctx.fill();
} else if (p.type === 'money') {
// Draw money symbols
ctx.save();
ctx.translate(p.x, p.y);
ctx.rotate(p.rotation * Math.PI / 180);
ctx.fillStyle = p.color;
ctx.font = `${p.size}px Arial`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(p.symbol, 0, 0);
ctx.restore();
}
});
ctx.globalAlpha = 1;
}
drawStar(ctx, cx, cy, spikes, outerRadius, innerRadius) {
let rot = Math.PI / 2 * 3;
let x = cx;
let y = cy;
let step = Math.PI / spikes;
ctx.beginPath();
ctx.moveTo(cx, cy - outerRadius);
for (let i = 0; i < spikes; i++) {
x = cx + Math.cos(rot) * outerRadius;
y = cy + Math.sin(rot) * outerRadius;
ctx.lineTo(x, y);