-
Notifications
You must be signed in to change notification settings - Fork 0
/
musicaddict3.mts
1685 lines (1349 loc) · 60.1 KB
/
musicaddict3.mts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { MusicAddict3_Data } from './musicaddict3.data.v3.mjs'
import PocketBase, { ListResult, RecordAuthResponse, RecordModel } from './vendor/pocketbase/0.21.5/pocketbase.es.mjs'
// ================================================================================================
// SHARED
//
const COVERART_BUFFER: coverart_buffer = {}
// ================================================================================================
// CONF
//
class MusicAddict3_Conf
{
site_url: string = './'
db_url: string = 'http://127.0.0.1:8090'
game_loop_interval: number = 3_000
ui_loop_interval: number = 1_000
save_loop_interval: number = 60_000
authrefresh_loop_interval: number = 600_000
activeplayers_loop_interval: number = 30_000
discover_chance: number = 0.13
listening_duration_range: number_range = { min: 15_000, max: 90_000 }
offer_chance: number = 0.31
offer_interval: number_range = { min: 60_000, max: 180_000 }
sell_price_mod_range: number_range = {min: 1.01, max: 1.5}
storage_upgrade_price_mod: number = 1.3
storage_size_max: number = 100
release_year_range: number_range = { min: 1950, max: 2064 }
transactions_list_max: number = 100
log_list_max: number = 100
tradelog_list_max: number = 100
price_tier_ranges: price_tier_ranges = [
{ roll_max: 0.0050, min_cash: 4_000, range: { min: 3_999, max: 100_000 }, tier_level: 6, tier_name: 'Holy Grail' },
{ roll_max: 0.0090, min_cash: 500, range: { min: 499, max: 999 }, tier_level: 5, tier_name: 'Platinum Press' },
{ roll_max: 0.0500, min_cash: 200, range: { min: 199, max: 499 }, tier_level: 4, tier_name: 'First Pressing' },
{ roll_max: 0.2000, min_cash: 50, range: { min: 49, max: 199 }, tier_level: 3, tier_name: 'Signed Copy' },
{ roll_max: 0.2500, min_cash: 20, range: { min: 19, max: 49 }, tier_level: 2, tier_name: 'Limited Edition' },
{ roll_max: 0.3000, min_cash: 7, range: { min: 6, max: 19 }, tier_level: 1, tier_name: 'B-Side Gem' },
{ roll_max: 1.0000, min_cash: 0, range: { min: 0.5, max: 6 }, tier_level: 0, tier_name: 'Common Cut' },
]
reputation_max: number = 100
reputation_gains: reputation_gains = {
buy_record: 0.0131,
sell_record: 0.0313,
upgrade_storage: 0.0171,
}
}
// ================================================================================================
// ENGINE
//
class MusicAddict3_Engine
{
Conf: MusicAddict3_Conf
UI: MusicAddict3_UI
DB: PocketBase
Worker: Worker
user_session: user_session = {
is_logged_in: false,
id: '',
save_id: '',
name: 'Anonymous',
}
save: save_data = {
// keepers
data_version: 1,
theme: 'dark',
cash: 7,
records: [],
collection_worth: { min: 0, max: 0 },
records_listened: 0,
records_liked: 0,
records_disliked: 0,
trade_income: 0,
trade_expenses: 0,
trade_profit: 0,
trade_offers_accepted: 0,
trade_offers_declined: 0,
records_sold: 0,
records_bought: 0,
reputation: 0,
storage_size: 10,
buy_chance: 0.1,
sell_chance: 0.9,
game_started_on: 0,
next_progress_action: 'digg',
buy_record: {} as record,
sell_record: {} as record,
sell_record_key: 0,
incoming_offer: false,
started_listening_on: 0,
listen_duration: 0,
// reset these on startup
session_started_on: 0,
autosaved_on: 0,
last_offer_on: 0,
next_offer_in: 0,
}
constructor()
{
this.Conf = new MusicAddict3_Conf()
this.UI = new MusicAddict3_UI()
this.DB = new PocketBase(this.Conf.db_url)
this.Worker = new Worker(`./lib/musicaddict3.worker.mjs?v=${Date.now()}`, { type: 'module' })
this.Worker.onmessage = (event: MessageEvent) => this.on_worker_message(event.data)
switch (window.location.pathname.split('/').pop())
{
case '':
case 'index.html':
this.init_game()
break
case 'market.html':
this.init_market()
break
}
}
async init_game(): Promise<void>
{
this.Worker.postMessage({
cmd: 'init_game',
payload: {
conf: {
game_loop_interval: this.Conf.game_loop_interval,
ui_loop_interval: this.Conf.ui_loop_interval,
save_loop_interval: this.Conf.save_loop_interval,
authrefresh_loop_interval: this.Conf.authrefresh_loop_interval,
}
},
} as worker_message_data)
const auth_data = await this.auth()
if (auth_data) {
this.user_session.is_logged_in = true
this.user_session.id = auth_data.record.id
this.user_session.name = auth_data.record['username']
const loaded_save = await this.load_save()
if (!loaded_save) {
this.UI.sysmsg(`Could not load progress data. Please try again.`)
}
else {
const save_data: save_data = this.decode_save(loaded_save['data'])
this.user_session.save_id = loaded_save.id
if (!save_data.data_version || save_data.data_version != this.save.data_version) {
this.UI.sysmsg(`Sorry, progress data reset required from version ${save_data.data_version} to ${this.save.data_version}.`)
}
else {
this.save = save_data
}
if (this.save.game_started_on == 0) {
this.save.game_started_on = Date.now()
}
this.save.session_started_on = 0
this.save.autosaved_on = 0
this.save.last_offer_on = 0
this.save.next_offer_in = 0
if (this.save.buy_record.id) {
COVERART_BUFFER[this.save.buy_record.id] = Coverart(this.save.buy_record.id, this.save.buy_record.title) ?? ''
}
if (this.save.sell_record.id) {
COVERART_BUFFER[this.save.sell_record.id] = Coverart(this.save.sell_record.id, this.save.sell_record.title) ?? ''
}
}
}
this.init_game_ui()
}
async init_market(): Promise<void>
{
const recent_log_entries: ListResult<RecordModel> = await this.DB.collection('ma3_tradelog').getList(1, this.Conf.tradelog_list_max, { sort: '-created' })
for (const log_entry of recent_log_entries.items) {
this.add_to_marked_trades_list(log_entry, true)
}
await this.DB.collection('ma3_tradelog').subscribe('*', (e) => this.add_to_marked_trades_list(e.record), { sort: '-created' })
this.Worker.postMessage({
cmd: 'init_market',
payload: {
conf: {
activeplayers_loop_interval: this.Conf.activeplayers_loop_interval,
},
},
} as worker_message_data)
this.UI.unhide(this.UI.e.tradelog)
this.UI.unbusy(this.UI.e.loading)
}
async auth(): Promise<RecordAuthResponse<RecordModel> | null>
{
try {
if (this.DB.authStore.isValid) {
const auth_data = await this.DB.collection('ma3_users').authRefresh()
return auth_data
}
}
catch (boo) {
this.UI.sysmsg('Re-authentication failed.')
}
return null
}
async load_save(): Promise<RecordModel | null>
{
try {
const existing_save: RecordModel = await this.DB.collection('ma3_saves').getFirstListItem(`user="${this.user_session.id}"`, { skipTotal: true })
return existing_save
}
catch (itsjustanewgame) {}
try {
const new_save: RecordModel = await this.DB.collection('ma3_saves').create({ user: this.user_session.id, data: this.encode_save(this.save) })
return new_save
}
catch (boo) {
return null
}
}
async store_save(): Promise<RecordModel | null>
{
try {
const stored_save_data: RecordModel = await this.DB.collection('ma3_saves').update(this.user_session.save_id, { user: this.user_session.id, data: this.encode_save(this.save) })
return stored_save_data
}
catch (boo) {
return null
}
}
init_game_ui(): void
{
this.set_theme(this.save.theme)
this.UI.e.signin_register_submit.addEventListener('click', () => this.on_register_submit())
this.UI.e.signin_login_submit.addEventListener('click', () => this.on_login_submit())
this.UI.e.ctrl_logout.addEventListener('click', () => this.on_logout_submit())
this.UI.e.ctrl_play.addEventListener('click', () => this.on_game_ctrl_play())
this.UI.e.ctrl_pause.addEventListener('click', () => this.on_game_ctrl_pause())
this.UI.e.ctrl_reset.addEventListener('click', () => this.on_game_ctrl_reset())
this.UI.e.ctrl_buy_chance_input.addEventListener('change', () => this.on_ctrl_buy_chance())
this.UI.e.ctrl_sell_chance_input.addEventListener('change', () => this.on_ctrl_sell_chance())
this.UI.e.ctrl_upgrade_storage.addEventListener('click', () => this.on_ctrl_upgrade_storage())
this.UI.e.ctrl_theme.addEventListener('click', () => this.on_ctrl_theme())
this.UI.e.ctrl_bgmusic.addEventListener('click', () => this.on_ctrl_bgmusic())
for (const dialog of document.querySelectorAll('dialog')) {
dialog.querySelector('.close')?.addEventListener('click', () => {
dialog.close()
})
}
if (!this.user_session.is_logged_in) {
this.UI.unhide([this.UI.e.intro, this.UI.e.signin_register, this.UI.e.signin_login])
this.UI.open(this.UI.e.intro)
}
else {
this.UI.hide([this.UI.e.signin_register, this.UI.e.signin_login])
this.UI.unopen(this.UI.e.intro)
this.UI.unhide([this.UI.e.intro, this.UI.e.game, this.UI.e.player_name])
this.UI.sysmsg(`Hello ${this.user_session.name}!`)
}
this.UI.e.player_name_value.innerHTML = this.user_session.name
this.UI.e.stats_started_on_value.innerHTML = Fmt.timestamp(this.save.game_started_on)
this.UI.e.ctrl_buy_chance_value.innerHTML = Fmt.percent(1.0 - this.save.buy_chance)
this.UI.e.ctrl_buy_chance_input.value = String(1.0 - this.save.buy_chance)
this.UI.e.ctrl_sell_chance_value.innerHTML = Fmt.percent(1.0 - this.save.sell_chance)
this.UI.e.ctrl_sell_chance_input.value = String(1.0 - this.save.sell_chance)
this.UI.e.ctrl_upgrade_storage_value.innerHTML = Fmt.cash(this.next_storage_slot_price())
this.UI.e.stats_records_missed_value.innerHTML = `${this.save.records_liked - this.save.records_bought}`
this.init_collection_list()
this.UI.unhide(this.UI.e.signin)
this.UI.unbusy(this.UI.e.loading)
this.update_ui()
}
update_ui(): void
{
this.UI.e.stats_cash_value.innerHTML = Fmt.cash(this.save.cash)
this.UI.e.stats_records_value.innerHTML = `${this.save.records.length} / ${this.save.storage_size}`
this.UI.e.stats_reputation_value.innerHTML = (this.save.reputation <= this.Conf.reputation_max) ? `${Fmt.float(this.save.reputation, 4)}` : `${Fmt.float(this.save.reputation, 4)} <small>(maxed out)</small>`
this.UI.e.stats_session_duration_value.innerHTML = (this.save.session_started_on > 0) ? Fmt.duration((Date.now() - this.save.session_started_on)) : '-'
this.UI.e.stats_autosaved_ago_value.innerHTML = (this.save.autosaved_on > 0) ? ((Date.now() - this.save.autosaved_on < this.Conf.save_loop_interval) ? Fmt.duration(Date.now() - this.save.autosaved_on) : `<span class="negative">${Fmt.duration(Date.now() - this.save.autosaved_on)}</span>`) : '<span class="negative">-</span>'
this.UI.e.stats_next_offer_in_value.innerHTML = (this.save.last_offer_on > 0) ? Fmt.duration((this.save.last_offer_on + this.save.next_offer_in) - Date.now()) : '-'
this.UI.e.stats_collection_worth_value.innerHTML = `${Fmt.cash(Math.max(0, this.save.collection_worth.min))} ‐ ${Fmt.cash(Math.max(0, this.save.collection_worth.max))}`
this.UI.e.stats_records_listened_value.innerHTML = `${this.save.records_listened}`
this.UI.e.stats_records_liked_value.innerHTML = `${this.save.records_liked}`
this.UI.e.stats_records_disliked_value.innerHTML = `${this.save.records_disliked}`
this.UI.e.stats_trade_income_value.innerHTML = Fmt.cash(this.save.trade_income)
this.UI.e.stats_trade_expenses_value.innerHTML = Fmt.cash(this.save.trade_expenses)
this.UI.e.stats_trade_profit_value.innerHTML = Fmt.cash(this.save.trade_profit)
this.UI.e.stats_records_sold_value.innerHTML = `${this.save.records_sold}`
this.UI.e.stats_records_bought_value.innerHTML = `${this.save.records_bought}`
this.UI.e.stats_trade_offers_accepted_value.innerHTML = `${this.save.trade_offers_accepted}`
this.UI.e.stats_trade_offers_declined_value.innerHTML = `${this.save.trade_offers_declined}`
if (this.save.storage_size == this.Conf.storage_size_max) {
this.UI.disable(this.UI.e.ctrl_upgrade_storage)
this.UI.e.ctrl_upgrade_storage_value.innerHTML = '<small>maxed out</small>'
}
else {
if (this.save.cash < this.next_storage_slot_price()) {
this.UI.disable(this.UI.e.ctrl_upgrade_storage)
}
else {
this.UI.undisable(this.UI.e.ctrl_upgrade_storage)
}
}
}
progress(): void
{
if (this.save.last_offer_on == 0) {
this.save.last_offer_on = Date.now()
this.save.next_offer_in = Rnd.float(this.Conf.offer_interval.min, this.Conf.offer_interval.max)
}
// trigger 'getoffer'
if (
Rnd.roll(this.Conf.offer_chance)
&& Date.now() - this.save.last_offer_on > this.save.next_offer_in
&& this.save.records.length > 0
&& ['broke', 'digg'].includes(this.save.next_progress_action)
) {
this.save.incoming_offer = true
this.save.next_progress_action = 'getoffer'
}
// trigger 'broke'
else if (
this.save.cash == 0
&& !this.save.incoming_offer
){
this.save.next_progress_action = 'broke'
}
switch (this.save.next_progress_action)
{
case 'digg':
this.add_log_line(`Digging for cool records.`)
if (Rnd.roll(this.Conf.discover_chance)) {
this.save.next_progress_action = 'discover'
}
break
case 'discover':
this.save.buy_record = this.random_record()
this.add_log_line(`Discovered ${Fmt.record(this.save.buy_record)}.`)
this.save.next_progress_action = 'listen'
break
case 'listen':
this.add_log_line(`Listening.`)
if (this.save.started_listening_on == 0) {
this.save.started_listening_on = Date.now()
this.save.listen_duration = Rnd.int(this.Conf.listening_duration_range.min, this.Conf.listening_duration_range.max)
}
else if (Date.now() - this.save.started_listening_on > this.save.listen_duration) {
this.save.started_listening_on = 0
this.save.records_listened += 1
if (Rnd.roll(this.save.buy_chance)) {
this.save.records_liked += 1
this.add_log_line(`You like what you hear.`)
this.save.next_progress_action = 'buy'
}
else {
this.save.records_disliked += 1
this.add_log_line(`You don't like what you hear.`)
this.save.next_progress_action = 'nobuy'
}
}
break
case 'buy':
if (this.save.cash < this.save.buy_record.buy_price.amount) {
this.UI.e.stats_records_missed_value.innerHTML = `${this.save.records_liked - this.save.records_bought}`
this.add_log_line(`Not enough cash to buy ${Fmt.record(this.save.buy_record)} for <span class="negative">${Fmt.cash(this.save.buy_record.buy_price.amount)}</span> (need <span class="negative">${Fmt.cash(this.save.buy_record.buy_price.amount - this.save.cash)}</span> more).`)
}
else if (this.save.records.length + 1 > this.save.storage_size) {
this.UI.e.stats_records_missed_value.innerHTML = `${this.save.records_liked - this.save.records_bought}`
this.add_log_line(`Not enough space to store ${Fmt.record(this.save.buy_record)}.`)
}
else {
this.save.cash -= this.save.buy_record.buy_price.amount
this.save.reputation += this.reputation_gain('buy_record')
this.save.trade_expenses += this.save.buy_record.buy_price.amount
this.save.records_bought += 1
this.save.records.push(this.save.buy_record)
this.add_to_collection_list(this.save.buy_record)
this.add_to_transactions_list('buy_record', this.save.buy_record.buy_price.amount)
this.log_trade('buy', this.save.buy_record)
this.add_log_line(`Bought ${Fmt.record(this.save.buy_record)} for <span class="negative">${Fmt.cash(this.save.buy_record.buy_price.amount)}</span>.`)
}
this.save.next_progress_action = 'digg'
break
case 'nobuy':
this.add_log_line(`Going to another corner of the store.`)
this.save.next_progress_action = 'digg'
break
case 'broke':
this.add_log_line(`You're broke.`)
break
case 'getoffer':
this.save.last_offer_on = Date.now()
this.save.next_offer_in = Rnd.float(this.Conf.offer_interval.min, this.Conf.offer_interval.max) - this.offer_interval_reduction()
this.save.sell_record_key = Rnd.array_key(this.save.records)
this.save.sell_record = this.save.records[this.save.sell_record_key] as record
this.save.sell_record.sell_price = this.record_sell_price(this.save.sell_record.buy_price)
this.add_log_line(`Someone wants to buy ${Fmt.record(this.save.sell_record)} from your collection.`)
if (Rnd.roll(this.save.sell_chance)) {
this.save.trade_offers_accepted += 1
this.save.next_progress_action = 'sell'
}
else {
this.save.trade_offers_declined += 1
this.save.next_progress_action = 'nosell'
}
break
case 'sell':
this.save.incoming_offer = false
this.save.cash += this.save.sell_record.sell_price.amount
this.save.reputation += this.reputation_gain('sell_record')
this.save.trade_income += this.save.sell_record.sell_price.amount
this.save.trade_profit += this.save.sell_record.sell_price.amount - this.save.sell_record.buy_price.amount
this.save.records_sold += 1
this.save.records.splice(this.save.sell_record_key, 1)
this.remove_from_collection_list(this.save.sell_record)
this.add_to_transactions_list('sell_record', this.save.sell_record.sell_price.amount)
this.log_trade('sell', this.save.sell_record)
this.add_log_line(`Sold it for <span class="positive">${Fmt.cash(this.save.sell_record.sell_price.amount)}</span> (<span class="positive">${Fmt.cash(this.save.sell_record.sell_price.amount - this.save.sell_record.buy_price.amount)}</span> profit).`)
this.save.next_progress_action = 'digg'
break
case 'nosell':
this.add_log_line(`Naah, you hold on to this one for now.`)
this.save.incoming_offer = false
this.save.next_progress_action = 'digg'
break
default:
console.warn('unhandled progress action:', this.save.next_progress_action)
}
}
add_log_line(message: string): void
{
const line = document.createElement('div')
line.classList.add('log_line')
line.innerHTML = `<small class="time">${Fmt.timestamp(Date.now(), '{hours}:{minutes}')}</small> <span class="message">${message}</span>`
this.UI.e.log_lines.prepend(line)
if (this.UI.e.log_lines.childNodes.length > this.Conf.log_list_max) {
this.UI.e.log_lines.lastChild?.remove()
}
}
init_collection_list(): void
{
this.save.collection_worth.min = 0
this.save.collection_worth.max = 0
for (const record of this.save.records) {
COVERART_BUFFER[record.id] = Coverart(record.id, record.title) ?? ''
this.add_to_collection_list(record)
}
}
add_to_collection_list(record: record): void
{
this.update_collection_worth('add', record.buy_price)
const e = document.createElement('div')
e.classList.add('record', `tier_${record.buy_price.tier.tier_level}`)
e.dataset['id'] = record.id
e.innerHTML = `<img src="${COVERART_BUFFER[record.id]}" class="cover tier_${record.buy_price.tier.tier_level}">`
e.addEventListener('click', () => {
this.UI.e.record_info_title.innerHTML = Fmt.discogs_link('release', record.title)
this.UI.e.record_info_coverart.innerHTML = `<img src="${COVERART_BUFFER[record.id]}" class="cover">`
this.UI.e.record_info_meta.innerHTML = `
<p>
<small>Artist:</small> <strong>${Fmt.discogs_link('artist', record.artist)}</strong><br>
<small>Year:</small> <strong>${Fmt.discogs_link('year', record.year)}</strong><br>
<small>Style:</small> <strong>${Fmt.discogs_link('style', record.style)}</strong><br>
<small>Format:</small> <strong>${Fmt.discogs_link('format', record.format)}</strong>
</p>
<p>
<small>Tier:</small> <span class="tier_${record.buy_price.tier.tier_level}">${record.buy_price.tier.tier_level}, ${record.buy_price.tier.tier_name}</span><br>
<small>Bought for:</small> <span class="negative">${Fmt.cash(record.buy_price.amount)}</span><br>
<small>Sells for:</small> <span class="positive">${Fmt.cash(record.buy_price.amount * this.Conf.sell_price_mod_range.min)} - ${Fmt.cash(record.buy_price.amount * this.Conf.sell_price_mod_range.max)}</span>
</p>
`
this.UI.e.record_info.showModal()
})
this.UI.e.collection_list.prepend(e)
}
remove_from_collection_list(record: record): void
{
this.update_collection_worth('substract', record.buy_price)
delete COVERART_BUFFER[record.id]
this.UI.e.collection_list.querySelector(`[data-id='${record.id}']`)?.remove()
}
add_to_transactions_list(type: 'buy_record' | 'sell_record' | 'buy_storage', amount: number): void
{
const e: HTMLDivElement = document.createElement('div')
e.innerHTML = `<span class="time">${Fmt.timestamp(Date.now(), '{hours}:{minutes}')}</span><br>`
switch (type)
{
case 'buy_record':
e.innerHTML += `buy record<br><span class="negative">-${Fmt.cash(amount)}</span><br>`
this.UI.e.transactions_list.prepend(e)
break
case 'sell_record':
e.innerHTML += `sell record<br><span class="positive">+${Fmt.cash(amount)}</span><br>`
this.UI.e.transactions_list.prepend(e)
break
case 'buy_storage':
e.innerHTML += `buy storage<br><span class="negative">-${Fmt.cash(amount)}</span><br>`
this.UI.e.transactions_list.prepend(e)
break
}
if (this.UI.e.transactions_list.childNodes.length > this.Conf.transactions_list_max) {
this.UI.e.transactions_list.lastChild?.remove()
}
}
update_collection_worth(mode: 'add' | 'substract', buy_price: record_buy_price): void
{
const min: number = buy_price.amount * this.Conf.sell_price_mod_range.min
const max: number = buy_price.amount * this.Conf.sell_price_mod_range.max
switch (mode)
{
case 'add':
this.save.collection_worth.min += min
this.save.collection_worth.max += max
break
case 'substract':
this.save.collection_worth.min -= min
this.save.collection_worth.max -= max
break
}
}
async on_worker_message(message: worker_message_data): Promise<void>
{
// console.debug('main got msg', message)
switch (message.cmd)
{
case 'game_loop_tick':
this.progress()
this.Worker.postMessage({
cmd: 'plan_next_game_loop_tick',
payload: {},
} as worker_message_data)
break
case 'ui_loop_tick':
this.update_ui()
this.Worker.postMessage({
cmd: 'plan_next_ui_loop_tick',
payload: {},
} as worker_message_data)
break
case 'save_loop_tick':
const stored_save_data: RecordModel | null = await this.store_save()
if (!stored_save_data) {
this.UI.sysmsg('Progress auto-save failed, will retry automatically.')
}
else {
this.save.autosaved_on = new Date(stored_save_data.updated).getTime()
}
this.Worker.postMessage({
cmd: 'plan_next_save_loop_tick',
payload: {},
} as worker_message_data)
break
case 'authrefresh_loop_tick':
try {
if (this.DB.authStore.isValid) {
await this.DB.collection('ma3_users').authRefresh()
}
}
catch (boo) {
this.UI.sysmsg('Authentication-refresh failed.')
}
this.Worker.postMessage({
cmd: 'plan_next_authrefresh_loop_tick',
payload: {},
} as worker_message_data)
break
case 'activeplayers_loop_tick':
try {
const activeplayers: RecordModel = await this.DB.collection('ma3_activeplayers').getOne('1', {})
this.UI.e.activeplayers_count_value.innerHTML = `${activeplayers['activeplayers_count']}`
}
catch (boo) {}
this.Worker.postMessage({
cmd: 'plan_next_activeplayers_loop_tick',
payload: {},
} as worker_message_data)
break
default:
console.warn('main got unhandled command:', message.cmd)
}
}
async on_register_submit(): Promise<void>
{
this.UI.busy(this.UI.e.signin_register_submit)
const username: string = this.UI.e.signin_register_username.value.trim()
const password: string = this.UI.e.signin_register_password.value.trim()
const passwordconfirm: string = this.UI.e.signin_register_passwordconfirm.value.trim()
if (!username || !password || !passwordconfirm) {
this.UI.sysmsg(`Fill out all fields to register.`)
this.UI.unbusy(this.UI.e.signin_register_submit)
return
}
try {
await this.DB.collection('ma3_users').create({ username: username, password: password, passwordConfirm: passwordconfirm })
await this.DB.collection('ma3_users').authWithPassword(username, password)
if (!this.DB.authStore.isValid) {
this.UI.unbusy(this.UI.e.signin_register_submit)
}
else {
this.reload()
}
}
catch (boo) {
this.UI.sysmsg('Could not create new user data. Please check your input and try again.')
this.UI.unbusy(this.UI.e.signin_register_submit)
}
}
async on_login_submit(): Promise<void>
{
this.UI.busy(this.UI.e.signin_login_submit)
const username: string = this.UI.e.signin_login_username.value.trim()
const password: string = this.UI.e.signin_login_password.value.trim()
if (!username || !password) {
this.UI.sysmsg('Fill out all fields to login.')
this.UI.unbusy(this.UI.e.signin_login_submit)
return
}
try {
await this.DB.collection('ma3_users').authWithPassword(username, password)
if (!this.DB.authStore.isValid) {
this.UI.unbusy(this.UI.e.signin_login_submit)
}
else {
this.reload()
}
}
catch (boo) {
this.UI.sysmsg('Could not authenticate. Please check your input and try again.')
this.UI.unbusy(this.UI.e.signin_login_submit)
}
}
on_logout_submit(): void
{
this.UI.busy(this.UI.e.loading)
this.UI.hide([this.UI.e.intro, this.UI.e.game])
this.UI.sysmsg(`Bye, see you soon ${this.user_session.name}!`)
this.Worker.postMessage({
cmd: 'pause',
payload: {},
} as worker_message_data)
this.DB.authStore.clear()
setTimeout(() => this.reload(), 2_000)
}
on_game_ctrl_play(): void
{
this.UI.hide([this.UI.e.ctrl_play, this.UI.e.ctrl_logout, this.UI.e.ctrl_reset])
this.UI.unhide([this.UI.e.ctrl_pause, this.UI.e.ctrl_upgrade_storage])
this.UI.undisable([this.UI.e.ctrl_buy_chance_input, this.UI.e.ctrl_sell_chance_input])
this.save.session_started_on = Date.now()
this.update_ui()
this.add_log_line(`You enter the record store.`)
this.Worker.postMessage({
cmd: 'play',
payload: {},
} as worker_message_data)
}
on_game_ctrl_pause(): void
{
this.UI.unhide([this.UI.e.ctrl_play, this.UI.e.ctrl_logout, this.UI.e.ctrl_reset])
this.UI.hide([this.UI.e.ctrl_pause, this.UI.e.ctrl_upgrade_storage])
this.UI.disable([this.UI.e.ctrl_buy_chance_input, this.UI.e.ctrl_sell_chance_input])
this.update_ui()
this.add_log_line(`You leave the record store.`)
this.Worker.postMessage({
cmd: 'pause',
payload: {},
} as worker_message_data)
}
async on_game_ctrl_reset(): Promise<void>
{
this.UI.disable([this.UI.e.ctrl_reset, this.UI.e.ctrl_play, this.UI.e.ctrl_logout, this.UI.e.ctrl_theme, this.UI.e.ctrl_bgmusic])
if (!confirm(`If you really want to reset all game progress, click 'OK'. If not, click 'CANCEL'.`)) {
this.UI.undisable([this.UI.e.ctrl_reset, this.UI.e.ctrl_play, this.UI.e.ctrl_logout, this.UI.e.ctrl_theme, this.UI.e.ctrl_bgmusic])
return
}
try {
const save_deleted: boolean = await this.DB.collection('ma3_saves').delete(this.user_session.save_id)
if (!save_deleted) {
this.UI.sysmsg(`Could not reset progress data. Please try again.`)
this.UI.undisable([this.UI.e.ctrl_reset, this.UI.e.ctrl_play, this.UI.e.ctrl_logout, this.UI.e.ctrl_theme, this.UI.e.ctrl_bgmusic])
}
else {
this.reload()
}
}
catch (boo) {
this.UI.sysmsg(`Could not reset progress data. Please try again.`)
this.UI.undisable([this.UI.e.ctrl_reset, this.UI.e.ctrl_play, this.UI.e.ctrl_logout, this.UI.e.ctrl_theme, this.UI.e.ctrl_bgmusic])
}
}
on_ctrl_buy_chance(): void
{
this.save.buy_chance = 1.0 - Number(this.UI.e.ctrl_buy_chance_input.value)
this.UI.e.ctrl_buy_chance_value.innerHTML = Fmt.percent(1.0 - this.save.buy_chance)
}
on_ctrl_sell_chance(): void
{
this.save.sell_chance = 1.0 - Number(this.UI.e.ctrl_sell_chance_input.value)
this.UI.e.ctrl_sell_chance_value.innerHTML = Fmt.percent(1.0 - this.save.sell_chance)
}
on_ctrl_upgrade_storage(): void
{
this.UI.disable(this.UI.e.ctrl_upgrade_storage)
if (this.save.storage_size == this.Conf.storage_size_max) {
return
}
const next_storage_slot_price = this.next_storage_slot_price()
if (this.save.cash < next_storage_slot_price) {
return
}
this.save.cash -= next_storage_slot_price
this.save.storage_size += 1
this.save.reputation += this.reputation_gain('upgrade_storage')
this.UI.e.ctrl_upgrade_storage_value.innerHTML = Fmt.cash(this.next_storage_slot_price())
this.add_to_transactions_list('buy_storage', next_storage_slot_price)
this.add_log_line(`Bought a storage slot for <span class="negative">${Fmt.cash(next_storage_slot_price)}</span>.`)
}
on_ctrl_theme(): void
{
let theme: string = document.documentElement.dataset['theme'] || 'dark'
if (theme == 'dark') {
this.set_theme('light')
}
else {
this.set_theme('dark')
}
}
on_ctrl_bgmusic(): void
{
this.UI.e.bgmusic_player.showModal()
}
set_theme(theme: 'dark' | 'light'): void
{
document.documentElement.dataset['theme'] = theme
this.save.theme = theme
}
reputation_gain(type: 'buy_record' | 'sell_record' | 'upgrade_storage'): number
{
if (this.save.reputation >= this.Conf.reputation_max) {
return 0
}
return this.Conf.reputation_gains[type]
}
next_storage_slot_price(): number
{
return (this.save.storage_size + 1) * this.Conf.storage_upgrade_price_mod
}
encode_save(data: save_data): string
{
return btoa(JSON.stringify(data))
}
decode_save(data: string): save_data
{
return JSON.parse(atob(data))
}
reload(): void
{
window.location.replace(this.Conf.site_url)
}
random_record(): record
{
const title: string = Rnd.record_title()
const artist: string = Rnd.artist_name()
const year: number = Rnd.int(this.Conf.release_year_range.min, this.Conf.release_year_range.max)
const style: string = Rnd.music_style()
const format: string = Rnd.record_format()
const id: string = this.record_id(title, artist)
const buy_price: record_buy_price = this.record_buy_price()
COVERART_BUFFER[id] = Coverart(id, title) ?? ''
return {
title: title,
artist: artist,
year: year,
style: style,
format: format,
id: id,
buy_price: buy_price,
sell_price: {} as record_sell_price,
}
}
record_buy_price(): record_buy_price
{
let price!: record_buy_price
for (const t of this.Conf.price_tier_ranges) {
const roll: number = Math.random()
if (this.save.cash >= t.min_cash && roll <= t.roll_max) {
price = {
amount: Rnd.float(t.range.min, t.range.max),
tier: t,
}
break
}
}
return price
}
record_sell_price(buy_price: record_buy_price): record_sell_price
{
return {
amount: buy_price.amount * Rnd.float(this.Conf.sell_price_mod_range.min, this.Conf.sell_price_mod_range.max),
}
}
record_id(title: string, artist: string, id_length: number = 64): string
{
const id_char_rep_map = {
'a': '2',
'b': '3',
'c': '5',