-
Notifications
You must be signed in to change notification settings - Fork 1
/
carrot_clicker.js
2144 lines (1890 loc) · 77.9 KB
/
carrot_clicker.js
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
/*
The Base of the Game is the Objects used to easily store data.
The core Object is the player. The player object Stores Global Variables not Atributed to another character.
The Character Class Object stores information on each Ingame Character. Currently the active Characters are Boomer_Bill, Belle_Boomerette, and Gregory
*/
// Error message if game hasnt loaded in 1 second
let loadCheck;
setTimeout(() => {
if(!loadCheck) {
toast('Game crash', 'The game has taken more than 1 second to load. It\'s likely that an error has occured, causing either a partial or full game crash. Feel free to contact us if you see this.', 'red', true, false, false, false, () => openDialog(...dialog.clearsave),
'Delete Save Data',
);
}
}, 1000);
let startTime = Date.now();
// Date
// let epoch = get("https://worldtimeapi.org/api/timezone/America/Chicago").unixtime;
// console.log(epoch);
// console.log(Math.round(Date.now()/1000));
/*------------Page Setup---------------*/
//#region
// Overlays
const mcContainer = dom('mouse_confetti');
const elInfoDropdown = dom('info_dropdown');
// Game
const mainCarrot = dom("main_carrot");
const elMainPrestigePotential = dom("main_prestige_potential");
const elPrestigePotential = dom('prestige_potential');
const Basic_Info = dom("Basic_Info");
const elCarrotCount = dom("Carrot_Count");
const elClickSpeed = dom("click_speed");
const elCPC = dom("cpc");
const elCPS = dom("cps");
const elCashCount = dom("cash_count");
const elGoldenCarrotCount = dom("golden_carrot_count");
const elTips = dom("Tip");
// Characters and Hoes
const elCharacterUpCost = {
bill: dom("UpBillCost"),
belle: dom("UpBelleCost"),
greg: dom("UpGregCost")
};
const elCharacterLevel = {
bill: dom("Bill_lvl"),
belle: dom("Belle_lvl"),
greg: dom("Greg_lvl")
};
const elToolPrices = document.querySelectorAll('.tool_price');
const elMainProgressContainer = dom('main_progress_container');
const elMainProgressBar = dom('main_progress_bar');
const elGregProgress = dom("Greg_Progress");
const elCharles = {
debug: dom("charles_debug"),
prices: {
improveWorkingConditions: dom("ImproveWorkingConditions"),
betterHoes: dom("BetterHoes"),
decreaseWages: dom("DecreaseWages"),
},
shop: {
improveWorkingConditions: dom("ImproveWorkingConditions_button"),
betterHoes: dom("BetterHoes_button"),
decreaseWages: dom("DecreaseWages_button"),
}
}
const tomeEffect = {
iwc: dom('iwc_effect'),
bh: dom('bh_effect'),
dww: dom('dww_effect'),
}
const tomeCount = {
iwc: dom('iwc_count'),
bh: dom('bh_count'),
dww: dom('dww_count'),
}
// Settings elements
const elFunTipsSlider = dom("FunTipsSlider");
const elFunTipsSlider_label = dom("FunTipsSliderLabel");
const elEnableKeybinds = dom('enable_keybinds');
const elEnableSounds = dom('enableSounds');
const elEnableMusic = dom('enableMusic');
const elEnableCarrotSounds = dom('enableCarrotSounds');
const elVolumeMaster = dom('volume_master');
const elVolumeMaster_label = dom('volume_master_percent');
const volumeMasterDropdown = dom('volume_master_dropdown');
const vmImage = dom('volume_master_img');
const vmdImage = dom('volume_master_dropdown_img');
const elEnableMainProgress = dom('enableMainProgress');
//#endregion
/*-------------Local Storage and Characters-------------*/
//#region
// Creates Characters
//creates a player class
class Player{
constructor(data_version,carrots,cpc,cps,equippedHoes,cash,
clickSpeedRecord,fallingConsecRecord,trinket_completion,pages,golden_carrots,
prestige_potential,prestige_potential_cap,prestige_available,
prestige,characters,achievements, internal,themes,cosmetics,
new_theme,new_cosmetic,flags){
this.data_version=data_version;
this.carrots=carrots;
this.cpc=cpc;
this.cps=cps;
this.equippedHoes=equippedHoes;
this.cash=cash;
this.clickSpeedRecord=clickSpeedRecord;
this.fallingConsecRecord=fallingConsecRecord;
this.trinket_completion=trinket_completion;
this.pages=pages;
this.golden_carrots=golden_carrots;
this.prestige_potential=prestige_potential;
this.prestige_potential_cap=prestige_potential_cap;
this.prestige_available=prestige_available;
this.prestige=prestige;
this.characters=characters;
this.achievements=achievements;
this.internal=internal;
this.themes=themes;
this.cosmetics=cosmetics;
this.new_theme=new_theme;
this.new_cosmetic=new_cosmetic;
this.flags=flags;
}
}
class statsTracker{
constructor(carrots,click_carrots,idle_carrots,bonus_carrots,cash,falling_carrots_grabbed,golden_carrots,prestige_count,clicks,hoes,tomes_bought,trinkets_complete,boosts_used) {
this.carrots=carrots;
this.click_carrots=click_carrots;
this.idle_carrots= idle_carrots;
this.bonus_carrots=bonus_carrots;
this.cash=cash;
this.falling_carrots_grabbed=falling_carrots_grabbed;
this.golden_carrots=golden_carrots;
this.prestige_count=prestige_count;
this.clicks=clicks;
this.hoes=hoes;
this.tomes_bought=tomes_bought;
this.trinkets_complete=trinkets_complete;
this.boosts_used=boosts_used;
}
}
/** Creates Character objects */
class Character{
/** Characters in the Game
* @param {String} nickname Shortened name
* @param {String} img the Image of the Character
*/
constructor(nickname, img) {
this.nickname=nickname;
this.img=img;
}
unlock(){
//possibly a method to unlock the characters
}
lock(){
//possibly a method to lock the characters
}
}
class Farmer extends Character{
/**
* Produces Carrots
* @param {String} nickname Shortened Name
* @param {String} img The image of the character
* @param {Number} lvl starting level
* @param {Number} lvlupPrice the starting level price
* @param {Array} scaling the way the level up prices scale
* @param {Array} Hoes Blank hoe array
*/
constructor(nickname,img,lvl,lvlupPrice,scaling,Hoes){
super(nickname,img);
this.lvl=lvl;
this.lvlupPrice=lvlupPrice;
this.scaling=scaling;
this.Hoes=Hoes;
}
}
class Blacksmith extends Character{
/**
* Forges Tools
* @param {String} nickname Shortened Name
* @param {String} img The image of the character
* @param {Number} lvl starting level
* @param {Number} lvlupPrice the level up prices
* @param {Array} scaling the way the level up prices scale
* @param {Array} Hoes Blank hoe array
* @param {Array} HoePrices Prices of Hoes
*/
constructor(nickname,img,lvl,lvlupPrice,scaling,Hoes,HoePrices,crafting){
super(nickname,img);
this.lvl=lvl;
this.lvlupPrice=lvlupPrice;
this.scaling=scaling;
this.Hoes=Hoes;
this.HoePrices=HoePrices;
this.crafting=crafting;
}
}
class Scholar extends Character{
constructor(nickname, img){
super(nickname,img);
}
}
// Default Values Stored in a Player Object
const playerPrestigeTemplate = {
carrots: 0,
click_carrots: 0,
idle_carrots: 0,
bonus_carrots: 0,
// cash: 0,
falling_carrots_grabbed: 0,
// golden_carrots: 0,
// prestige_count: 0,
clicks: 0,
hoes: {
crafted: [0, 0, 0, 0, 0, 0],
craftedTotal: 0,
},
boosts_used: 0,
};
const default_player = new Player(
18,//data_version; needs to be incremented by 1 any time any game object is changed
0, //carrots
1, //cpc; Carrots per click
0, //cps; Carrots per Second
0, //equippedHoes
0, //cash
0, //clickSpeedRecord
0, //fallingConsecRecord
'0/0', //trinket_completion,
0, //pages; tome pages that increase prestige potential
0, //golden_carrots
0, //prestige_potential; golden carrots recived upon prestige
0, //prestige_potential_cap
false, //prestige_available; wether you can prestige
clone(playerPrestigeTemplate), //prestige
// Unlocked characters
{bill:true}, //characters; unlocked
{}, //achievements
0, //internal
// Unlockables
['theme_dark','theme_light',"theme_oled"], // themes
{
'bundle': ['default'],
'farmable': ['default'],
'bill': ['default'],
'belle': ['default'],
'greg': ['default'],
'charles': ['default'],
'carl': ['default'],
'jared': ['default'],
'tools': ['default'],
}, // cosmetics
false, //new_theme
false, //new_cosmetic
{} //flags
)
default_player.lifetime = new statsTracker(0,0,0,0,0,0,0,0,0,{crafted: [0, 0, 0, 0, 0, 0],craftedTotal: 0},0,0,0);
/* --- Tools --- */
/** Tool durability values (hardmode) */
// const toolDurability = [140, 800, 3200, 12000, 24000, 64000];
/** Tool price scaling */
const toolScaling = [
false, // False means fall back to default (0.02)
0.024,
0.021,
0.019,
0.018,
0.03,
];
/** Tool craft speed */
const tool_craft_speed = [
0.06,
0.03,
0.01,
0.009,
0.007,
0.005,
];
// Character Defaults
const Default_Boomer_Bill = new Farmer(
"bill", './assets/characters/Bill.png',
1, 100,
[ // Price scaling
{ min: 1, modifier: 0.11 },
{ min: 75, modifier: 0.13 },
{ min: 100, modifier: 0.09 },
{ min: 300, modifier: 0.08 },
{ min: 500, modifier: 0.065 },
],
[0,0,0,0,0,0],
);
const Default_Belle_Boomerette = new Farmer(
"belle", './assets/characters/Belle.png',
0, 200,
[ // Price scaling
{ min: 0, modifier: 0.058 },
{ min: 100, modifier: 0.11 },
{ min: 125, modifier: 0.07 },
{ min: 200, modifier: 0.08 },
],
[0,0,0,0,0,0],
);
const Default_Gregory = new Blacksmith(
"greg", './assets/characters/Greg.png',
0, 5000,
[ // Price scaling
{ min: 0, modifier: 0.17706 },
{ min: 25, modifier: 0.1874 },
{ min: 50, modifier: 0.227 },
{ min: 75, modifier: 0.284 },
{ min: 100, modifier: 0.409 },
{ min: 125, modifier: 0.25 },
],
[0,0,0,0,0,0],
[15000,750000,55000000,9000000000,5000000000000,25000000000000000],
false,
);
class Tome {
constructor(value=0,price=1,max=25000){
this.value=value;
this.price=price;
this.max=max;
}
priceQuery(amount=1, sendNewPrice=false){
//handling cases where the tomes can not be bought
if(typeof(amount)!=="number") return console.error("amount needs to be a number");
if(this.value+amount>=this.max && sendNewPrice==false){console.error(); return "∞"}
//useful variables
let valueDummy = this.value;
let target = valueDummy+amount;
let sum = this.price;
let newPrice = this.price;
let scaling = 1.001;
//multibuy for loop
for(let i=0;i<amount+10;i++){
//scaling
if(valueDummy>99) scaling = 1.01;
else if(valueDummy>375) scaling = 1.003;
else if(valueDummy>1000)scaling = 1.00101;
//set new price
newPrice=Math.ceil(newPrice*scaling);
//check if target is met;
if(target===valueDummy+1) break;
//numbers go up
sum+=newPrice;
valueDummy+=1;
}
if(sendNewPrice) return newPrice;
else return sum;
}
add(amount=1){
// Handling cases where the tomes can not be bought
if(typeof(amount)!=="number") return console.error("amount needs to be a number");
if(this.value+amount>this.max) return toast("Can not purchase", `There are only ${this.max} tomes containing knowledge on this subejct`, '', false, true);
// Return if can't afford
let price = this.priceQuery(amount)
if(player.golden_carrots < price) return;
// Updates values
player.golden_carrots -= price;
this.value += amount;
this.price = this.priceQuery(amount,true);
player.lifetime.tomes_bought += amount; // Statistics
// Recalculate CPC/CPS/level up prices
recalculateCarrotsPer();
characterPrices();
characterButtons();
// Update page
updateCharlesShop();
updateCPC();
updateGC();
mouseConfetti([3, 8], ccWhite);
}
}
const Default_Charles = new Scholar("charles",'./assets/characters/Charles.png',)
Default_Charles.improveWorkingConditions=new Tome (0,1,22025);
Default_Charles.decreaseWages=new Tome(0,1,22025);
Default_Charles.betterHoes=new Tome(0,1,22025);
class carlListing {
constructor(price=1, currency='cash', available=false, bought=false) {
this.price = price;
this.currency = currency;
this.available = available;
this.bought = bought;
}
}
const Default_Carl = {
nickname: "carl",
img: './assets/characters/Carl.png',
// Shop
shop: {
theme: {
'theme_classic': new carlListing(16, undefined, true),
'theme_bw': new carlListing(6),
'theme_terminal': new carlListing(12),
'theme_chatapp': new carlListing(5),
'theme_camo': new carlListing(3),
'theme_original': new carlListing(54),
'theme_red': new carlListing(5),
'theme_green': new carlListing(5),
'theme_blue': new carlListing(5),
'theme_grey': new carlListing(12, undefined, true),
// 'theme_custom': new carlListing(80),
},
cosmetic: {
// Bundle
'bundle/cookie': new carlListing(16),
'bundle/xmas': new carlListing(25),
'bundle/plumber': new carlListing(16),
'bundle/developer_art': new carlListing(4),
// Farmable
'farmable/pixel_carrot': new carlListing(8),
'farmable/pixel_golden_carrot': new carlListing(10),
'farmable/blockgame_potato': new carlListing(5),
'farmable/pineapple': new carlListing(20),
'farmable/ascii_color': new carlListing(2),
'farmable/ascii': new carlListing(2),
// Carrot variants
'farmable/alien_carrot': new carlListing(3),
'farmable/demon_carrot': new carlListing(3),
'farmable/ghost_carrot': new carlListing(3),
'farmable/rainbow_carrot': new carlListing(3),
// Bill
'bill/biker_bill': new carlListing(5),
'bill/fancy_bill': new carlListing(40),
'bill/dollar_bill': new carlListing(10),
'bill/business_bill': new carlListing(5),
'bill/gold_fancy_bill': new carlListing(100),
// Greg
'greg/safety_greg': new carlListing(12),
// Charles
'charles/special_charles': new carlListing(3),
// Carl
'carl/joker_carl': new carlListing(8),
// Tools
'tools/fertilizer': new carlListing(5),
}
},
order: [],
}
const Default_Jared = {
// Info
name: "Jared",
nickname: "Jared",
img: './assets/characters/Jared.png',
// Shop player data
data: {
'mp3_player': {
available: true,
level: 0,
value: false,
},
'clickrate': {
available: true,
level: 0,
value: 2,
},
'level_up_discount': {
available: true,
level: 0,
value: 100,
},
'belle_bonus': {
available: true,
level: 0,
value: 0,
},
// 'greg_slots': { // scrapped because of how craft speed works- may add later but probably wouldnt be any good
// available: true,
// level: 0,
// value: 1,
// },
'tool_slots': {
available: true,
level: 0,
value: 0,
},
'greg_speed': {
available: true,
level: 0,
value: 1,
},
'greg_min_start': {
available: true,
level: 0,
value: 100,
},
'falling_bonus': {
available: true,
level: 0,
value: 0,
},
'page_bonus': {
available: true,
level: 0,
value: 1,
},
'magic_keyboard': {
available: true,
level: 0,
value: false,
},
// 'paperclip': {
// available: true,
// level: 0,
// value: 0,
// },
// 'fake_trophy': {
// available: false,
// level: 0,
// value: false,
// },
},
}
/** Hire Jared */
function hireJared() {
if(player.characters['jared'] !== 'ready') {
if(player.characters['jared']) populateJared();
else return; // Not available for hire or already hired
}
const hireCost = 10000000;
if(player.carrots < hireCost) return toast(...toasts.error_jared_hire_cost); // Too expensive
player.carrots -= hireCost;
player.characters['jared'] = true;
populateJared();
toast(...toasts.notice_trinkets);
}
// Used when determining how many characters there are
const chars = [ 'bill', 'belle', 'greg', 'charles', 'carl', 'jared' ];
const defaultChar = {
'bill': Default_Boomer_Bill,
'belle': Default_Belle_Boomerette,
'greg': Default_Gregory,
'charles': Default_Charles,
'carl': Default_Carl,
'jared': Default_Jared,
}
/** Return number of available shop items
* @returns Number
*/
function carlItemsAvailable() {
let c = 0;
for(let [key, value] of Object.entries(Default_Carl.shop.theme)) if(Carl.shop.theme[key].available) c++; // Themes
for(let [key, value] of Object.entries(Default_Carl.shop.cosmetic)) if(Carl.shop.cosmetic[key].available) c++; // Cosmetics
return c;
}
/** Returns true if available or bought
* @param {string} type
* @param {number} item
* @returns Boolean
*/
function carlShopQuery(type, item) {
try { return Carl.shop?.[type]?.[item].available || Carl.shop?.[type]?.[item].bought; }
catch (error) { console.warn('carlShopQuery: invalid query- item or type not found'); }
}
// Use savedata if available, otherwise use default
var player = localStorage.getObject("player") || clone(default_player);
var Boomer_Bill = localStorage.getObject("Bill") || clone(Default_Boomer_Bill);
var Belle_Boomerette = localStorage.getObject("Belle") || clone(Default_Belle_Boomerette);
var Gregory = localStorage.getObject("Greg") || clone(Default_Gregory);
var saved_Charles = localStorage.getObject("Charles") || clone(Default_Charles);
var Carl = localStorage.getObject("Carl") || clone(Default_Carl);
var Jared = localStorage.getObject("Jared") || clone(Default_Jared);
const levelable = [Boomer_Bill, Belle_Boomerette, Gregory];
// Update Charles
Charles=new Scholar(saved_Charles.nickname,saved_Charles.img);
Charles.improveWorkingConditions=new Tome (saved_Charles.improveWorkingConditions.value,saved_Charles.improveWorkingConditions.price,22025);
Charles.decreaseWages=new Tome(saved_Charles.decreaseWages.value,saved_Charles.decreaseWages.price,22025);
Charles.betterHoes=new Tome(saved_Charles.betterHoes.value,saved_Charles.betterHoes.price,22025);
// Objects to save in localstorage
const saveList = {
"player": player,
"Bill": Boomer_Bill,
"Belle": Belle_Boomerette,
"Greg": Gregory,
"Charles": Charles,
"Carl": Carl,
"Jared": Jared,
}
const saveListKeys = Object.keys(saveList);
var preventSaveGame = false;
/** Saves objects data to Local Storage */
function saveGame() {
setTimePlayed(true);
if(preventSaveGame || player.flags['cookies_accepted'] !== true) return;
// player.time_last_saved = Math.round(Date.now() / 1000);
player.time_last_saved = get("https://worldtimeapi.org/api/timezone/America/Chicago").unixtime;
for(let i = 0; i < saveListKeys.length; i++) {
let key = saveListKeys[i];
let obj = saveList[key];
localStorage.setObject(key, obj);
}
}
function setTimePlayed(skippable) {
if(window?.blurred && skippable) return;
let now = Date.now();
player.time_played = (player.time_played??0) + ((now - startTime)/1000); // Calculate playtime
startTime = now;
}
// Autosave
var autosave =
setInterval(() => {
saveGame();
}, 5000);
// Save before unload (does not work for some browsers/devices)
window.addEventListener('beforeunload', () => { saveGame(); });
//#endregion
/*--------------Settings----------------*/
//#region
/** If sounds are turned off, grey out individual sound toggles */
function optionSoundsDisable(state) {
elEnableMusic.disabled = !state;
elEnableCarrotSounds.disabled = !state;
if(!state) stopMusic(); // Carrot sounds
}
/** Volume slider handler */
function volumeSliderHandler(event=false) {
let v = event ? event.srcElement.value : settings.master_volume * 100;
volumeMasterDropdown.value = v;
elVolumeMaster.value = v;
elVolumeMaster_label.value = v;
vmImage.src = vmdImage.src = v !== 0 && vmdImage.src !== './assets/icons/volume.svg' ? './assets/icons/volume.svg' : './assets/icons/mute.svg';
volume = v / 100;
if(music !== undefined) music.volume = volume;
settings.master_volume = volume;
saveSettings();
}
/** Fill out settings page options */
function fillSettingsPage() {
document.querySelectorAll('[data-option]').forEach(element => element.checked = settings?.[element.id]); // Checkboxes
document.querySelectorAll('[data-option-slider]').forEach(element => element.value = settings?.[element.dataset.optionSlider]); // Sliders
optionSoundsDisable(settings.enableSounds);
volumeSliderHandler();
eInnerText(elVolumeMaster_label, `${settings.master_volume * 100}%`);
volume = settings.master_volume;
// Update autosave variable
if(settings.autosave_interval !== default_settings.autosave_interval) {
clearInterval(autosave);
autosave = setInterval(() => { saveGame(); }, settings.autosave_interval * 1000);
}
optionSoundsDisable(settings.enableSounds);
}
/** Save settings object in localStorage */
function saveSettings() {
if(player.flags['cookies_accepted']) localStorage.setObject("settings", settings);
}
/** Reset settings to defaults */
function resetSettings() {
settings = clone(default_settings);
saveSettings();
fillSettingsPage();
}
// Default keybinds
const keybinds_default = {
// Gameplay
key_carrot: 'Spacebar',
key_multibuy: 'Shift',
key_bill_lvlup: '1',
key_belle_lvlup: '2',
key_greg_lvlup: '3',
// Tools
key_craft_0: '4',
key_craft_1: '5',
key_craft_2: '6',
key_craft_3: '7',
key_craft_4: '8',
key_craft_5: '9',
// modifier_equip: 'Shift',
// Settings
key_full_numbers: 'F',
// Interface
key_cleartoasts: 'X',
// Menus
key_tips_menu: 'H',
key_prestige: 'P',
key_inventory: 'E',
key_themes: 'Not set',
key_cosmetics: 'Not set',
// Tripane
key_pane_achievements: 'A',
key_pane_statistics: 'S',
key_pane_settings: 'D',
}
keybinds_default['keys'] = Object.keys(keybinds_default);
// Default settings object
const default_settings = {
notificationLength: 6, // number - Time in seconds
enable_keybinds: true, // boolean
autosave_interval: 5,
tutorial_messages: true, // boolean
carl_shop_toasts: true, // boolean
cosmetic_auto_equip: false, // boolean
master_volume: 0.8, // number - Between 0 and 1
enableSounds: true, // boolean
enableMusic: false, // boolean
enableCarrotSounds: false, // boolean
full_numbers: false, // boolean
enableMainProgress: true, // boolean
confetti_effects: true, // boolean
// UI
theme: 'theme_dark', // string
cosmetics: {
farmable: 'default',
bill: 'default',
belle: 'default',
greg: 'default',
charles: 'default',
carl: 'default',
jared: 'default',
tools: 'default',
},
openpanel: null, // string
show_nav: (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)), // boolean
cosmetics_grid: true, // boolean
achievements_grid: false, // boolean
compact_achievements: false,// boolean
fun_tip_percentage: 40, // number - between 0 and 100
keybinds: keybinds_default, // object
}
var settings;
// Settings object
if(localStorage.getObject("settings") !== null) {
// Save found
console.log('[Settings] SETTINGS localStorage object found!');
settings = localStorage.getObject('settings');
} else {
// Create from default
console.log('[Settings] No localStorage object found, creating...');
resetSettings();
}
// Clear localStorage
function clearSave() {
preventSaveGame = true;
ClearLocalStorage();
}
//#endregion
/* ----------------------Functions------------------------*/
//#region
// Multibuy
const multibuy = [1,10,100]; // Multibuy multipliers
var mbsel = 0; // Multibuy selection
/** Cycles multibuy amount */
function multibuySpin() {
mbsel = (mbsel+1) % multibuy.length;
// Update page
characterPrices();
characterButtons();
updateAllTools();
updateToolPrices();
updateCharlesShop();
eInnerText(dom("multibuy"), multibuy[mbsel] + "x");
// Tutorial message
if(player.flags['tutorial_multibuy'] !== true) {
toast(...toasts.tutorial_multibuy);
player.flags['tutorial_multibuy'] = true;
}
}
/** Clears localStorage
* @param {Boolean} disableReload
*/
function ClearLocalStorage(disableReload) {
console.log('Clearing local storage');
window.scrollTo(0, 0);
localStorage.clear();
if(disableReload) return;
location.reload();
}
/** Gives a random number between 0 and max
* @param {number} max
* @returns Random Number
*/
function r(max) { return Math.floor(Math.random() * max); }
/** Returns a copy of an object using JSON.parse(JSON.stringify(...))
* @param {*} obj
*/
function clone(obj) { return JSON.parse(JSON.stringify(obj)); }
/** Shorthand for adding/removing a CSS class to/from an element
* @param {node} element HTML element
* @param {string} classname CSS class name
* @param {boolean} state true = add, false = remove
*/
function style(element, classname, state) {
state ? element.classList.add(classname) : element.classList.remove(classname);
}
// Store click speed
var clickSpeed = 0;
var clickSpeedBest = 0;
var clickArray = [];
/** Earn carrots function
* @param {number} amount Amount of carrots to be earned
* @param {string} type Can be click, idle, or bonus. For statistics.
* @param {boolean} useMousePos If the number popup should appear at mouse position or not
*/
function earnCarrots(amount, type, useMousePos = false) {
player.carrots += amount; // Grant Carrots
// Statistics
player.prestige.carrots += amount;
player.lifetime.carrots += amount;
player.prestige[`${type}_carrots`] += amount;
player.lifetime[`${type}_carrots`] += amount;
// Update page
carrotCount();
characterButtons();
updateAllTools();
// Bonus
if(type === 'bonus') popupHandler(useMousePos, DisplayRounded(amount, 1), 'falling');
}
/** Earn currency
* @param {number} amount Amount of cash to be earned
* @param {string} type 'bonus' will use mouse position
*/
function earnCash(amount, type) {
popupHandler((type === 'bonus'), amount, 'cash');
player.cash += amount;
player.lifetime.cash += amount;
cashCount(true);
}
// Carrot event listeners
var hold = {
active: false,
delay: undefined,
clock: undefined,
}
mainCarrot.addEventListener('mousedown', e => { holdStart(); });
mainCarrot.addEventListener('touchstart', e => { e.stopImmediatePropagation(); holdStart(); });
/** Holding down clicks carrots
* @param {Boolean} useMousePos
*/
function holdStart(useMousePos = true, method=0) {
clearTimeout(hold.delay);
hold.active = true;
hold.delay = setTimeout(() => {
clearInterval(hold.clock)
hold.clock = setInterval(() => {
if(document.hidden) return clearInterval(hold.clock);
carrotClick(false, useMousePos, method);
}, 1000 / (Jared.data.clickrate.value || 2));
}, 250);
}
// holdStop
//#region
/** Stops Clicking on release */
function holdStop() {
hold.active = false;
clearTimeout(hold.delay);
clearInterval(hold.clock);
}
mainCarrot.addEventListener('mouseup', () => { holdStop(); });
mainCarrot.addEventListener('mouseout', event => {
if(!hold.active || clickMethod === 1) return;
let obstruct = event.relatedTarget; // Don't stop if moused out to falling carrot
if(obstruct.classList.contains('falling_carrot')) return obstruct.click();
holdStop();
});
mainCarrot.addEventListener('touchend', () => { holdStop(); });
mainCarrot.addEventListener('touchcancel', () => { holdStop(); });
window.addEventListener('blur', () => {
holdStop();
setTimePlayed();
window.blurred = true;
})
window.addEventListener('focus', () => startTime = Date.now(), window.blurred = undefined);
//#endregion
// Carrot click
mainCarrot.addEventListener('touchstart', event => { carrotClick(event, true, 2) });
mainCarrot.addEventListener('click', event => { carrotClick(event) });
var clickMethod = -1; // -1 = any, 0 = click, 1 = key, 2 = touch
var clickMethodTimer;
/** Carrot Click
* @param {Boolean} useMousePos Whether or not to use the mouse position for the number popup
* @param {Number} source To prevent spacebar & click from being used simultaneously
* @returns
*/
function carrotClick(event, useMousePos=true, source=0) {
if(clickMethod === -1) { // Prevent click/spacebar at the same time
clickMethod = source;
clearTimeout(clickMethodTimer);
clickMethodTimer = setTimeout(() => clickMethod = -1, 1000);
}
if(
(clickMethod !== source && clickMethod !== -1 && !Jared.data.magic_keyboard.value) ||
(source === 2 && clickMethod === 2)
) return;
// Grant carrots
earnCarrots(player.cpc, 'click');
player.prestige.clicks++;
player.lifetime.clicks++;
fallingConsecutive = 0;
cpsbuff = 5; // Used by trinkets
// Update page
carrotCount();
popupHandler(useMousePos, DisplayRounded(Math.floor(player.cpc,2), 1, 10000, unitsShort));
mouseConfetti([0, 2], ccCarrot, 200, 5);