-
Notifications
You must be signed in to change notification settings - Fork 0
/
index2.html
2012 lines (1714 loc) · 58.8 KB
/
index2.html
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
<!doctype html>
<html prefix="og: http://ogp.me/ns#">
<head>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-130030503-3"></script>
<script>
if (window.location.hostname !== 'localhost') {
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-130030503-3');
}
</script>
<meta charset="utf-8">
<meta id="viewport" name="viewport" content="">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<style>* {padding: 0; margin: 0; overflow: hidden;}</style>
<title>Crypto Climber</title>
<meta property="og:title" content="Crypto Climber" />
<meta property="og:type" content="website" />
<meta property="og:url" content="https://cryptoclimber.decent.org/" />
<meta property="og:image" content="https://cryptoclimber.decent.org/og.png" />
<meta property="og:description" content="Fun little game about bitcoin trading" />
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png">
<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/4.8.5/pixi.min.js"></script>
<script src="pixi-multistyle-text/0.6.0/pixi-multistyle-text.umd.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js"></script>
<script src="file-saver/2.0.1/FileSaver.min.js"></script>
</head>
<body>
<script>
// ===== constants =====
const INIT_FUNDS = 10000
const TICKS_PER_DAY = 24
const GAME_LENGTH_DAYS = parseInt(getQueryParam('days'), 10) || 30
const GAME_LENGTH_TICKS = GAME_LENGTH_DAYS * TICKS_PER_DAY
const PAST_LENGTH_DAYS = Math.round(GAME_LENGTH_DAYS / 2)
const PAST_LENGTH_TICKS = PAST_LENGTH_DAYS * TICKS_PER_DAY
const GRAPH_X_GRANULARITY_PX = 5 // smaller is more dense
const Y_SCALE_FACTOR = 1000
const BANDS = 20
const OFFSET_X = 0.25
const SMOOTH_FACTOR_Y = 50
const MARGIN = 15
const BUTTON_WIDTH = 160
const BUTTON_HEIGHT = 80
const SHOW_PRICE = false
const SHOW_DEBUG = false
const SHOW_FPS = parseBoolean(getQueryParam('fps')) || false
const SPEED_LEVELS = [6.0, 4.8, 3.6, 2.4, 1.2]
const ZOOM_LEVELS = [1.6, 1.4, 1.2, 1.0, 0.8]
const DEFAULT_LEVEL = 2
const DEFAULT_SPEED = SPEED_LEVELS[DEFAULT_LEVEL]
const DEFAULT_ZOOM = ZOOM_LEVELS[DEFAULT_LEVEL]
const WARP_SPEED_DELTA = (SPEED_LEVELS[0] - SPEED_LEVELS[1]) / 30
const WARP_ZOOM_DELTA = (ZOOM_LEVELS[0] - ZOOM_LEVELS[1]) / 30
const INTRO =
'How good are you at trading' +
'\na ' + GAME_LENGTH_DAYS + ' day sample of' +
'\nhistorical Bitcoin prices?' +
'<strong>' +
'\n\nPress [UP] to go LONG' +
'\nPress [DOWN] to sell SHORT' +
'\nPress [SPACE] to close position ' +
'</strong>' +
'\n\nPress [LEFT] / [RIGHT] to change speed ' +
'\nPress [P] to pause game ' +
'\n\n<strong>Press [ENTER] or [SPACE] to start!</strong>'
const HODL_NAME = 'Buy and hold'
const SHEET_URL = 'https://script.google.com/macros/s/AKfycbyDTk5pYHGjgHartXZZX876CZbKYa_kKljZDEOJ1dylwVSn1Mk/exec'
const TEST_SHEET_URL = 'https://script.google.com/macros/s/AKfycbwISEh8gGr-8QXD_76yIn8AsxDhUI3XS8ACE0Q2E4uWnTYbdfY/exec'
const DEFAULT_TEXTS = Object.freeze({
summary: INTRO,
highscores: '',
iteration: '',
funds: '',
price: '',
debug: '',
})
const COLOR_BUTTON_INACTIVE = 0xffffff
const COLOR_BUTTON_ACTIVE = 0xffee44
const COLOR_BUTTON_PRESSED = 0xffee44
const COLOR_BUTTON_DISABLED = 0x444444
const COLOR_RED = 0xff0000
const COLOR_GREEN = 0x00ff00
const COLOR_BLACK = 0x000000
const COLOR_GREY_DARK_2 = 0x222222
const COLOR_GREY_DARK_4 = 0x444444
const COLOR_GREY_DARK_6 = 0x666666
const COLOR_GREY_MEDIUM = 0x888888
const COLOR_GREY_LIGHT = 0xcccccc
const COLOR_WHITE = 0xffffff
const COLOR_SELF = 0xffff00 // yellow
const COLOR_HODL = 0x00aaff // light blue
const COLOR_NICE_BLUE = 0x1a73e8
const EPSILON = 0.1
const HOUR_IN_MS = 60 * 60 * 1000
// ===== global variables =====
let screenWidth = window.innerWidth
let screenHeight = window.innerHeight
let speed = DEFAULT_SPEED
let zoom = DEFAULT_ZOOM
let texts = Object.assign({}, DEFAULT_TEXTS)
let entities = {
gamespace: null,
tradelines: null,
tradelabels: null,
ui: null,
messages: {
iteration: null,
funds: null,
summary: null,
highscores: null,
price: null,
debug: null,
pause: null,
},
logos: null,
graph: null,
player: null,
equityGraph: null,
tradeGraph: null,
}
let assets = {
funds: INIT_FUNDS,
trade: null,
trades: [],
scores: [],
}
let priceData = {}
let player = getQueryParam('player')
let viewPortX = 0
let viewPortY = 0
let time = 0
let tick = -1
let gameOver = false
let gameStarted = false
let paused = false
let input = {
short: false,
long: false,
speedLevel: DEFAULT_LEVEL,
}
let fps = 60
// ===== startup code =====
if (window.navigator.userAgent.includes('iPhone') || window.navigator.userAgent.includes('Android')) {
document.getElementById("viewport").setAttribute("content",
"minimal-ui, width=device-width, initial-scale=0.5, minimum-scale=0.5, maximum-scale=0.5, user-scalable=no")
}
const app = new PIXI.Application({
width: window.innerWidth,
height: window.innerHeight,
antialias: false,
transparent: false,
resolution: window.devicePixelRatio,
preserveDrawingBuffer: true,
});
// Full screen
app.renderer.view.style.position = 'absolute';
app.renderer.view.style.display = 'block';
app.renderer.view.style.overflow = 'hidden';
app.renderer.autoResize = true;
screenWidth = window.innerWidth
screenHeight = window.innerHeight
app.renderer.resize(screenWidth, screenHeight);
document.body.appendChild(app.view);
PIXI.loader
.add('prices', 'btc1h.json')
.load(() => {
// TODO: load font concurrently with resources
WebFont.load({
google: {
families: ['B612 Mono']
},
active: setup
})
});
window.onresize = listenerResize
window.onload = () => {
listenerResize(null)
}
// ===== setup and layout =====
function setup() {
app.ticker.remove(update)
app.stage.removeChildren()
gameOver = false
gameStarted = false
time = 0
tick = -1
speed = DEFAULT_SPEED
zoom = DEFAULT_ZOOM
input = {
short: false,
long: false,
speedLevel: DEFAULT_LEVEL,
}
assets.funds = INIT_FUNDS
assets.trades = []
assets.scores = []
assets.trade = null
priceData = parsePriceData(PIXI.loader.resources.prices.data, GAME_LENGTH_TICKS)
entities.gamespace = new PIXI.Container()
entities.gamespace.interactive = false
entities.gamespace.interactiveChildren = false
entities.gamespace.addChild(createGrid())
entities.graph = createGraph()
entities.gamespace.addChild(entities.graph)
entities.gamespace.addChild(entities.graph.mask)
entities.player = createPlayer()
entities.gamespace.addChild(entities.player)
entities.tradelines = new PIXI.Container()
entities.gamespace.addChild(entities.tradelines)
entities.tradelabels = new PIXI.Container()
entities.gamespace.addChild(entities.tradelabels)
app.stage.addChild(entities.gamespace)
texts = Object.assign({}, DEFAULT_TEXTS)
setupUI(screenWidth, screenHeight);
onNeutral()
showControls(false)
setViewPort(0, 0, OFFSET_X)
addInputListeners()
app.ticker.add(update)
}
function setupUI(width, height) {
app.stage.removeChild(entities.ui)
let uiContainer = new PIXI.Container()
entities.ui = uiContainer
let {messagesContainer, messages} = createMessages(width, height, MARGIN)
uiContainer.addChild(messagesContainer)
entities.messages = messages
entities.logos = createLogos(width, height, MARGIN)
uiContainer.addChild(entities.logos)
entities.smallLogo = createSmallLogo(width, height, MARGIN)
uiContainer.addChild(entities.smallLogo)
entities.longButton = createButton("\u25B3\u2009Long\u2009",
width - BUTTON_WIDTH - MARGIN, height - 3 * BUTTON_HEIGHT - 5 * MARGIN,
BUTTON_WIDTH, BUTTON_HEIGHT, input.long,
(pressed) => {
if (pressed) {
onLong()
}
})
uiContainer.addChild(entities.longButton)
entities.neutralButton = createButton("Neutral",
width - BUTTON_WIDTH - MARGIN, height - 2 * BUTTON_HEIGHT - 3 * MARGIN,
BUTTON_WIDTH, BUTTON_HEIGHT, !input.long && !input.short,
(pressed) => {
if (pressed) {
onNeutral()
}
})
uiContainer.addChild(entities.neutralButton)
entities.shortButton = createButton("\u25BD\u2009Short",
width - BUTTON_WIDTH - MARGIN, height - BUTTON_HEIGHT - MARGIN,
BUTTON_WIDTH, BUTTON_HEIGHT, input.short,
(pressed) => {
if (pressed) {
onShort()
}
})
uiContainer.addChild(entities.shortButton)
entities.speedDown = createButton("<\u2009Slow",
MARGIN, height - BUTTON_HEIGHT - MARGIN,
BUTTON_WIDTH, BUTTON_HEIGHT, false,
(pressed) => {
if (pressed) {
onSpeedDown()
}
updateSpeedButtons(pressed, false)
})
uiContainer.addChild(entities.speedDown)
entities.speedUp = createButton("Fast\u2009>",
3 * MARGIN + BUTTON_WIDTH, height - BUTTON_HEIGHT - MARGIN,
BUTTON_WIDTH, BUTTON_HEIGHT, false,
(pressed) => {
if (pressed) {
onSpeedUp()
}
updateSpeedButtons(false, pressed)
})
uiContainer.addChild(entities.speedUp)
showControls(isGameRunning())
uiContainer.interactive = true
uiContainer.on('tap', listenerGlobalTap)
uiContainer.hitArea = new PIXI.Rectangle(0, 0, width, height)
app.stage.addChild(uiContainer)
}
function showControls(show) {
entities.longButton.visible =
entities.neutralButton.visible =
entities.shortButton.visible =
entities.speedUp.visible =
entities.speedDown.visible =
show
}
function updateSpeedButtons(downPressed = false, upPressed = false) {
entities.speedDown.tint = entities.speedDown.label.style.fill = input.speedLevel > 0 ?
(downPressed ? COLOR_BUTTON_PRESSED : COLOR_BUTTON_INACTIVE) : COLOR_BUTTON_DISABLED
entities.speedUp.tint = entities.speedUp.label.style.fill = input.speedLevel < SPEED_LEVELS.length - 1 ?
(upPressed ? COLOR_BUTTON_PRESSED : COLOR_BUTTON_INACTIVE) : COLOR_BUTTON_DISABLED
}
function updateTexts() {
entities.messages.summary.text = texts.summary
entities.messages.iteration.text = texts.iteration
entities.messages.funds.text = texts.funds
if (SHOW_PRICE) {
entities.messages.price.text = texts.price
}
if (SHOW_DEBUG) {
entities.messages.debug.text = texts.debug
}
if (SHOW_FPS) {
entities.messages.fps.text = texts.fps
}
}
// ===== update loop =====
function update(dt) {
if (!gameStarted || paused) {
return
}
targetSpeed = SPEED_LEVELS[input.speedLevel]
targetzoom = ZOOM_LEVELS[input.speedLevel]
if (speed < targetSpeed) {
speed = Math.min(targetSpeed, speed + WARP_SPEED_DELTA)
zoom = Math.min(targetzoom, zoom + WARP_ZOOM_DELTA)
} else if (speed > targetSpeed) {
speed = Math.max(targetSpeed, speed - WARP_SPEED_DELTA)
zoom = Math.max(targetzoom, zoom - WARP_ZOOM_DELTA)
}
// 60 is the target fps
time += dt / (speed * 60 / TICKS_PER_DAY)
var i = Math.floor(time)
if (i >= GAME_LENGTH_TICKS) {
if (!gameOver) {
gameOver = true
gameStarted = false
onGameOver()
}
return
}
if (i > tick) {
tick = i
handleInput(tick)
}
var x = time * GRAPH_X_GRANULARITY_PX
var y = Y_SCALE_FACTOR * priceData.scale * ((priceData.series[tick] - priceData.series[0])
+ (time - tick) * (priceData.series[tick + 1] - priceData.series[tick]))
if (assets.trade) {
recalculateTrade(assets.trade, tick)
updateTrade(assets.trade, x, y)
}
entities.graph.mask.position.x = x
setViewPort(x, (viewPortY + (y - viewPortY) / SMOOTH_FACTOR_Y), OFFSET_X)
updatePlayer(x, y)
updateMessages(tick)
}
function setViewPort(x, y, xOffset) {
viewPortX = x
viewPortY = y
entities.gamespace.scale.x = zoom
entities.gamespace.scale.y = -zoom
entities.gamespace.position.x = -(x * zoom - screenWidth / 2 - (screenWidth * xOffset))
entities.gamespace.position.y = -(-y * zoom - screenHeight / 2)
}
function updatePlayer(x, y) {
entities.player.x = x
entities.player.y = y
entities.player.alpha = assets.trade ? 0.5 : 0.2
}
function startGame() {
texts.summary = ''
updateTexts()
entities.logos.visible = false
entities.smallLogo.visible = true
showControls(true)
gameStarted = true
pauseGame(false)
}
function pauseGame(p) {
paused = entities.messages.pause.visible = p && isGameRunning()
}
function onSpeedUp() {
input.speedLevel = Math.min(input.speedLevel + 1, SPEED_LEVELS.length - 1)
}
function onSpeedDown() {
input.speedLevel = Math.max(input.speedLevel - 1, 0)
}
function onLong() {
input.short = false
input.long = true
entities.longButton.tint = COLOR_BUTTON_ACTIVE
entities.neutralButton.tint = COLOR_BUTTON_INACTIVE
entities.shortButton.tint = COLOR_BUTTON_INACTIVE
}
function onShort() {
input.short = true
input.long = false
entities.longButton.tint = COLOR_BUTTON_INACTIVE
entities.neutralButton.tint = COLOR_BUTTON_INACTIVE
entities.shortButton.tint = COLOR_BUTTON_ACTIVE
}
function onNeutral() {
input.long = false
input.short = false
entities.longButton.tint = COLOR_BUTTON_INACTIVE
entities.neutralButton.tint = COLOR_BUTTON_ACTIVE
entities.shortButton.tint = COLOR_BUTTON_INACTIVE
}
function handleInput(i) {
if (input.long && !input.short) {
// LONG
if (assets.trade) {
if (assets.trade.isLong) {
return
} else {
exitTrade(i)
}
}
enterTrade(true, i, assets.funds)
} else if (!input.long && input.short) {
// SHORT
if (assets.trade) {
if (!assets.trade.isLong) {
return
} else {
exitTrade(i)
}
}
enterTrade(false, i, assets.funds)
} else {
// NEUTRAL
if (assets.trade) {
exitTrade(i)
}
}
}
function updateMessages(i) {
texts.summary = ''
texts.iteration = 'Day ' + (Math.floor(i / TICKS_PER_DAY) + 1) + ' of ' + GAME_LENGTH_DAYS
var equity = assets.funds + (assets.trade ? assets.trade.current : 0)
texts.funds = 'Equity $' + Math.round(equity)
if (SHOW_PRICE) {
texts.price = 'price: $' + Math.round(priceData.series[i])
}
if (SHOW_DEBUG) {
texts.debug =
'inputs:' + (input.short?'S':' ') + (input.long?'L':' ') + (input.warp?'W':' ') + ' S' + (input.speedLevel+1)
+ '\nspeed:' + speed.toFixed(2) + ' (sec/day @ 60fps)'
+ '\nzoom:' + zoom.toFixed(2)
+ '\ntick:' + tick
+ ' x:' + viewPortX.toFixed(2)
+ ' y:' + viewPortY.toFixed(2)
if (assets.trades.length > (assets.trade ? 1 : 0)) {
let lastTrade = assets.trades[assets.trades.length - (assets.trade ? 2 : 1)]
texts.debug +=
'\n\nLast: ' + (lastTrade.isLong ? 'LONG' : 'SHORT')
+ '\n bar:(' + lastTrade.barOpen + ' \u2192 ' + lastTrade.barClose + ')'
+ '\n price:(' + lastTrade.priceOpen.toFixed(2) + ' \u2192 ' + lastTrade.priceClose.toFixed(2) + ')'
+ '\n profit:' + (lastTrade.current - lastTrade.margin).toFixed(2)
}
if (assets.trade) {
let currentTrade = assets.trade
texts.debug +=
'\n\nCurrent: ' + (currentTrade.isLong ? 'LONG' : 'SHORT')
+ '\n bar:(' + currentTrade.barOpen + ' \u2192 ' + currentTrade.barClose + ')'
+ '\n price:(' + currentTrade.priceOpen.toFixed(2) + ' \u2192 ' + currentTrade.priceClose.toFixed(2) + ')'
+ '\n profit:' + (currentTrade.current - currentTrade.margin).toFixed(2)
}
}
if (SHOW_FPS) {
fps = fps * 0.95 + app.ticker.FPS * 0.05
texts.fps = 'FPS:' + fps.toFixed(0) + ' (' + app.ticker.FPS.toFixed(2) + ')'
}
updateTexts()
}
function onGameOver() {
onNeutral()
showControls(false)
if (assets.trade) {
exitTrade(GAME_LENGTH_TICKS)
}
updateMessages(GAME_LENGTH_TICKS - 1)
const returns = playerReturns()
const hodl = hodlReturns()
setTimeout(() => {
if (!player) {
player = window.prompt('Nick name?') || 'anonymous';
}
gameOverLayout()
gameOverLayout.showContent(0)
let tradeList = selfTrades(assets.trades)
addScore(true, player, returns, assets.trades.length, tradeList)
addScore(false, HODL_NAME, hodl, 1, hodlTrades())
showScores()
saveResult(returns, hodl, tradeList)
})
}
function playerReturns() {
const profit = assets.funds - INIT_FUNDS
return profit / INIT_FUNDS
}
function hodlReturns() {
return priceData.series[GAME_LENGTH_TICKS] / priceData.series[0] - 1
}
function hodlTrades() {
return {
position: ["L"],
barOpen: [0],
barClose: [GAME_LENGTH_TICKS],
priceOpen: [priceData.series[0]],
priceClose: [priceData.series[GAME_LENGTH_TICKS]]
}
}
function selfTrades(trades) {
return {
position: trades.map(t => t.isLong ? 'L' : 'S'),
barOpen: trades.map(t => t.barOpen),
barClose: trades.map(t => t.barClose),
priceOpen: trades.map(t => t.priceOpen),
priceClose: trades.map(t => t.priceClose)
}
}
// ===== 'create' methods =====
function createGraph() {
const p0 = priceData.series[0]
const past = priceData.pastSeries.length
let graph = new PIXI.Graphics()
graph.lineStyle(2, COLOR_WHITE)
graph.position.set(0, 0)
for (let i = 0; i < priceData.series.length - 1; i++) {
graph
.moveTo(GRAPH_X_GRANULARITY_PX * i,
Y_SCALE_FACTOR * priceData.scale * (priceData.series[i] - p0))
.lineTo(GRAPH_X_GRANULARITY_PX * (i + 1),
Y_SCALE_FACTOR * priceData.scale * (priceData.series[i + 1] - p0))
}
graph.position.set(0, 0)
for (let i = 0; i < past; i++) {
graph.lineStyle(2, 0x666666, i / past)
.moveTo(GRAPH_X_GRANULARITY_PX * (i + 1 - past),
Y_SCALE_FACTOR * priceData.scale * (priceData.pastSeries[i] - p0))
.lineTo(GRAPH_X_GRANULARITY_PX * (i + 2 - past),
Y_SCALE_FACTOR * priceData.scale * (priceData.pastSeries[i + 1] - p0))
graph.addChild(graph)
}
// Note: you have to add both 'graph' and 'graph.mask' to the gamespace container
let width = (PAST_LENGTH_TICKS + GAME_LENGTH_TICKS) * GRAPH_X_GRANULARITY_PX
let yMin = Y_SCALE_FACTOR * priceData.scale * p0 * (Math.pow(0.9, BANDS) - 1)
let yMax = Y_SCALE_FACTOR * priceData.scale * p0 * (Math.pow(1.1, BANDS) - 1)
graph.mask = new PIXI.Graphics()
graph.mask.isMask = true
graph.mask.drawRect(-width, yMin, width, yMax - yMin)
return graph
}
function createButton(text, x, y, w, h, initialState, callback) {
const g = new PIXI.Graphics()
const txt = new PIXI.Text(text, TEXT_STYLE.clone())
txt.x = (w - txt.width) / 2
txt.y = (h - txt.height) / 2
g.addChild(txt)
g.label = txt
g.lineStyle(2, COLOR_BUTTON_INACTIVE, 1);
g.beginFill(COLOR_BUTTON_INACTIVE, 0.25);
g.drawRoundedRect(0, 0, w, h, 15);
g.endFill();
g.tint = initialState ? COLOR_BUTTON_ACTIVE : COLOR_BUTTON_INACTIVE
g.x = x
g.y = y
g.buttonMode = true
g.interactive = true
g.interactiveChildren = false
g.buttonStates = new Set()
g.buttonLastState = false
// hacks to ensure reasonable multitouch behavior
const f = e => {
const release = e.type == 'pointerup' || e.type == 'pointerupoutside' || e.type =='pointercancel'
const pressing = !release && app.renderer.plugins.interaction.hitTest(e.data.global, g) && e.data.buttons == 1
const id = e.data.pointerId
if (pressing) {
g.buttonStates.add(id)
} else {
g.buttonStates.delete(id)
}
// console.log(text, pressing, g.buttonStates, e.type, id)
const state = g.buttonStates.size != 0
if (g.buttonLastState != state) {
g.buttonLastState = state
callback(state)
}
}
g.on('pointermove', f)
g.on('pointerdown', f)
g.on('pointerup', f)
g.on('pointerupoutside', f)
g.on('pointercancel', f)
return g
}
function createMessages(width, height, margin) {
let messagesContainer = new PIXI.Container()
let messages = {}
const ROW_HEIGHT = 30
let x = margin
let y = margin
messages.iteration = new PIXI.Text(texts.iteration, TEXT_STYLE)
messages.iteration.position.set(x, y)
messagesContainer.addChild(messages.iteration)
y += ROW_HEIGHT
messages.funds = new PIXI.Text(texts.funds, TEXT_STYLE)
messages.funds.position.set(x, y)
messagesContainer.addChild(messages.funds)
y += ROW_HEIGHT
if (SHOW_PRICE) {
messages.price = new PIXI.Text(texts.price, TEXT_STYLE)
messages.price.position.set(x, y)
messagesContainer.addChild(messages.price)
y += ROW_HEIGHT
}
if (SHOW_DEBUG) {
let style = TEXT_STYLE.clone()
style.align = 'left'
style.fontSize = 20
messages.debug = new PIXI.Text(texts.debug, style)
messages.debug.position.set(x, y + ROW_HEIGHT)
messagesContainer.addChild(messages.debug)
}
if (SHOW_FPS) {
let style = TEXT_STYLE.clone()
style.fontSize = 16
messages.fps = new PIXI.Text(texts.fps, style)
messages.fps.anchor.set(0.5, 0.0)
messages.fps.position.set(width / 2, margin)
messagesContainer.addChild(messages.fps)
}
messages.summary = new MultiStyleText(texts.summary, TEXT_MULTI_STYLE)
messages.summary.position.set(width / 2, height / 2 + margin)
messages.summary.anchor.set(0.5, 0.0)
messagesContainer.addChild(messages.summary)
{
let style = TEXT_STYLE.clone()
style.fontSize = 48
messages.pause = new PIXI.Text('PAUSED', style)
messages.pause.anchor.set(0.5, 0.5)
messages.pause.position.set(width / 2, height / 2)
messages.pause.visible = paused
messagesContainer.addChild(messages.pause)
}
return {messagesContainer, messages}
}
function createLogos(width, height, margin) {
let logoContainer = new PIXI.Container()
let logo = new PIXI.Sprite.from('logo_vertical.png')
logo.position.set(width / 2, height / 2 - margin)
logo.anchor.set(0.5, 1.0)
logoContainer.addChild(logo)
let createdBy = new PIXI.Sprite.from('created.png')
createdBy.position.set(margin, height - margin)
createdBy.anchor.set(0.0, 1.0)
createdBy.scale.set(0.5)
createdBy.interactive = true
createdBy.buttonMode = true
createdBy.on('click', () => { window.location.href = 'https://decent.org/' })
createdBy.on('tap', () => { window.location.href = 'https://decent.org/' })
logoContainer.addChild(createdBy)
if (document.fullscreenEnabled && document.exitFullscreen && app.view.requestFullscreen) {
let fullscreen = new PIXI.Sprite.from(!document.fullscreenElement ?
'fullscreen_enter.png' : 'fullscreen_exit.png')
fullscreen.position.set(margin, margin)
fullscreen.anchor.set(0.0, 0.0)
fullscreen.scale.set(0.25)
fullscreen.interactive = true
fullscreen.buttonMode = true
fullscreen.on('click', toggleFullScreen)
fullscreen.on('tap', toggleFullScreen)
logoContainer.addChild(fullscreen)
}
logoContainer.visible = isMainScreen()
return logoContainer
}
function toggleFullScreen() {
if (!document.fullscreenElement && app.view.requestFullscreen) {
app.view.requestFullscreen()
} else if (document.exitFullscreen) {
document.exitFullscreen()
}
}
function createSmallLogo(width, height, margin) {
let logo = new PIXI.Sprite.from('logo.png')
logo.position.set(width - margin, margin)
logo.anchor.set(1.0, 0.0)
logo.scale.set(0.5)
logo.visible = !isMainScreen()
return logo
}
function createScreenShotButton() {
if (HTMLCanvasElement && HTMLCanvasElement.prototype && HTMLCanvasElement.prototype.toBlob) {
let screenshot = new PIXI.Sprite.from('screenshot.png')
screenshot.anchor.set(0.0, 0.0)
screenshot.scale.set(0.125)
screenshot.interactive = true
screenshot.buttonMode = true
screenshot.on('click', () => { screenShot(app.view, entities.messages.highscores) })
screenshot.on('tap', () => { screenShot(app.view, entities.messages.highscores) })
screenshot.visible = isGameOverScreen()
return screenshot
} else {
return null
}
}
function createGrid() {
let grid = new PIXI.Container()
const p0 = priceData.series[0]
const gradHeight = 256
const grad = gradientTexture(1, gradHeight)
const alpha = 0.12
let ppi = p0
for (let i = 1; i <= BANDS; i++) {
let prevY = Y_SCALE_FACTOR * priceData.scale * (ppi - p0)
ppi *= 1.1
let y = Y_SCALE_FACTOR * priceData.scale * (ppi - p0)
var sprite = new PIXI.Sprite(grad)
sprite.x = -PAST_LENGTH_TICKS * GRAPH_X_GRANULARITY_PX
sprite.y = prevY
sprite.anchor.set(0.0, 0.0)
sprite.alpha = alpha - (i * alpha / BANDS)
sprite.scale.set((PAST_LENGTH_TICKS + GAME_LENGTH_TICKS) * GRAPH_X_GRANULARITY_PX, (y - prevY) / gradHeight)
grid.addChild(sprite)
}
let pmi = p0
for (let i = 1; i <= BANDS; i++) {
let prevY = Y_SCALE_FACTOR * priceData.scale * (pmi - p0)
pmi *= 0.9
let y = Y_SCALE_FACTOR * priceData.scale * (pmi - p0)
var sprite = new PIXI.Sprite(grad)
sprite.x = -PAST_LENGTH_TICKS * GRAPH_X_GRANULARITY_PX
sprite.y = y
sprite.anchor.set(0.0, 0.0)
sprite.alpha = alpha - (i * alpha / BANDS)
sprite.scale.set((PAST_LENGTH_TICKS + GAME_LENGTH_TICKS) * GRAPH_X_GRANULARITY_PX, (prevY - y) / gradHeight)
grid.addChild(sprite)
}
let days = new PIXI.Graphics()
const mul = TICKS_PER_DAY * GRAPH_X_GRANULARITY_PX
for (let i = -PAST_LENGTH_DAYS; i <= GAME_LENGTH_DAYS; i++) {
days.lineStyle(2, i < 0 ? COLOR_GREY_DARK_2 : (i == 0 ? COLOR_GREY_DARK_4 : 0x333333))
.moveTo(i * mul, Y_SCALE_FACTOR * priceData.scale * (pmi - p0))
.lineTo(i * mul, Y_SCALE_FACTOR * priceData.scale * (ppi - p0))
}
grid.addChild(days)
return grid
}
function gradientTexture(w, h) {
var canvas = document.createElement('canvas')
canvas.width = w
canvas.height = h
var ctx = canvas.getContext('2d')
var gradient = ctx.createLinearGradient(0, 0, 0, h)
gradient.addColorStop(0, '#000000')
gradient.addColorStop(1, '#ffffff')
ctx.fillStyle = gradient
ctx.fillRect(0, 0, w, h)
return PIXI.Texture.fromCanvas(canvas)
}
function createPlayer() {
let player = new PIXI.Graphics()
player.alpha = 0.2
player.lineStyle(4, COLOR_WHITE)
player.drawCircle(0, 0, 8)
player.endFill()
return player
}
// ===== trades =====
function enterTrade(isLong, i, margin) {
assets.trade = {}
assets.trade.isLong = isLong
assets.trade.barOpen = assets.trade.barClose = i
assets.trade.priceOpen = assets.trade.priceClose = priceData.series[i]
assets.trade.margin = margin
assets.trade.current = margin
assets.funds = assets.funds - margin
assets.trades.push(assets.trade)
}
function exitTrade(i) {
if (!assets.trade) {
return
}
recalculateTrade(assets.trade, i)
updateTrade(assets.trade, GRAPH_X_GRANULARITY_PX * i,
Y_SCALE_FACTOR * priceData.scale * (priceData.series[i] - priceData.series[0]))
assets.funds = assets.funds + assets.trade.current
assets.trade = null
}
function recalculateTrade(trade, i) {
if (!trade) {
return
}
trade.barClose = i
trade.priceClose = priceData.series[i]
// TODO: interpolate estimated price between ticks
const longValue = trade.margin * trade.priceClose / trade.priceOpen
if (trade.isLong) {
trade.current = longValue
} else {
// assets.margin dolcsi ertekben kolcsonkertem bitcoint, es rogton eladtam
// ennyi bitcoint adtam el eredetileg:
// assets.margin / assets.strikePrice
// === ennyit kell visszaadjak ma
// nekem meg megvan az eredeti assets.margin dolcsim
// abbol megveszem a bitcoint mai aron, es a kulonbozetet megnyertem!
// bwahahaha
trade.current = 2 * trade.margin - longValue
}
}
function updateTrade(trade, x, y) {
const profit = Math.round(trade.current - trade.margin)
// update label
if (!trade.label) {
trade.label = new PIXI.Text('', TEXT_STYLE)
trade.label.scale.set(1, -1)
trade.label.anchor.set(0.25, 0.5)
entities.tradelabels.addChild(trade.label)
}
trade.label.position.set(x, trade.isLong ? y + 20 : y - 25)
trade.label.style = profit < 0 ? TEXT_LOSS_STYLE : TEXT_PROFIT_STYLE
trade.label.text
= (profit < 0 ? '-$' : '+$')
+ Math.abs(profit)
+ (trade.isLong ? '\u25B3' : '\u25BD')